循环检测服务器某个端口是否开放

脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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验证通过。