py开发的ping命令

  • 格式:docx
  • 大小:11.21 KB
  • 文档页数:2

#!/usr/bin/python
#_*_coding:utf-8_*_
import sys
import os
import time
import string
from threading import Thread
class PING(Thread):
def __init__(self,ip):
Thread.__init__(self)
self.ip=ip
def run(self):
if =="nt":
output=os.popen("ping -n 1 %s" % (self.ip)).read().split("\r\n")
if "0%" in output:
print "%s used" % self.ip
else:
pass
elif os.uname()[0] == "Linux":
output=os.popen("ping -c 2 -w 3 %s" % (self.ip)).read() if -1==output.find("100% packet loss"):
print "%s used\r" % self.ip
else:
print ("%s is ERROR" %(self.ip))
T_thread=[]
Ip_addr=[]
def usage():
print 'Usage : python ping.py START_IP END_IP [THREAD_COUNT]'
if len(sys.argv)!=3 and len(sys.argv)!=4:
usage()
sys.exit(0)
ip1=sys.argv[1]
ip2=sys.argv[2]
MAX_THREAD_COUNT=300
if len(sys.argv)==4:
MAX_THREAD_COUNT=sys.argv[3]
print 'The IP Range is :'+ip1+'~'+ip2
ip1s=ip1.split('.')
ip2s=ip2.split('.')
if len(ip1s)!=4 or len(ip2s)!=4:
print 'IP ERROR!'
usage()
sys.exit(0)
ip="%s.%s." %(ip1s[0],ip1s[1])
num31=int(ip1s[2])
num32=int(ip2s[2])
num41=int(ip1s[3])
num42=int(ip2s[3])
for i in range(num31,num32+1):
if i==num31 & i!=num32:
for j in range(num41,255):
test=ip+str(i)+"."+str(j)
Ip_addr.append(test)
elif i==num32 & i!=num31:
for j in range(1,num42+1):
test=ip+str(i)+"."+str(j)
Ip_addr.append(test)
elif i==num31 & i==num32:
for j in range(num41,num42+1):
Ip_addr.append(ip+str(i)+"."+str(j)) else:
for j in range(1,255):
test=ip+str(i)+"."+str(j)
Ip_addr.append(test)
for i in Ip_addr:
t=PING(i)
T_thread.append(t)
thread_count=0
for i in range(len(T_thread)):
if thread_count > MAX_THREAD_COUNT:
thread_count = 0
time.sleep(2)
T_thread[i].start()
thread_count += 1。