Python判断telnet通不通的实例

yipeiwu_com5年前Python基础

这个跟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通不通的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

天翼开放平台免费短信验证码接口使用实例

对于目前众多的验证码解决方案来说,这个API有着中国电信这个重量级的运营商为靠山,应该是比较靠谱的了,而且还是免费的。详细情况请参阅:http://open.189.cn 使用方式:#定...

Python中用sleep()方法操作时间的教程

 mktime()方法是localtime()反函数。它的参数是struct_time或全9元组,它返回一个浮点数,为了兼容时time()。 如果输入值不能表示为有效的时间,那...

python简单验证码识别的实现方法

python简单验证码识别的实现方法

利用SVM向量机进行4位数字验证码识别        主要是思路和步骤如下: 一,素材收集 检查环境是否包含有相应的库: 1....

分享几道你可能遇到的python面试题

本文主要给大家介绍的是关于最近在面试中遇到的几个python面试题,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 一、生成斐波那契数列并取前10项 def func...

C#返回当前系统所有可用驱动器符号的方法

本文实例讲述了C#返回当前系统所有可用驱动器符号的方法。分享给大家供大家参考。具体如下: // The initial C# code for the "plain" WMI que...