import telnetlib
from socket import*# 使用socketdefsocket_scan(host, port):
conn = socket(AF_INET, SOCK_STREAM)
conn.settimeout(2)try:
conn.connect((host, port))print(host, port,'is available')except Exception:print(host, port,'is not available')finally:
conn.close()# 使用telnetdeftelnet_scan(host, port):
t = telnetlib.Telnet()try:
t.open(host, port, timeout=2)print(host, port,'is available')except Exception:print(host, port,'is not available')finally:
t.close()defmain():
host ='127.0.0.1'for port inrange(80,90):
socket_scan(host, port)if __name__ =='__main__':
main()
运行结果
127.0.0.1 80 is not available
127.0.0.1 81 is not available
127.0.0.1 82 is not available
127.0.0.1 83 is not available
127.0.0.1 84 is not available
127.0.0.1 85 is not available
127.0.0.1 86 is not available
127.0.0.1 87 is not available
127.0.0.1 88 is not available
127.0.0.1 89 is not available