您当前的位置: 首页 >  网络

dawn

暂无认证

  • 5浏览

    0关注

    204博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

学习Python(6):应用Python开发网络程序

dawn 发布时间:2021-02-06 16:03:52 ,浏览量:5

  应用Python通过telent去操作网络设备,对网络管理员来说是很方便的。

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 '' 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

  上面的程序比较简单,可以获取网络设备的数据存到txt文件中,文件名称为设备名称加当前的时间。

  这个程序还可以优化,比如加入数据分析,提取所需要的数据进行汇总分析等等。

  PS:《网络安全和信息化》,2021年第7期,105页。

关注
打赏
1664252102
查看更多评论
立即登录/注册

微信扫码登录

0.2710s