python3 查看端口打开情况

来源:互联网 发布:怎么强制删除mac软件 编辑:程序博客网 时间:2024/06/05 10:00

刚实习工作,学了一下python,发现python真的很不错,自己写了一个脚本,把自己电脑的端口看了一遍,希望大家多给一点建议,代码也写的不好,请多多指教

闲时无聊,就整了一个程序,把自己的电脑扫描了一下,关了一些不必要的端口

中间一开始发现很慢,后来利用了线程

但是老出现有时候有些端口没扫到,但是多扫几次就能扫到,不知道啥问题,希望老师求指点

# python3
import socket
from threading import Thread, activeCount

def port_scan(host, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #print(port)
    
    res = sock.connect_ex((host, port))
    if res == 0:
        print('port',port,'is open')
        sock.close()
    else:
        pass

def port():
    i = 1
    if activeCount() <= 100:
        for i in range(1, 65536):
            try:
                #port_scan(host, i)
                Thread(target = port_scan, args = (host, i)).start()
            except Exception as e:
                pass



if __name__ == '__main__':
    host = input('please enter your test ip:')
    port()
    print('scan success!')

    print('please take off the unnecessary port.')

可以参考一下连接

https://docs.python.org/2/library/socket.html

https://docs.python.org/3.4/library/threading.html

1 0