您现在的位置是:首页 > 文章详情

扫描端口占用情况的python脚本

日期:2017-06-21点击:469

    之前项目上线前,领导要求让写一个脚本用来判断端口的占用情况。由于现在python3使用也比较多,基于python2修改了一下,做了个python3版本的,现在做一下总结。

一、python脚本实现扫描端口:

    pthon2下代码如下(当时的环境):

#!/usr/bin/env python # -*- coding:utf-8 -*- # used for pthon2.*    import socket, time, thread socket.setdefaulttimeout(3) #设置默认超时时间   def socket_port(ip, port): """           输入IP和端口号,扫描判断端口是否占用 """ try: if port >=65535: print u'端口扫描结束' 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() except: print u'端口扫描异常'   def ip_scan(ip): """      输入IP,扫描IP的0-65534端口情况 """ try: print u'开始扫描 %s' % ip start_time=time.time() for i in range(0,65534): thread.start_new_thread(socket_port,(ip, int(i))) print u'扫描端口完成,总共用时:%.2f' %(time.time()-start_time)  #        raw_input("Press Enter to Exit") except: print u'扫描ip出错'   if __name__=='__main__': url=raw_input('Input the ip you want to scan: ') lock=thread.allocate_lock() ip_scan(url)

        效果图:

    wKiom1lKNMixnGGfAABDtYb7fIA745.png-wh_50

    python3的代码:

#!/usr/bin/env python # -*- coding:utf-8 -*- # used  for python3.* import socket,time,_thread socket.setdefaulttimeout(3) #设置默认超时时间 def socket_port(ip, port): """ 输入IP和端口号,扫描判断端口是否占用 """ try: if port >=65535: print (u'端口扫描结束') 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() except: print (u'端口扫描异常')    def ip_scan(ip): """ 输入IP,扫描IP的0-65534端口情况 """ try: print (u'开始扫描 %s' % ip) start_time=time.time() for i in range(0,65534): _thread.start_new_thread(socket_port,(ip, int(i))) print (u'扫描端口完成,总共用时:%.2f' %(time.time()-start_time))     # raw_input("Press Enter to Exit") except: print (u'扫描ip出错')    if __name__=='__main__': url=input('Input the ip you want to scan: ') lock=_thread.allocate_lock() ip_scan(url)

    效果:

    wKiom1lKNYOh2GtpAABwqoRjik8857.png二、linux命令判断

    1. lsof -i:端口号   用于查看指定端口号的占用情况,如下查看80端口的情况。

wKioL1lKNuDw8nIVAAAkIWYgxks058.png    2.netstat -tunlp |grep 端口号,用于查看指定的端口号的进程情况,如查看25端口的情况,netstat -tunlp |grep 25

wKiom1lKN7iA4vaYAABGY_J4_4o959.png三、写python脚本中出现的问题

   1.ImportError: No module named 'thread'

    说没有thread这个模块,python3中没有了thread模块,取而代之的是_thread和threading(推荐使用),_thread是为了过渡使用的。

  2.IndentationError: unindent does not match any outer indentation level

    百度后发现原因是因为混用了空格和tab。

    tab键设置为4位。vim  /etc/vimrc  增加set ts=4

  3.关于python2与python3的区别

    请查看该篇文章http://www.cnblogs.com/hanggegege/p/5840005.html


原文链接:https://blog.51cto.com/babyhanggege/1940700
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章