2019-08-02 实用脚本:遍历路由器批量执行命令

先回顾一下实用paramiko连接网络设备的过程:

1、标准paramiko连接设备
import paramiko

2、创建SSH对象
ssh = paramiko.SSHClient()

3、允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

4、连接网络设备/主机
ssh.connect(hostname='xx.xxx.xxx.42',port=22,username='username',password='password')

5、执行命令
stdin,stdout,stderr = ssh.exec_command('sudo systemctl status ssh')

stdin标准输入:你输入的命令,会返还给你
stdout标准输出:你的命令执行结果
stderr标准错误:在执行过程中出现的错误

6、获取命令结果
result = stdout.read() ##标准输出,只有在命令正确的情况下才会输出,否则返回的信息为空。
print (result.decode()) ##因为linux是utf-8的bytes格式所以要decode

7、关闭连接
ssh.close()

下面上脚本,登录一批路由器(路由器列表,通过读取config文件里的字典获得),逐个执行命令(批量命令通过读取文本文件取得)

#!/usr/bin/env python3

import paramiko
import time
import sys
import logging
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
from config import ne05esq #config.py里定义了ne05esq字典

#逐行读取命令文本,生成列表
def get_cmd(file_name):
    cmd=[]
    try:
        file_object = open(file_name, 'r', encoding='utf-8')
        for line in file_object:
            cmd.append(line)
    finally:
         file_object.close()
    return(cmd)

#获取字典里的IP地址字段,单独形成一个列表
def get_ip_list():
    all_ip = []
    for key in ne05esq:
        all_ip.append(key)
    return(all_ip)

username = "username"
password = "password"

cmd = get_cmd('test.conf')
allip = get_ip_list()

def mySshClient(ip, username, passwd, cmd):
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(
            hostname=ip,
            username=username,
            password=password,
            allow_agent=False,
            look_for_keys=False)
        print("Sucessfully login to ", ip)

        command = ssh_client.invoke_shell()
        for i in range(len(cmd)):
            command.send(cmd[i])
            time.sleep(1)  #有时候输出较多,需要将等待延长几秒
            output = command.recv(65535)
            print(output.decode("utf-8"))  #需要的话可以使用标准输入输出写到文件里
        ssh_client.close()

    except AuthenticationException:
        logging.warning('username or password error')
    except NoValidConnectionsError:
        logging.warning('connect time out')
    except:
        logging.warning('unknow error')
        print("Unexpected error:", sys.exc_info()[0])

if __name__ == '__main__':
    for index in range(len(allip)):    #循环读取设备地址
        mySshClient(allip[index], username, password, cmd)

配置文件类似下面内容:

ne05esq = {
"xx.xxx.xx.1"    : "ar01.xxx.lon",
"xx.xxx.xx.2"    : "ar01.xxx.lon",
}

命令文本类不需进行转义等特殊处理,如下:

system
disp ver | no-more
disp cur | no-more

这个脚本可以用来批量配置,备份等操作。
再贴一下写到文件里的脚本,稍有改动:

#增加一个时间函数
def DatetimeToDate():
    timeStruct = datetime.date.today()
    return timeStruct.strftime('%Y-%m-%d')

#....... 前面跳过,下面的是在原先脚本基础上增加标准输出
        print("Sucessfully login to ", ip)
        command = ssh_client.invoke_shell()
        filename = 'saved_cfg/' + ip + "_" + str(DatetimeToDate()) + '.cfg' #文档目录和名称
        print('Create file: ', filename)
        for i in range(len(cmd)):
            command.send(cmd[i])
            time.sleep(3)  #有时候输出较多,需要将等待延长几秒
            output = command.recv(65535)
            print(output.decode("utf-8"))  #可注释掉显无需示
            out1 = output.decode("utf-8")
            with open(filename, 'a') as f:
                f.write(out1)
                f.flush()
         ssh_client.close()
#后面略过
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。