Python判断telnet通不通的实例

yipeiwu_com6年前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设计】。

相关文章

python实现五子棋人机对战游戏

python实现五子棋人机对战游戏

本文代码基于 python3.6 和 pygame1.9.4。 五子棋比起我之前写的几款游戏来说,难度提高了不少。如果是人与人对战,那么,电脑只需要判断是否赢了就可以。如果是人机对战,那...

python+pyqt5实现图片批量缩放工具

python+pyqt5实现图片批量缩放工具

批量修改图片大小好像用PS也可以,不过我不会,程序猿就用程序来解决。 这段时间学了下Python,很强大,之前一些不知道怎么处理的东西在Python里面都能找到解决方法。 工具界面如下...

pandas筛选某列出现编码错误的解决方法

如下所示: df = df[df['cityname']==u'北京市'] 记得,如果用的python2,一定要导入 import sys reload(sys) sy...

用Python实现随机森林算法的示例

拥有高方差使得决策树(secision tress)在处理特定训练数据集时其结果显得相对脆弱。bagging(bootstrap aggregating 的缩写)算法从训练数据的样本中建...

Python如何获取Win7,Win10系统缩放大小

这篇文章主要介绍了Python如何获取Win7,Win10系统缩放大小,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用pywin3...