• python程序检测Linux主机端口占用


    监测指定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

    ps:摘自https://www.cnblogs.com/wangtao1993/p/6144183.html

    如有帮助希望点个推荐;如果没帮助到或者内容有错误,可以下面留言,谢谢!
  • 相关阅读:
    PHP面试:实现动态获取函数参数的方法
    PHP面试:什么是类的多态性,请写出一个例子
    php相关操作
    客户端app支付宝登录接口
    商品分类设计
    Git连接远程服务器
    iptables/mysql设置指定主机访问指定端口
    CMake安装grpc生成gRPCTargets.cmake文件
    Linux下Springboot解决`APR based Apache Tomcat Native library`提示
    java双重检测或枚举类实现线程安全单例(懒汉模式)
  • 原文地址:https://www.cnblogs.com/ZhaoHS/p/15592025.html
Copyright © 2020-2023  润新知