在日常工作中我们经常要对 Cisco 的网络设备的配置进行备份,或者和 suricata 联动的时候要执行操作。
方法其实很简单,调用 python 的相应模块即可。
准备工作如下:
首选需要在/export/servers/python363装好 python 3.6, pip install netmiko
其次,在路由器上可以配置en的密码
然后依次执行备份就可以了。
#!/export/servers/python363/bin/python3.6
from netmiko import Netmiko
import time
tw_bgp = {
"device_type": "cisco_ios",
"host": "tw-bgp",
"ip": "192.168.1.10",
"username": "noc",
"use_keys": True,
"secret" : "xxxxxxxx",
"key_file": "/root/.ssh/id_jump_rsa_new",
}
tw_r1_e1 = {
"device_type": "cisco_ios",
"host": "tw-r1-e1",
"ip": "192.168.1.11",
"username": "noc",
"use_keys": True,
"key_file": "/root/.ssh/id_jump_rsa_new",
}
tw_r1_e2 = {
"device_type": "cisco_ios",
"host": "tw-r1-e2",
"ip": "192.168.1.12",
"username": "noc",
"use_keys": True,
"key_file": "/root/.ssh/id_jump_rsa_new",
}
tw_r2_e1 = {
"device_type": "cisco_ios",
"host": "tw-r2-e1",
"ip": "192.168.1.13",
"username": "noc",
"use_keys": True,
"key_file": "/root/.ssh/id_jump_rsa_new",
}
tw_r2_e2 = {
"device_type": "cisco_ios",
"host": "tw-r2-e2",
"ip": "192.168.1.14",
"username": "noc",
"use_keys": True,
"key_file": "/root/.ssh/id_jump_rsa_new",
}
devices=[tw_bgp, tw_r1_e1, tw_r1_e2, tw_r2_e1, tw_r2_e2]
for dev in devices:
name = dev["ip"]
connection = Netmiko(**dev)
connection.enable()
out = connection.send_command("show running-config")
calender = time.strftime("%Y%m%d")
file_name = '{}-{}.txt'.format(dev["host"],calender)
file = open(file_name ,"w")
file.write(out)
file.close()
connection.disconnect()
print("BACKUP for %s done" %dev["host"])