关于使⽤python批量操作⽹络设备(交换机,路由器)的知识点⼩结
关于使⽤python批量操作⽹络设备,这⾥本⼈⽬前只接触了两个模块,netmiko和pratmiko,后⾯的脚本也都将基于这两个模块。
⼀、netmiko模块
1、使⽤netmiko模块连接操作设备
import netmiko #导⼊netmiko模块
import time #导⼊time模块
#使⽤with语句打开⽤于ssh连接所需要的相关信息(⽤户名,密码,ip地址,需要配置的命令),这个打开了两个⽂件⽤户信息⽂件,命令⽂件,分别命名为devices_file,cmd_file with open("ip_", "r") as devices_file, open("", "r") as cmd_file:
#将⽤户信息⽂件按⾏读取赋值给devices
devices = adlines()
#将命令⽂件按⾏读取赋值给cmdlist
cmdlist = adlines()
#使⽤循环将⽤户名,密码,IP地址,分别赋值给username,password,ip_address变量,并依次登陆
for line in devices:
line = line.strip("\n")
ip_address = line.split(",")[0] #split() 通过指定分隔符对字符串进⾏切⽚,如果参数 num 有指定值,则分隔 num+1 个⼦字符串
username = line.split(",")[1]
password = line.split(",")[2]
#创建⼀个名为SW2的字典,该字典包含“device_type”“ip”“username”和“password”4个必选的键,如果设备类型是netmiko不⽀持的类型,不清楚还能不能连接
SW2 = {
'device_type': 'huawei',
'ip': ip_address,
'username': username,
'password': password,
}
connect = netmiko.ConnectHandler(**SW2) #函数ConnectHandler()。该函数⽤来实现SSH登录⽹络设备,是Netmiko最重要的函数。
print("Successfully connect to" + SW2['ip'])
#config_commands = ['dis arp']
#output = connect.send_config_set(config_commands)
#rint(output)字符串函数strip的作用
#使⽤循环将cmdlist中的命令依次输⼊
for cmd in cmdlist:
output2 = connect.send_config_set(cmd) #send_config_set()则可向设备⼀次输⼊多个命令
print(output2)
time.sleep(1)
print("*" * 50 + "分割线" + "*" * 50)
#result = connect.send_command('dis int LoopBack 0')
#print(result)
脚本运⾏结果如下:
2、ssh_netmiko_多线程
使⽤netmiko实现多线程操作⽹络设备
#coding=utf-8
import threading #Python 3已经内置了threading模块来实现多线程,这⾥引⼊
from queue import Queue #多线程中需要⽤的队列,这⾥引⼊,多线程中需要⽤的队列,这⾥引⼊,通过队列传递数据,安全,不会造成多个线程访问时混乱import netmiko
import time
#定义连接函数,使⽤netmiko连接设备,并输⼊预定义命令
def ssh_session(ip, username, password,cmdlist, output_q):
SW2 = {
'device_type': 'huawei',
'ip': ip_address,
'username': username,
'password': password,
}
connect = netmiko.ConnectHandler(**SW2)
print("Successfully connect to" + SW2['ip'])
'''
config_commands = ['dis arp', 'dis ip routing-table', 'dis int brief']
output = connect.send_config_set(config_commands)
print(output)
print("*" * 50 + "分割线" + "*" * 50)
'''
for cmd in cmdlist:
output = connect.send_config_set(cmd)
print(output)
time.sleep(1)
print("*" * 50 + "分割线" + "*" * 50)
#result = connect.send_command('dis int LoopBack 0')
#print(result)
print("程序于 {} 开始执⾏\n".format(time.strftime("%X")))
threads = []
with open("ip_", "r") as devices_file, open("", "r") as cmd_file:
devices = adlines()
cmdlist = adlines()
for line in devices:
line = line.strip("\n")
ip_address = line.split(",")[0] #split() 通过指定分隔符对字符串进⾏切⽚,如果参数 num 有指定值,则分隔 num+1 个⼦字符串
username = line.split(",")[1]
password = line.split(",")[2]
#使⽤threading的Thread()函数为ssh_session函数创建⼀个线程并将它赋值给变量t,注意Thread()函数的target参数对应的是函数名称(即ssh_session)#args对应的是该ssh_session函数的参数
t = threading.Thread(target=ssh_session, args=(ip_address, username, password, cmdlist, Queue()))
t.start()
threads.append(t)
for i in threads:
i.join() #threading的join()⽅法的作⽤是强制阻塞调⽤它的线程,直到该线程运⾏完毕或者终⽌(类似
单线程同步)
print("程序于 {} 执⾏结束\n".format(time.strftime("%X")))
脚本缺少错误控制加⼊try语句,可以更好的应⽤脚本,不会因为地址和⽤户名密码错误导致脚本中断,另外关于脚本⾥的使⽤了队列实现线程控制,但是为什么要写成这个形式 t = threading.Thread(target=ssh_session, args=(ip_address, username, password, cmdlist, Queue())),⽬前我还不太了解。希望知道原理的⼤⼤能告诉我⼀下~
⼆、prarmiko模块
1、使⽤prarmiko模块连接⽹络设备操作(连接协议ssh)
'''
需在命令⾏运⾏程序,并给四个⽂件参数,存放ip的⽂件在前,存放命令的⽂件在后,例如:python lab3_1.
'''
import paramiko
import time
import getpass
import sys
import socket
#username = input("username:")
#password = pass("password:")
ip_file = sys.argv[1] #sys.argv[]就是⼀个从程序外部获取参数的桥梁,外部取得的参数可以是多个,所以获得的是⼀个列表(list),其第⼀个元素是程序本⾝,随后才依次是外部给予的参数,
cmd_file = sys.argv[2] #这⾥使⽤sys.argv(),即将保存的ip和命令的⽂件作为参数赋值给变量
user_file = sys.argv[3]
pass_file = sys.argv[4]
switch_with_authentication_issue = [] #认证失败的列表,⽤于存放⽤户认证失败的IP地址
switch_not_reachable = [] #连接失败的列表,⽤于存放连接失败的ip地址
#打开⽂件⽤户信息⽂件,IP地址⽂件
iplist = open(ip_file, "r")
userlist = open(user_file, "r")
passlist = open(pass_file, "r")
#使⽤循环按⾏读取,⽂件内容,这个⽤zip() 函数将可迭代的对象作为参数,将对象中对应的元素打包成⼀个个元组,然后返回由这些元组组成的对象
#例如: 192.168.1.1 admin 123
for line1, line2, line3 in adlines(), adlines(), adlines()):
try:
ip = line1.strip()
username = line2.strip()
password = line3.strip()
ssh_client = paramiko.SSHClient() #调⽤paramiko的SSHClient⽅法连接⽹络设备,及本地设备为客户端
'''
默认情况下,Paramiko会拒绝任何未知的SSH公钥(publickey),这⾥我们需要使⽤ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
来让Paramiko接受SSH服务端(也就是SW3)提供的公钥,这是任何时候使⽤Paramiko都要⽤到的标准配置。
'''
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
t(hostname=ip, username=username, password=password) #调⽤connect()⽅法,输⼊连接设备所需的ip,⽤户名,密码
print("登录成功", ip)
command = ssh_client.invoke_shell() #调⽤Paramiko.SSHClient()的invoke_shell()⽅法来唤醒shell
cmdlist = open(cmd_file, "r") #读⼊命令⽂件
cmdlist.seek(0) #seek() ⽅法⽤于移动⽂件读取指针到指定位置,参数为0代表从⽂件开头开始算起。
for line adlines():
command.send(line + "\n")
time.sleep(5)
cmdlist.close()
output = v(65535)
print(output.decode("ascii"))
except paramiko.ssh_exception.AuthenticationException:
print("⽤户认证失败:" + ip)
switch_with_authentication_issue.append(ip)
:
print(ip + "连接失败")
switch_not_reachable.append(ip)
iplist.close()
userlist.close()
passlist.close()
ssh_client.close
print("*" * 50 + "分割线" + "*" * 50)
print("\n⽤户认证失败的交换机:\n")
for i in switch_with_authentication_issue:
print(i)
print("\n⽹络连接失败交换机:\n")
for i in switch_not_reachable:
print(i)
三、配置⽂件备份
1、使⽤netmiko备份,⽤于备份netmiko⽀持的设备,使⽤h3c设备测试此脚本,备份失败(可能是netmiko中没有h3c的相关函数)
import netmiko
import time
with open("") as devices_file:
devices = adlines()
for line in devices:
line = line.strip("\n")
ipaddr = line.split(",")[0] #split() 通过指定分隔符对字符串进⾏切⽚,如果参数 num 有指定值,则分隔 num+1 个⼦字符串
username = line.split(",")[1]
password = line.split(",")[2]
vendor = line.split(",")[3]
SW2 = {
'device_type': vendor,
'ip': ipaddr,
'username': username,
'password': password,
}
now = time.strftime("%Y-%m-%d", time.localtime())
connect = netmiko.ConnectHandler(**SW2)
print("Successfully connect to" + SW2['ip'])
backup_cfg = connect.send_command("dis cur") #将命令内容赋值给变量
print(backup_cfg)
#将变量的值写⼊⽂件,⽂件命名按时间划分
with open( "C:\\ftp\\交换机_" + str(now) + "_{}.txt".format(ipaddr), "w") as f:
f.write(backup_cfg)
2、使⽤prarmiko,基于tftp备份配置⽂件
⾸先要搭建⼀个tftp服务器,使⽤tftp相关软件即可
其次运⾏脚本
import paramiko
import time
with open("ip_") as devices_file:
devices = adlines()
for line in devices:
line = line.strip("\n")
ip_address = line.split(",")[0] #split() 通过指定分隔符对字符串进⾏切⽚,如果参数 num 有指定值,则分隔 num+1 个⼦字符串 username = line.split(",")[1]
password = line.split(",")[2]
now = time.strftime("%Y-%m-%d", time.localtime())
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
t(hostname=ip_address, username=username, password=password)
print("登陆成功:",ip_address)
command = ssh_client.invoke_shell()
command.send("copy startup.cfg {}_{}.cfg\n".format(now,ip_address))
command.send("y\n")
command.send("tftp 192.168.134.222 put {}_{}.cfg\n".format(now,ip_address))
time.sleep(15)
command.send("delete {}_{}.cfg\n".format(now,ip_address))
command.send("y\n")
time.sleep(5)
output = v(65535)
print(output.decode("ascii"))
ssh_client.close
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论