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

相关文章

python实现通过队列完成进程间的多任务功能示例

python实现通过队列完成进程间的多任务功能示例

本文实例讲述了python实现通过队列完成进程间的多任务功能。分享给大家供大家参考,具体如下: 1.通过队列完成进程间的多任务 import multiprocessing de...

实例讲解python函数式编程

函数式编程是使用一系列函数去解决问题,按照一般编程思维,面对问题时我们的思考方式是“怎么干”,而函数函数式编程的思考方式是我要“干什么”。 至于函数式编程的特点暂不总结,我们直接拿例子来...

python指定写入文件时的编码格式方法

实例如下: #encoding=utf-8 content=u"广东松炀再生资源股份有限" content=content.encode("utf-8")#写入的文件编码格式为utf...

python脚本执行CMD命令并返回结果的例子

python脚本执行CMD命令并返回结果的例子

最近写脚本的时想要用python直接在脚本中去执行cmd命令,并且将返回值打印出来供下面调用,所以特意查了下,发现主要有一下几种方式来实现,很简单: 就拿执行adb, adb shell...

Python实现迭代时使用索引的方法示例

本文实例讲述了Python实现迭代时使用索引的方法。分享给大家供大家参考,具体如下: 索引迭代 Python中,迭代永远是取出元素本身,而非元素的索引。 对于有序集合,元素确实是有索引的...