• Telnet登陆网络设备执行命令脚本


    # !/usr//bin/python3
    # -*- coding:UTF-8 -*-
    
    from telnetlib import Telnet
    import time, os, datetime, json
    import logging
    
    
    class TelnetClient():
    
        def __init__(self):
            self.tn = Telnet()
    
        def __login_host(self, ip, username, password, enable=None, verbose=True):
            try:
                self.tn.open(ip, port=23)
            except:
                logging.warning('%s网络连接失败' % ip)
                return False
            self.tn.read_until(b'Username:', timeout=1)
            self.tn.write(b'\n')
            self.tn.write(username.encode() + b'\n')
            rely = self.tn.expect([], timeout=1)[2].decode().strip()  # 读显
            if verbose:
                print(rely)
            self.tn.read_until(b'Password:', timeout=1)
            self.tn.write(password.encode() + b'\n')
            rely = self.tn.expect([], timeout=1)[2].decode().strip()
            if verbose:
                print(rely)
            if enable is not None:
                self.tn.write(b'enable\n')
                self.tn.write(enable.encode() + b'\n')
                if verbose:
                    rely = self.tn.expect([], timeout=1)[2].decode().strip()
                    print(rely)
                    time.sleep(1)
            time.sleep(2)
            rely = self.tn.read_very_eager().decode()
            if 'Login invalid' not in rely:
                logging.warning('%s登陆成功' % ip)
                return True
            else:
                logging.warning('%s登陆失败,用户名或密码错误' % ip)
                return False
    
        def __do_cmd(self, cmd, location=None):
            if location:
                os.system('mkdir backup\\{}'.format(location))
                with open('backup/{}/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f:
                    self.tn.write(cmd.encode().strip() + b'\n')
                    time.sleep(3)
                    rescmd = self.tn.read_very_eager().decode()
                    f.write(rescmd)
                    logging.warning('命令执行结果:\n %s' % rescmd)
                return True
            else:
                os.system('mkdir backup')
                with open('backup/configuration_{}.txt'.format(location, datetime.date.today()), 'w') as f:
                    self.tn.write(cmd.encode().strip() + b'\n')
                    time.sleep(3)
                    rescmd = self.tn.read_very_eager().decode()
                    f.write(rescmd)
                    logging.warning('命令执行结果:\n %s' % rescmd)
                return True
    
        def telnet_login(self, ip, user, pwd, enable=None, cmd=None, location=None):
            res1 = self.__login_host(ip, user, pwd, enable)
            if res1:
                for i in cmd.split(';'):
                    self.__do_cmd(i, location)
                self.__logout_host()
                return True
            else:
                self.__logout_host()
                return False
    
        def __logout_host(self):
            self.tn.close()
    
    
    if __name__ == '__main__':
        username = 'cisco'  # 用户名
        password = 'cisco'  # 密码
        # 存放设备登陆信息和要执行的命令(多条命令用;隔开),示例:["ip", "username", "password", "enable_password", "terminal length 0;show run", "backup_path"]
        lists = 'list.text'
        with open('test.txt', 'rt', encoding='utf-8') as list_obj:
            # textline = list_obj.readline()
            # while textline != '':
            #     print(json.loads(textline))
            #     textline = list_obj.readline()
            telnet_client = TelnetClient()
            for line in list_obj:
                hostmsg = json.loads(line)
                telnet_client.telnet_login(hostmsg[0], hostmsg[1], hostmsg[2], hostmsg[3], hostmsg[4])
  • 相关阅读:
    PAT 2016 数据的交换输出
    HDU 2020 绝对值排序
    HDU 2013 蟠桃记
    HDU 2005 第几天?
    HDU 2004 成绩转换
    系统时钟初始化
    array_map 去除数组参数里面左右两端空格
    建立自己的异常类方式
    laravel withCount 统计关联数量
    laravel门面和服务提供者使用
  • 原文地址:https://www.cnblogs.com/xwupiaomiao/p/16111128.html
Copyright © 2020-2023  润新知