学习python⑵:应用Python开发网络程序

import telnetlib
import time
import sys
import os.path
import configparser

class TelnetClient():
def init(self,):
self.tn = telnetlib.Telnet() # 定义一个Telnet连接

def Login(self,HostIP,Username,Password):                    # 给定参数进行连接
    try:
        self.tn.open(HostIP,port=23)                         # 连接
        self.tn.read_until(b'login: ',timeout=5)             # 等待login:出现,最多等待5秒
        self.tn.write(Username.encode('ascii') + b'\n')      # 输入用户名称
        self.tn.read_until(b'Password: ',timeout=5)          # 等待Password:出现,最多等待5秒
        self.tn.write(Password.encode('ascii') + b'\n')      # 输入用户口令
        time.sleep(2)                                        # 延时两秒
        Result = self.tn.read_very_eager().decode('ascii')   # 获取返回结果
        if '<'+Equipmentname+'>' in Result:
            return True                                      # 成功登陆
        else:
            self.Disconnect()
            self.StrErr = '连接地址:{}失败,用户名称或者密码错误。\r\n'.format(HostIP)
            return False                                     # 登陆失败
    except:
        self.StrErr='连接地址:{}失败!\r\n'.format(HostIP)    # 异常
        self.Disconnect()
        return False

def ExecuteCommand(self,command):                            # 执行命令
    Year = time.strftime('%Y', time.localtime(time.time()))
    Month = time.strftime('%m', time.localtime(time.time()))
    Day = time.strftime('%d', time.localtime(time.time()))
    Pathname, Filename = os.path.split(os.path.abspath(sys.argv[0]))
    SaveFile = Pathname + "\\" + Equipmentname + Year + Month + Day + ".txt"
    file_object = open(SaveFile, 'ab+')                           # 打开文件准备写
    file_object.write(Equipmentname.encode('ascii')+b"\r\n")      # 将返回的结果写入文件
    self.tn.write(command.encode('ascii')+b'\n')                  # 执行命令
    time.sleep(1)
    Result=self.tn.read_very_eager()
    while True:
        file_object.write(Result)                                 # 将返回的结果写入文件
        if not Result.find(StrMore.encode('ascii'))>0:
            break
        self.tn.write(b" ")                                       # 发送空格键
        time.sleep(1)
        Result=self.tn.read_very_eager()

def Logout(self):                                                 # 正常退出
    self.tn.write(b"exit\n")

def Disconnect(self):                                             # 异常关闭
    self.tn.close()

if name == 'main':
Equipmentname='' # 设备名称
HostIP = '' # IP地址
Username = '' # 用户名称
Password = '' # 密码
Command = [] # 命令集
CommandPrompt="" # 命令提示符
StrMore="-- More --"
conf = configparser.ConfigParser() # 定义一个读取对象
conf.read("NetConfig.ini") # 打开配置文件
sections = conf.sections() # 返回所有的section,列表
NewTelnetClient = TelnetClient() # 实例化
for section in sections:

lists = conf.items(section) # 得到sections的所有键值对,列表

    HostIP=section
    Equipmentname=conf.get(section, 'EquipmentName')
    Username=conf.get(section, 'Username')
    Password=conf.get(section, 'Password')
    Command=conf.get(section, 'CommandSet')
    Command=conf.get(section, 'CommandSet').split(',')
    if NewTelnetClient.Login(HostIP, Username, Password):  # 如果正常登录则执行命令,完成后退出
        print("设备:{},IP地址:{}".format(Equipmentname, HostIP))
        for S in Command:
            print("执行:",S)
            NewTelnetClient.ExecuteCommand(S)
        print("命令执行完毕!")
        NewTelnetClient.Logout()
    else:
        print(NewTelnetClient.StrErr)
    NewTelnetClient.Disconnect()
    time.sleep(2)

配置文件NetConfig.ini内容:

  [IP地址1]
  EquipmentName=设备名称
  Username=用户名称
  Password=用户密码
  CommandSet=dis mac-address,dis arp,......,dis cu

  [IP地址2]
  EquipmentName=设备名称
  Username=用户名称
  Password=用户密码
  CommandSet=dis mac-address,dis arp,......,dis cu

  ......

  [IP地址n]
  EquipmentName=设备名称
  Username=用户名称
  Password=用户密码
  CommandSet=dis mac-address,dis arp,......,dis cu

猜你喜欢

转载自blog.51cto.com/dawn0919/2631152