這篇文章主要介紹Python如何判斷telnet通不通,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
這個跟ping那個差不多,ping的那個腳本就是通過這個改了下,大體一致,不過telnet的不需要判斷返回的字符串??煲恍?/p>
這里具體需要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通不通”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。