这篇文章主要介绍Python如何判断telnet通不通,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
这个跟ping那个差不多,ping的那个脚本就是通过这个改了下,大体一致,不过telnet的不需要判断返回的字符串。快一些
这里具体需要telnet的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通不通”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。