使用Python编写一个IP端口扫描工具

使用Python编写一个IP端口扫描工具?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

# -*- coding:utf8 -*-
import socket, time, thread
import os
from time import sleep
socket.setdefaulttimeout(1)
def socket_port(ip,port):
 try:
  if port>=65535:
   return 
  s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  result=s.connect_ex((ip,port))
  if result==0:
   lock.acquire()
   print ip,u':',port,u'端口开放'
   lock.release()
  s.close()
 except Exception,e:
  pass
def ip_scan(ip):
 """
 输入IP,扫描IP的0-65534端口情况
 """
 try:
  print u'开始扫描 %s' % ip
  start_time=time.time() 
  for j in range(0,660):
   for i in range(j*100,100*(j+1)):
    thread.start_new_thread(socket_port,(ip,int(i)))
   sleep(0.1)#休眠 防止线程创建的过多报错(can not create new start thread)
  print u'扫描端口完成,总共用时 :%.2f' %(time.time()-start_time)
 except Exception,e :
  print u'扫描ip出错'
if __name__=='__main__':
 lock=thread.allocate_lock()
 ip_scan('192.168.3.37')

运行结果:

使用Python编写一个IP端口扫描工具

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。