玩蛇网提供最新Python编程技术信息以及Python资源下载!

python实现多线程Ping网段方法源码

python 培训

这是转贴,不是我写的python代码,也没测试过,只是给大家分享学习下,我也赚点积分嘿。
通过修改某站一个多线程PING的代码,来实现PING网段。
使用方法:fping 192.168.1.1-254

需要用到的python方法模块有:sys、subprocess、threadingQueue

import sys
import subprocess
from threading import Thread
from Queue import Queue

if sys.hexversion < 0x02040000:
        print >> sys.stderr, 'Your python version is too old (%s)' % \
                                                        (sys.version.split()[0])
        print >> sys.stderr, 'You need at least Python 2.4'
        sys.exit(1)
  
class CreateThread(Thread):
	def __init__(self, func, args, name=""):
		Thread.__init__(self)
		self.__name = name
		self.__func = func
		self.__args = args

	def run(self):
		apply(self.__func, self.__args)

class FPing(object):
	def __init__(self, network, tnum):
	        self.network = network
	        self.tnum = tnum

	def ip_process(self, network):
		start = network.split('-')[0].split('.')[3]
		end = network.split('-')[1]
		ip = network.split('-')[0].split('.')[ : 3]
		ip_3 = '.'.join(ip)
		return (start, end, ip_3)
	
	def check_grama(self, network):
		check = network.find('-')
		if check == -1:
			self.usage()
			sys.exit(1)
			
	def usage(self):
		print '''Usage: python fping.py ip-num
		example:
		python fping 192.168.1.1-255'''
	
	def ping_scan(self, num, iq, oq):
		while True:
			try:
				ip = iq.get()
				print "[*]Thread %s: Pinging %s" % (num, ip)
				ret = subprocess.call("ping -c 1 -w 3 %s" % ip, shell = True,
							stdout = open('/dev/null','w'), stderr = subprocess.STDOUT)
				if ret == 0:
					print "[*]%s: is alive." % ip
					oq.put(ip)
				else:
					print "[*]%s: did not respond" % ip
                                        oq.put(ip)
				iq.task_done()
                                oq.task_done()
			except Exception:
				print "Threading Exception !"
				sys.exit(1)

	def active(self):
		worker_num = self.tnum
		in_q = Queue()
		out_q = Queue()

		start, end, ip3 = self.ip_process(self.network)

		for ip1 in xrange(int(start), int(end) + 1):
			ip = ip3 + '.' + str(ip1)
			in_q.put(ip)

		for i in xrange(worker_num):
			worker = CreateThread(self.ping_scan, (i, in_q, out_q), self.ping_scan.__name__)
			worker.setDaemon(True)
			worker.start()
			
		print "[*]Main Thread Waiting."
		in_q.join()
		out_q.join()
		print "[*]Done!"

#www.iplaypython.com
if __name__ == '__main__':
	thread_worker_num = 10
	fping = FPing(sys.argv[1], thread_worker_num)
	if len(sys.argv) != 2:
		fping.usage()
		sys.exit(1)
	fping.active()

玩蛇网原创,转载请注明文章出处和来源网址:http://www.iplaypython.com/code/other/o2230.html



微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!

微信扫描下图可直接关注

玩蛇网Python新手QQ群,欢迎加入: ① 240764603 玩蛇网Python新手群
文章发布日期:2016-05-18 10:25 玩蛇网 www.iplaypython.com

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
相关文章推荐
别人正在看
特别推荐
去顶部去底部