Python实现Telnet连通性检测脚本
本文介绍使用Python编写Telnet连通性检测脚本的方法。通过telnetlib库尝试连接指定IP列表的23端口,根据成功或失败记录时间与状态至文件。脚本包含定时循环机制,每2秒执行一次检测,持续7200秒,并将结果保存至/root目录下的指定文本文件中,便于监控网络状态。
该脚本逻辑与ping检测类似,但无需解析返回字符串,因此执行效率更高。
需要检测的IP地址需预先定义在脚本中的数组内。
脚本设置了7200秒(即2小时)的定时循环检测机制。
具体代码实现如下:
#!/usr/bin/env python
# coding: utf8
import telnetlib
import time
import codecs
import os
# telnet host
def telnetdo(host, statusFile):
status1 = 'telnet success'
status2 = 'telnet faild'
for ipAdd in host:
# get now time
nowTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
try:
t = telnetlib.Telnet(ipAdd, port=23, timeout=1)
writeToText(nowTime, ipAdd, status1, statusFile)
except:
writeToText(nowTime, ipAdd, status2, statusFile)
# write status information to txt
def writeToText(nowTime, ipAdd, status, statusFile):
s_text = 'TIME:' + nowTime + '\t' + 'IP:' + ipAdd + '\t' + 'STATUS:' + status + '\r\n'
if '0' == judgeFile(statusFile):
with open(statusFile, 'a') as f:
f.write(s_text)
f.close()
if '1' == judgeFile(statusFile):
with open(statusFile, 'w') as f:
f.write(s_text)
f.close()
# Determine whether statusFile exists
# 0: exists
# 1: no exists
def judgeFile(statusFile):
if os.path.exists(statusFile):
return '0'
else:
return '1'
if __name__ == "__main__":
host = ['192.168.1.254', '192.168.1.100']
# write file
statusFile = '/root/telnetStatus.txt'
i = 7200
while i:
telnetdo(host, statusFile)
time.sleep(2)
i = i - 1
检测结果将保存至/root目录下。
以上为Python判断Telnet连通性的完整示例,供参考使用。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









