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深浅拷贝的理解

1,浅拷贝是什么? 浅拷贝是对于一个对象的顶层拷贝,通俗的理解是:拷贝了引用,并没有拷贝内容 通过a=b这种方式赋值只是赋值的引用(内存地址),a和b都指向了同一个内存空间,所...

python逐行读写txt文件的实例讲解

实例如下所示: # -*-coding:utf-8-*- import os file_obj = open("test2.txt") all_lines = file_obj.re...

使用python脚本实现查询火车票工具

使用python脚本实现查询火车票工具

使用python脚本实现查询火车票信息的效果图如下: 实现的代码: # coding: utf-8 """命令行火车票查看器 Usage: tickets [-gdtkz] O...

pandas中read_csv的缺失值处理方式

今天遇到的问题是,要将一份csv数据读入dataframe,但某些列中含有NA值。对于这些列来说,NA应该作为一个有意义的level,而不是缺失值,但read_csv函数会自动将类似的缺...

基于python3 OpenCV3实现静态图片人脸识别

基于python3 OpenCV3实现静态图片人脸识别

本文采用OpenCV3和Python3 来实现静态图片的人脸识别,采用的是Haar文件级联。 首先需要将OpenCV3源代码中找到data文件夹下面的haarcascades文件夹里...