admin管理员组

文章数量:1536366

telnet远程登录脚本

场景描述:有多台路由器,需要统一进行相关操作,比如统一shutdown局域口0/1。
如果每台路由器都进行telnet远程登录操作,即繁琐又麻烦。
因此有了以下登录操作脚本,python代码如下:
#coding:utf-8
from telnetlib import Telnet
import time
import logging

'''author fzuim'''

'''
路由器telnet执行远程命令类
指令统一采用encode UTF-8编码方式
使用方式:
1. 在.py同路径下,新建route_list.txt、cmd.txt
2. 在route_list.txt一行行输入顺序连接的IP列表
3. 在cmd.txt一行行输入顺序执行的命令
4. python 直接编译py文件运行即可
note: 适用于每个路由器登录和特权账号密码一致的情况,若不一致得改造下代码。
'''
class RouteTelnetClient():
    #初始化属性
    def __init__(self):
        self.tn = Telnet()

    #定义login_host函数,用于登陆设备
    def login_host(self, host, username, password, enable=None, shret=True):
        try:
            self.tn.open(host, port=23)
        except:
            logging.warning('%s网络连接失败' %host)
            return False

        #输入用户名
        self.tn.read_until(b'Username:', timeout=1)
        self.tn.write(b'\n')
        self.tn.write(username.encode() + b'\n')

        if shret:
            rely = self.tn.expect([], timeout=1)[2].decode().strip()
            print(rely)

        #输入密码
        self.tn.read_until(b'Password:', timeout=1)
        self.tn.write(password.encode() + b'\n')

        if shret:
            rely = self.tn.expect([], timeout=1)[2].decode().strip()
            print(rely)

        #判断是否进入特权模式
        if enable is not None:
            self.tn.write(b'enable\n')
            self.tn.write(enable.encode()+b'\n')
            if shret:
                rely = self.tn.expect([], timeout=1)[2].decode().strip()
                print(rely)
                time.sleep(1)

        rely = self.tn.read_very_eager().decode()
        if 'Login invalid' not in rely:
            logging.warning('%s->登陆成功' %host)
            return True
        else:
            logging.warning('%s->登陆失败,用户名或密码错误' %host)
            return False

    #定义do_cmd函数,用于执行命令
    def do_cmd(self, cmds):
        #读取文件,for语句循环执行命令
        try:
            with open(cmds) as cmd_obj:
                for cmd in cmd_obj:
                    self.tn.write(cmd.encode().strip() + b'\n')
                    time.sleep(2)
                    rely = self.tn.read_very_eager().decode()
                    logging.warning('命令执行结果:\n %s' %rely)
        except IOError as e:
            logging.error('open %s failed:%s.\n' %(cmd, e))
    
    #定义logout_host函数,关闭程序
    def logout_host(self):
        self.tn.close()

#定义了入口函数
if __name__ == '__main__':
    username    = 'admin'  	        #用户名
    password    = 'admin!' 		    #密码
    enable      = 'admin%'    	    #特权密码
    lists       = 'route_list.txt'  #和.py文件同路径文件
    cmds        = 'cmd.txt'    		#和.py文件同路径文件
    
    #创建实例
    telnet_client = RouteTelnetClient()
    
    #读取文件,for语句循环登陆路由器IP
    #格式:名称,广域网口IP
    try:
        with open(lists, 'rt') as list_obj:
            for route in list_obj:
                info_list = route.split(',') #分割字符串
                name = info_list[0]; #名称
                host = info_list[1]; #路由器IP
                print(u'准备链接[%s][%s]... \n' %(name, host))
                input(u'是否开始?(回车开始)')

                if telnet_client.login_host(host.strip(), username, password, enable):
                    telnet_client.do_cmd(cmds) #执行命令
                    telnet_client.logout_host()
                    time.sleep(2)
                else:
                    logging.error('telnet %s login failed.\n' %host)
    except IOError as e:
        logging.error('open %s failed:%s.\n' %(lists, e))
        

本文标签: 路由器脚本telnet