本脚本由群友似水年华大佬分享,
    **大佬为了简化脚本的环境搭建把脚本封装成了exe方便大家哪来即用。

    7、网络设备批量调试及备份 - 图1
    dev_config.exe是批量配置的脚本,调用ip.txt里放的ip输入用户名密码登陆设备,运行cmd.txt的命令。
    7、网络设备批量调试及备份 - 图2
    dev_bak.exe是备份脚本,调用ip.txt的ip输入用户名密码登陆设备,实现配置备份。

    7、网络设备批量调试及备份 - 图3
    视频演示如下:
    image.png
    image.png
    https://mp.weixin.qq.com/s/JBZPiKvAB48z76ihzYe0JQ (公众号原文链接里面有视频演示)
    ,时长04:28
    以下是脚本部分为三个文件:
    说明:第一个文件,devlogin.py是做的一个设备登陆的类,其他使用的时候引入这个就好了,dev_bak是配置备份的文件,其中设备登陆部分是从第一个文件引入的,第二个同理。如果需要多设备支持,就需要对devlogin.py里面去优化。
    现在devlogin里面做了思科,华为,juniper-netscreen,所以其他的需要优化这部分。
    devlogin.py登陆文件

    1. import netmiko
    2. import socket
    3. import re
    4. from netmiko import ConnectHandler, SSHDetect
    5. from netmiko.ssh_exception import NetMikoTimeoutException
    6. from netmiko.ssh_exception import NetMikoAuthenticationException
    7. ##This script use to login device by ssh or telnet,it will detect the TCP port (22,23) automaticly and
    8. #find out which is open to use,you can use port_scan to comfirm which metod will be used to connect device
    9. #and following two Classes are the different because the first one is only use to login cisco device,and
    10. #second one is use to login all devices now it supports 'cisco','huawei','juniper',and it can be detect
    11. #automatic!
    12. ##
    13. class CiscoLogin():
    14. ##Only use to Login cisco device!!!
    15. #
    16. def __init__(self,username,password,enable_pwd,ip):
    17. self.username = username
    18. self.password = password
    19. self.enable_pwd = enable_pwd
    20. self.ip = ip
    21. def port_scan(self):
    22. connect_protocol = 'unknown'
    23. sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    24. try:
    25. sock.connect((self.ip,22))
    26. sock.shutdown(2)
    27. sock.close()
    28. connect_protocol = 'ssh'
    29. except Exception as e:
    30. try:
    31. sock.connect((self.ip,23))
    32. sock.shutdown(2)
    33. sock.close()
    34. connect_protocol = 'telnet'
    35. except Exception as e:
    36. print('[+]%s端口不可达'%self.ip)
    37. return connect_protocol
    38. def ssh_login(self):
    39. auth_flag = False
    40. net_conn = ''
    41. hostname = ''
    42. devtype = ''
    43. device = {
    44. 'device_type': 'cisco_ios',
    45. 'ip': self.ip,
    46. 'username': self.username,
    47. 'password': self.password,
    48. 'secret': self.enable_pwd,
    49. # 'timeout': 5,
    50. }
    51. # 尝试探测设备型号以及登陆设备
    52. try:
    53. devtype = 'cisco_ios'
    54. print ('-' * 30)
    55. print ("[+] Trying to connect to: " + self.ip)
    56. net_conn = ConnectHandler(**device)
    57. # print (net_conn)
    58. print ("[+] connected to: " + self.ip)
    59. login_out = net_conn.find_prompt()
    60. print(login_out)
    61. hostname = login_out.replace('#', ' ').replace('>',' ').rstrip()
    62. if '#' in login_out:
    63. auth_flag = True
    64. print('login success')
    65. elif '>' in login_out:
    66. try:
    67. net_conn.enable()
    68. auth_flag = True
    69. except Exception as e:
    70. print('ENABLE authtication fail')
    71. except (EOFError, NetMikoAuthenticationException):
    72. print ('username/password wrong!')
    73. except (ValueError,NetMikoAuthenticationException):
    74. print ('enable password wrong!')
    75. return net_conn, auth_flag, hostname, devtype
    76. def telnet_login(self):
    77. auth_flag = False
    78. net_conn = ''
    79. hostname = ''
    80. devtype = ''
    81. device = {
    82. 'device_type': 'cisco_ios_telnet',
    83. 'ip': self.ip,
    84. 'username': self.username,
    85. 'password': self.password,
    86. 'secret': self.enable_pwd,
    87. }
    88. # 尝试探测设备型号以及登陆设备
    89. print ('[+] 尝试TELNET登陆%s设备...' % self.ip)
    90. try:
    91. devtype = 'cisco_ios_telnet'
    92. net_conn = ConnectHandler(**device)
    93. login_out = net_conn.find_prompt()
    94. if '#' in login_out:
    95. auth_flag = True
    96. hostname = login_out.replace('#', '')
    97. elif '>' in login_out:
    98. try:
    99. net_conn.enable()
    100. if net_conn.check_enable_mode():
    101. auth_flag = True
    102. hostname = login_out.replace('#', '')
    103. print('[+] 登陆ASA:%s设备成功...' % self.ip)
    104. except Exception as e:
    105. print('ENABLE认证失败')
    106. except (EOFError, NetMikoAuthenticationException):
    107. print ('username/password wrong!')
    108. except (ValueError,NetMikoAuthenticationException):
    109. print ('enable password wrong!')
    110. return net_conn, auth_flag, hostname, devtype
    111. class AllDevLogin():
    112. ##Use to login all devices,and it can autodetect device brand,support 'cisco','huawei','juniper'
    113. ##
    114. def __init__ (self,username,password,enable_pwd,ip):
    115. self.username = username
    116. self.password = password
    117. self.enable_pwd = enable_pwd
    118. self.ip = ip
    119. def port_scan(self):
    120. connect_protocol = 'unknown'
    121. sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    122. try:
    123. sock.connect((self.ip,22))
    124. sock.shutdown(2)
    125. sock.close()
    126. connect_protocol = 'ssh'
    127. except Exception as e:
    128. try:
    129. sock.connect((self.ip,23))
    130. sock.shutdown(2)
    131. sock.close()
    132. connect_protocol = 'telnet'
    133. except Exception as e:
    134. print('[+]%s端口不可达'%self.ip)
    135. return connect_protocol
    136. def telnet_autodetect(self):
    137. dev_detect_flag = False
    138. dev_telnet = {
    139. 'device_type': 'cisco_ios_telnet',
    140. 'ip': self.ip,
    141. 'username': self.username,
    142. 'password': self.password,
    143. 'secret': self.enable_pwd,
    144. # 'timeout':5,
    145. # 'global_delay_factor':1.3,
    146. }
    147. net_conn = ConnectHandler(**dev_telnet)
    148. if True:
    149. dev_out = net_conn.send_command('show version')
    150. if 'Adaptive' in dev_out:
    151. devtype = 'cisco_asa_telnet'
    152. elif 'Cisco' in dev_out:
    153. devtype = 'cisco_ios_telnet'
    154. elif 'Unrecognized command' in dev_out:
    155. dev_out = net_conn.send_command('display version')
    156. devtype = 'huawei_telnet'
    157. elif 'unknown keyword' in dev_out:
    158. dev_out = net_conn.send_command('get sys')
    159. devtype = 'juniper_junos_telnet'
    160. else:
    161. devtype = 'None'
    162. return devtype
    163. def ssh_login(self):
    164. auth_flag = False
    165. net_conn = ''
    166. hostname = ''
    167. devtype = 'cisco_ios'
    168. device = {
    169. 'device_type': 'autodetect',
    170. 'ip': self.ip,
    171. 'username': self.username,
    172. 'password': self.password,
    173. 'secret': self.enable_pwd,
    174. 'timeout':5,
    175. # 'global_delay_factor':1.3,
    176. }
    177. # 尝试探测设备型号以及登陆设备
    178. try:
    179. ###device autodetect
    180. print('[+] 正在尝试分析'+self.ip+'的设备品牌...')
    181. devtype_detect = SSHDetect(**device)
    182. devtype = devtype_detect.autodetect()
    183. device['device_type'] = devtype
    184. print ("[+] 正在尝试SSH登陆: " + self.ip)
    185. net_conn = ConnectHandler(**device)
    186. login_out = net_conn.find_prompt()
    187. print (login_out)
    188. ###SSH to device
    189. if 'cisco' in devtype:
    190. if '#' in login_out:
    191. auth_flag = True
    192. hostname = login_out.replace('#', '')
    193. #print (hostname)
    194. elif '>' in login_out :
    195. net_conn.enable()
    196. print('enable')
    197. if net_conn.check_enable_mode():
    198. auth_flag = True
    199. hostname = login_out.replace('#', '')
    200. print('[+] 登陆:%s设备成功...' % self.ip)
    201. else:
    202. print('[+] Enable:%s设备失败...' % self.ip)
    203. elif devtype == 'huawei':
    204. hostname = login_out.replace('<','').replace('>','')
    205. if login_out:
    206. auth_flag = True
    207. print('[+] 登陆%s设备成功...'%self.ip)
    208. if '>' in login_out:
    209. try:
    210. net_conn.config_mode()
    211. auth_flag = True
    212. except Exception as e:
    213. print('[+] Config_mode authtication fail')
    214. elif devtype == 'netscreen' or 'juniper':
    215. hostname = login_out.replace('->','')
    216. if '>' in login_out:
    217. auth_flag = True
    218. except (EOFError, NetMikoAuthenticationException):
    219. print ('username/password wrong!')
    220. except (ValueError,NetMikoAuthenticationException):
    221. print ('enable password wrong!')
    222. return net_conn, auth_flag, hostname, devtype
    223. def telnet_login(self):
    224. device = {
    225. 'device_type': 'cisco_ios',
    226. 'ip': self.ip,
    227. 'username': self.username,
    228. 'password': self.password,
    229. 'secret': self.enable_pwd,
    230. }
    231. try:
    232. devtype= telnet_autodetect()
    233. device['device_type'] = devtype
    234. net_conn = ConnectHandler(**device)
    235. login_out = net_conn.find_prompt()
    236. if 'cisco' in devtype:
    237. print ('-' * 30)
    238. print ("[+] 正在尝试TELNET登陆: " + self.ip)
    239. hostname = login_out.replace('#', '').replace('>','')
    240. # print (hostname)
    241. if '#' in login_out:
    242. auth_flag = True
    243. print('[+] 登陆%s设备成功...'%self.ip)
    244. elif '>' in login_out:
    245. try:
    246. net_conn.enable()
    247. if net_conn.check_enable_mode():
    248. auth_flag = True
    249. except Exception as e:
    250. print('ENABLE authtication fail')
    251. elif devtype == 'huawei_telnet':
    252. print ('-' * 30)
    253. print ("[+] Trying to connect to: " + self.ip)
    254. net_conn = ConnectHandler(**device)
    255. print ("[+] Connected to: " + ip)
    256. login_out = net_conn.find_prompt()
    257. print(login_out)
    258. hostname = login_out.replace('<', '').replace('>','')
    259. # print (hostname)
    260. if ']' in login_out:
    261. auth_flag = True
    262. print('[+] 登陆%s设备成功...'%self.ip)
    263. elif '>' in login_out:
    264. auth_flag = True
    265. try:
    266. net_conn.config_mode()
    267. auth_flag = True
    268. except Exception as e:
    269. print('[+] Config_mode authtication fail')
    270. elif devtype == 'juniper_junos_telnet':
    271. hostname = login_out.replace('->', '')
    272. print (hostname)
    273. if '>' in login_out:
    274. auth_flag = True
    275. except (EOFError, NetMikoAuthenticationException):
    276. print ('username/password wrong!')
    277. except (ValueError,NetMikoAuthenticationException):
    278. print ('enable password wrong!')
    279. return net_conn, auth_flag, hostname, devtype

    dev_config.py调试命令文件

    1. import netmiko
    2. import time
    3. import csv
    4. import re
    5. import getpass
    6. import socket
    7. import devlogin
    8. import fileinput
    9. from netmiko import ConnectHandler, SSHDetect
    10. from devlogin import CiscoLogin
    11. def fail_write(fail_path, data):
    12. with open(fail_path, 'a', encoding='utf-8', newline='') as faillogin:
    13. faillogin.write(data + '\r\n')
    14. def config_write(fail_path, data):
    15. with open(fail_path, 'a', encoding='utf-8', newline='') as config_write:
    16. config_write.write(data + '\r\n')
    17. config_write.write('-'*30 + '\r\n')
    18. def device_config(net_conn,hostname,devtype,ip,config_commands):
    19. config_output = net_conn.send_config_from_file ('cmd.txt')
    20. print (config_output)
    21. return config_output
    22. def main():
    23. total_time = 0
    24. file_path = 'config.txt'
    25. fail_path = 'fail.txt'
    26. config_commands = []
    27. dev_count = 0
    28. username = input('[+] Please Enter Username:')
    29. password = getpass.getpass('[+] Please Enter password:')
    30. enable_pwd = getpass.getpass('[+] Please Enter enable secret:')
    31. print ('[+] starting...')
    32. for cmd in fileinput.input('cmd.txt'):
    33. cmd= cmd.rstrip()
    34. config_commands.append(cmd)
    35. print('您要配置的命令如下:')
    36. for value in config_commands:
    37. print (value)
    38. cmd_comfirm= input('请确认是否使用以上命令进行配置[Y/N]?')
    39. if cmd_comfirm == 'y' or cmd_comfirm == 'Y':
    40. print ('-'*30)
    41. print ('[+] 开始执行...')
    42. print ('-'*30)
    43. for ip in fileinput.input('ip.txt'):
    44. start_time = time.time()
    45. ip = ip.rstrip()
    46. dev_count +=1
    47. print ('-' * 30)
    48. print ('[+] 正在尝试用用户名:'+ username +'登陆%s设备...'%ip)
    49. login = CiscoLogin(username,password,enable_pwd,ip)
    50. connect_protocol = login.port_scan()
    51. if connect_protocol == 'ssh':
    52. net_conn, auth_flag, hostname, devtype = login.ssh_login()
    53. elif connect_protocol == 'telnet':
    54. net_conn, auth_flag, hostname, devtype = login.telnet_login()
    55. else:
    56. print ('[+] 设备的端口不可达..')
    57. if auth_flag:
    58. config_output = device_config(net_conn,hostname,devtype,ip,config_commands)
    59. config_write(file_path,config_output)
    60. else:
    61. fail_write(fail_path, ip)
    62. print ('-'*30)
    63. else :
    64. print ('请修改cmd.txt中的命令后重新执行!脚本将直接退出!')
    65. exit(1)
    66. print ('总共配置了{0}设备'.format(dev_count))
    67. end_time = time.time()
    68. run_time = end_time - start_time
    69. run_time = round(run_time,2)
    70. total_time += run_time
    71. total_time = round(total_time,2)
    72. print ('[+] 运行耗时%s秒'%run_time)
    73. print ('[+] 运行总耗时%s秒'%total_time)
    74. conti=input('[+] 请按任意键退出:')
    75. if conti:
    76. exit(1)
    77. if __name__ == '__main__':
    78. login_info = u'''
    79. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    80. 此脚本为CISCO设备批量配置脚本,
    81. 请将需要配置的命令行保存在程序目录下并以cmd.txt命名,
    82. 请将需要登陆的设备IP保存在程序目录下并以ip.txt命名,
    83. 系统将自动读取IP以及命令并自动配置到设备,
    84. 注意,请在命令行最后加上'do copy running start'/'do write'以
    85. 确保配置能正确保存到设备!
    86. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    87. '''
    88. print(login_info)
    89. main()

    dev+bak.py备份文件:

    1. import netmiko
    2. import sys
    3. import os
    4. import time
    5. import re
    6. import fileinput
    7. from netmiko import ConnectHandler, SSHDetect
    8. from devlogin import AllDevLogin
    9. def config_bak(net_conn,devtype):
    10. cmd = 'show run'
    11. if 'cisco' in devtype:
    12. config = net_conn.send_command('show running-config')
    13. elif devtype == 'huawei':
    14. config = net_conn.send_command('display current-configuration')
    15. else:
    16. print('[+] Not in Config Mode,Please check enable password')
    17. return config,cmd
    18. def file_write(hostname,config,cmd,ip):
    19. filename = (u'{0}_{1}_{2}.txt'.format(hostname,ip,cmd))
    20. filepath = r'configbak/'
    21. if os.path.exists(filepath):
    22. print ('[+] The "%s" file exists.' %filepath)
    23. else:
    24. print ('[+] Now, I will create the %s'%filepath)
    25. os.makedirs(filepath)
    26. save = open(filepath + filename,'w')
    27. print(u'[+] executing {0} command'.format(cmd))
    28. save.write(config)
    29. print(u'[+] {0} command executed,result was saved at configbak,named {2}!'.format(cmd,filepath,filename))
    30. def main():
    31. # fail_path = 'fail.txt'
    32. username = input('[+] Please Enter Username:')
    33. password = input('[+] Please Enter password:')
    34. enable_pwd = input('[+] Please Enter enable secret:')
    35. print ('[+] start to backup...')
    36. for ip in fileinput.input('ip.txt'):
    37. ip = ip.rstrip()
    38. login = AllDevLogin(username,password,enable_pwd,ip)
    39. connect_protocol = login.port_scan()
    40. if connect_protocol == 'ssh':
    41. net_conn, auth_flag, hostname, devtype = login.ssh_login()
    42. elif connect_protocol == 'telnet':
    43. net_conn, auth_flag, hostname, devtype = login.telnet_login()
    44. if auth_flag:
    45. config, cmd = config_bak(net_conn, devtype)
    46. file_write(hostname,config,cmd,ip)
    47. if __name__ == '__main__':
    48. login_info = u'''
    49. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    50. 此脚本为CISCO设备配置备份脚本,
    51. 请将需要登陆的设备IP保存在程序目录下并以ip.txt命名,
    52. 系统将自动读取IP并登陆到设备完成备份,并将备份保存在configbak文件夹下
    53. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    54. '''
    55. print(login_info)
    56. main()

    脚本和exe获取公众号后台回复:“思科备份脚本”