Python实现定时检测服务器端口连通性
本文介绍使用Python编写定时任务以检测服务器端口连通性的方法。通过socket模块建立TCP连接,结合threading实现多线程定时检查,并设置超时机制避免阻塞。代码示例展示了如何封装检测逻辑并循环执行,适用于运维监控场景。
具体实现代码如下所示:
import socket
import threading
import time
def testconn( host , port ):
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(1)
try:
sk.connect((host,port))
return host+" Server is "+str(port)+" connect"
except Exception:
return host+" Server is "+str(port)+" not connect!"
sk.close()
class Test(threading.Thread):
def __init__(self):
pass
def test(self):
print testconn('172.31.32.3',22)
def run(self):
while True:
#print time.strftime('%Y-%m-%d %H:%M:%S')
self.test()
time.sleep(1)
a=Test()
a.run()
上述内容即为Python定时任务检测服务器端口连通性的完整示例,希望能为读者提供有价值的参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









