python批量给交换机下发配置--初级版(下发相同配置)

用paramiko多线程SSH登陆华为交换机处理简单的命令

[root@10-57-22-238 sshsw]# ll
total 12
-rw-r--r-- 1 root root  79 Mar 14 23:53 cmd.txt
-rw-r--r-- 1 root root 274 Mar 14 23:32 conf.py
-rw-r--r-- 1 root root 933 Mar 14 23:51 ssh_sw_cmd.py

cmd.txt用来存放要配置到交换机的命令,内容如下(以下内容为配置NTP)。

sys
ntp unicast-peer 192.168.6.100 version 4 source-interface LoopBack0
commit

conf.py 保存交换机的管理IP,及登陆交换机的用户名密码

#-*- coding: utf-8 -*-
#!/usr/bin/python
#要执行操作的交换机管理

#交换机SSH用户名密码    
username = "wsf535"  #用户名
passwd = "****"    #密码
threads = [10]   #多线程

data.csv储存设备名与ip

torname,ip
S303-ilo-asw-w5855-01.64,10.21.0.64
S304-ilo-asw-w5855-01.65,10.21.0.65
S305-ilo-asw-w5855-01.66,10.21.0.96
S306-ilo-asw-w5855-01.67,10.21.0.97
S307-ilo-asw-w5855-01.68,10.21.0.224
S308-ilo-asw-w5855-01.69,10.21.0.225

ss_sw_cmd.py为主运行文件 

#-*- coding: utf-8 -*-
#!/usr/bin/python
import paramiko
import threading
import time
import os
from conf import *

#拿到cmd.txt文件中的命令
with open('./cmd.txt', 'r') as f:
    cmd_line= f.readlines()
cmd=[]
for c in cmd_line:
     cmd.append(c)
#定义连接与操作
def ssh2(ip,username,passwd,cmd):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,22,username,passwd,timeout=5)
        ssh_shell = ssh.invoke_shell()
        for m in cmd:
            res = ssh_shell.sendall(m)
        lines = ''
        flag = 0
        while True:
            line = ssh_shell.recv(2048)
            #print(line)
            lines += line
            if line and line.endswith(b'>') and flag == 1:
                break
            if line and line.endswith(b'>') and flag == 0:
                flag = 1
        ssh.close()
        print(lines)

    except Exception as err:
        print "%s\t Error: %s\n"%(ip, err)

if __name__=='__main__':
    fo=open("data.csv","r")
    swip=[]
    ls=[]
    for line in fo:
        line=line.replace("\n","")
        ls.append(line.split(","))
    for i in range(1,len(ls)):
        swip.append(ls[i][1])
    print "Begin......"
    for i in range(len(swip)):
        ip = swip[i].replace("\r","")
        a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd))
        time.sleep(1)
        a.start()


 

 

你可能感兴趣的:(python批量给交换机下发配置--初级版(下发相同配置))