SoFunction
Updated on 2024-11-16

Example of Python determining whether telnet is working or not.

This is similar to the ping one, the ping script is changed by this, generally the same, but the telnet one does not need to judge the returned string. It's faster.

The specific ip you need to telnet to is the one you need to write to the defined array.

I've added a timer here, it's 7200 seconds, that's 2 hours

All right, get on the code:

#!/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 = ('%Y-%m-%d %H:%M:%S',(()))
 try:
  t = (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:
  (s_text)
  () 
 if '1' == judgeFile(statusFile):
 with open(statusFile, 'w') as f:
  (s_text)
  () 
 
 
  
# Determine whether statusFile exists 
# 0: exists
# 1: no exists
def judgeFile(statusFile):
 if (statusFile):
 return '0'
 else:
 return '1'
  
if __name__ == "__main__":
 host = ['192.168.1.254', '192.168.1.100']
 # write file
 statusFile = '/root/'
 i = 7200
 while i:
 telnetdo(host, statusFile)
 (2)
 i = i - 1

The result will exist under /root

The above example of this Python judgment telnet pass or fail is all that I have shared with you, I hope to give you a reference, and I hope you will support me more.