python 扫描 ip 端口占用

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# Create Time: 2019-03-12 01:51:48
# Last Modified: 2019-03-12 03:16:53

import socket
import time
import _thread as thread

socket.setdefaulttimeout(3)


def socket_port(ip, port):
    try:
        if port >= 65535:
            print("Port scan end!")
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = s.connect_ex((ip, port))
        if result == 0:
            lock.acquire()
            print(f"{ip}: {port} 已经占用")
            lock.release()
    except:
        print("Port scan error")


def ip_scan(ip):
    try:
        print("starting")
        start_time = time.time()
        for i in range(0, 65534):
            thread.start_new_thread(socket_port, (ip, int(i)))
        print("用时 %.2f" % (time.time()-start_time))
    except:
        print("scan error")


if __name__ == '__main__':
    url = input("input ip: ")
    lock = thread.allocate_lock()
    ip_scan(url)