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 DataFrame转dict字典过程详解

python DataFrame转dict字典过程详解

这篇文章主要介绍了python DataFrame转dict字典过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 背景:将商品i...

Python实现监控键盘鼠标操作示例【基于pyHook与pythoncom模块】

Python实现监控键盘鼠标操作示例【基于pyHook与pythoncom模块】

本文实例讲述了Python实现监控键盘鼠标操作。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import pythoncom import py...

Python3实现的简单三级菜单功能示例

Python3实现的简单三级菜单功能示例

本文实例讲述了Python3实现的简单三级菜单功能。分享给大家供大家参考,具体如下: 三级菜单_要求: 1. 运行程序输出第一级菜单 2. 选择一级菜单某项,输出二级菜单,同理输出三级菜...

Django项目使用ckeditor详解(不使用admin)

Django项目使用ckeditor详解(不使用admin)

效果图: 1.安装django-ckeditor pip install django-ckeditor 如果需要上传图片或者文件,还需要安装pillow pip insta...