脚本如下:
import socket
import datetime
import time
def check_port(host, port):
try:
socket.create_connection((host, port), timeout=1).close()
return True
except socket.error as e:
return False
host = '166.166.166.24'
port = 5236
while True:
with open('test.log', 'a') as file:
if check_port(host, port):
file.write(str(datetime.datetime.now()) + f" Port {port} on {host} is open.\n")
else:
file.write(str(datetime.datetime.now()) + f" Port {port} on {host} is closed or unreachable.\n")
file.close()
time.sleep(10)
站长已经使用python3.6验证通过。