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])

 常见网络设备命令结果全部显示

<H3C> screen-length disable     # no screen-length disable (华三)
Cisco# terminal length 0        # terminal no length (思科)
MaiPu# more off                 # more on (迈普)
<HuaWei> screen-length 0 temporary    # undo screen-length temporary (华为)
RuiJie# terminal length 0       # terminal no length (锐捷)
ZTE# terminal length 0          # no terminal length (中兴)

常见网络设备巡检命令
https://blog.csdn.net/qq_46417230/article/details/122336116

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值