监测指定IP的端口是否被占用
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 import socket, time, thread 5 socket.setdefaulttimeout(3) #设置默认超时时间 6 7 def socket_port(ip, port): 8 """ 9 输入IP和端口号,扫描判断端口是否占用 10 """ 11 try: 12 if port >=65535: 13 print u'端口扫描结束' 14 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) 15 result=s.connect_ex((ip, port)) 16 if result==0: 17 lock.acquire() 18 print ip,u':',port,u'端口已占用' 19 lock.release() 20 except: 21 print u'端口扫描异常' 22 23 def ip_scan(ip): 24 """ 25 输入IP,扫描IP的0-65534端口情况 26 """ 27 try: 28 print u'开始扫描 %s' % ip 29 start_time=time.time() 30 for i in range(0,65534): 31 thread.start_new_thread(socket_port,(ip, int(i))) 32 print u'扫描端口完成,总共用时:%.2f' %(time.time()-start_time) 33 # raw_input("Press Enter to Exit") 34 except: 35 print u'扫描ip出错' 36 37 if __name__=='__main__': 38 url=raw_input('Input the ip you want to scan: ') 39 lock=thread.allocate_lock() 40 ip_scan(url)
执行结果如下:
Input the ip you want to scan: 192.168.1.5 开始扫描 192.168.1.5 192.168.1.5 : 22 端口已占用 192.168.1.5 : 111 端口已占用 192.168.1.5 : 2181 端口已占用 192.168.1.5 : 8022 端口已占用 192.168.1.5 : 7923 端口已占用 192.168.1.5 : 8190 端口已占用 192.168.1.5 : 8009 端口已占用 192.168.1.5 : 8080 端口已占用 192.168.1.5 : 9081 端口已占用 192.168.1.5 : 9008 端口已占用 192.168.1.5 : 8761 端口已占用 192.168.1.5 : 9080 端口已占用 192.168.1.5 : 9526 端口已占用 192.168.1.5 : 9527 端口已占用 192.168.1.5 : 10189 端口已占用 192.168.1.5 : 10190 端口已占用 192.168.1.5 : 10191 端口已占用 192.168.1.5 : 38787 端口已占用 扫描端口完成,总共用时:7.46