├── README.md ├── auto_config.py ├── auto_show ├── config.py ├── config.pyc └── onecollect.py ├── autoconfig_beta ├── auto_config.py ├── config.py ├── config.pyc ├── configuration.txt └── result.txt ├── config.py ├── config.pyc ├── configuration.txt ├── jietu.png └── result.txt /README.md: -------------------------------------------------------------------------------- 1 | ## 背景介绍 2 | 3 | 本人在互联网工作多年,混迹过bat中两家,都是屌丝网工,即便两家自动化程度都已经非常高了,但网工在日常工作种任然少不了大量配置交换机。
4 | 所以这里写一个python脚本,把可以自动化登录设备刷配置,然后显示检测命令结果和ping检测结果,从而减少人成本。
5 | 6 | github地址: 7 |
8 | 这里也提供一个百度网盘的下载地址 9 | 链接: 密码: ignz 10 | 11 | 12 | 13 | ## 设计思路 14 | 15 | 比较简单,就是实现读取操作单(configuration.txt)中的内容,获取需要配置的设备管理IP和命令以及检测步骤,然后通过配置文件(config.py)里面的参数来获取设备登录帐号密码和登录方式等信息进行自动化登录设备刷配置。 16 |
17 | 由于这个脚本会对每一步进行检测并提示操作者是否继续,所以变更单里面的操作顺序可能比较重要,所以没有使用多进程来做,串行逐个执行变更单的设备和配置。
18 | 但是考虑到我们日常可能会用到需要刷大量设备配置,所以在文件夹(autoconfig_beta)中添加了无脑多进程批量刷配置的脚本,这个在最后再介绍。 19 |
20 | 这个脚本用python写的,而且不需要额外按照任何库,对于linux基础比较弱和没有python基础的网工来说可以是分分钟就能上手。
21 | 就是界面有点丑。。。 22 | 23 | ## 操作简介 24 | 25 | 如上面介绍,config.py文件主要是配置登录设备的相关参数
26 | 27 | ``` python 28 | 'config_username':'test', #有配置权限的帐号,如果不填会让你每次输入,因为有些大厂就是动态的3A帐号密码,所以这块不填方便你每次输入 29 | 'config_password':'test', #有配置权限帐号的密码,同上 30 | 'show_username':'test_show', #只有show权限的帐号,如果不填会直接使用配置权限帐号,分离可以防止一些配置命令误敲 31 | 'show_password':'test_show', #只有show权限的帐号的密码,如果不填会直接使用配置权限帐号的密码 32 | 'ssh_port':'22', #ssh的端口号,默认是22 33 | 'login_method':'telnet', #登录方式,填写ssh或者telnet 34 | 'login_user_identification':':', #telnet方式需要填写对应设备的登录时账户输入的标识符,本人亲测大部分就是login:和username:,用:就行,不用改 35 | 'login_password_identification':'assword:' #同上,输入密码的标识符,这个我看了juniper、cisco、hw、h3c基本都是这个,所以也不用改 36 | ``` 37 | 38 | 操作单是文件 configuration.txt
39 | 以下是一个demo 40 | 41 | ``` python 42 | $IP: 43 | 10.1.1.11 44 | $CONFIG: 45 | configure terminal 46 | interface eth1/1 47 | ip add ress 1.1.1.1 48 | $CHECK: 49 | terminal length 0 50 | show ip int brief 51 | $PING: 52 | 1.1.1.1 53 | $CONFIG: 54 | configure terminal 55 | hostname 123 56 | $PING: 57 | 10.1.1.240 58 | 10.1.1.119 59 | 60 | $IP: 61 | 10.1.1.12 62 | $CONFIG: 63 | configure terminal 64 | interface eth1/1 65 | ip add ress 2.2.2.2 66 | no shutdown 67 | $CHECK: 68 | terminal length 0 69 | show ip int brief 70 | $PING: 71 | 2.2.2.2 72 | ``` 73 | 74 | 可以看到每个设备需要包含$IP:、$CONFIG:、$CHECK:、$PING:等参数
75 | $IP:下只能填写一个设备的管理ip
76 | $CONFIG:下可以写条需要执行的命令
77 | $CHECK:下写多条进行展示的命令,为了防止一些设备show的东西很多要输入more,我建议在交换机上先输入terminal length 0(思科) screen-length 0 temporary(华为)其他也差不多,来防止出现more这种分屏显示(这块如果为了针对厂商做自动more一方面比较麻烦,有的厂商不是more,而且会有more显示到回显)
78 | $IP:下填写要ping的地址,因为我们做一些操作,经常怕把网干断了,所以需要ping检测一下
79 | 80 | 由上面可知,一个管理IP可能存在多个$CONFIG:、$CHECK:、$PING:这样的组合步骤,所以支持一个$IP:下包含多个$CONFIG:、$CHECK:、$PING:这样组合的模块。 81 | 82 | 执行结果如下(这个和上面操作单的内容不符,随便找了设备测试的)
83 | ![](http://182.61.38.60/jietu.png)
84 | 85 | 86 | 87 | ## 多进程刷配置版 88 | 89 | autoconfig_beta文件下是简单粗暴的批量多进程刷配置。
90 | 正如前面所说,比如刷全网所有设备的acl或者snmp这种配置,全网上千台设备,一个个刷太累了,再或者巡检,让你去show全网设备的板卡信息,这也太累了是不是。
91 | 由于设备量太大,配置简单(没啥风险,甚至就是为了巡检采集信息用),也没必要说每一步都要检查,所以直接多进程并发去下发命令,哐哐哐就是干!最后会把结果保存到文本result.txt中。
92 | 如果有登录失败会爆出来 93 | 类似的也有一个config.py
94 | 里面参数和之前类似,只是多了'multiprocess':'3' #这个就是用来指定多进程的数量,指定几个就是同时登录几台设备去刷配置
95 | 96 | 然后就是configuration.txt 97 | 只由 $IP:、$CONFIG:组成,结构清晰很多有木有 98 | $IP: 可以由多个IP地址组成比如 99 | 100 | ``` python 101 | $IP: 102 | 1.1.1.1 103 | 2.2.2.2 104 | $CONFIG: 105 | show run 106 | show clock 107 | 108 | $IP: 109 | 3.3.3.3 110 | $CONFIG: 111 | show time 112 | 113 | ``` 114 | 115 | 执行过程就是,在1.1.1和2.2.2上执行相同的命令show run和show clock。
116 | 在3.3.3.3上执行show time。
117 | 如果可以登录就将结果保存在result.txt中,即便登录失败也会报出来并保存在result.txt中方便排错。
118 | 由于多进程数量是3,所以会三台一起登录分别刷配置,高效很多有木有! 119 | 120 | 121 | ## 多进程采集-ssh 122 | 123 | auto_show文件夹下onecollect.py是简单粗暴的批量多进程ssh采集。
124 | 使用方法很简单,在config文件里面填下设备帐号密码IP和命令,最大五个进程。python onecollect.py抓取完信息会放在设备名生成的文件夹下,加上日期。 125 | 如果进行批量设备采集信息收集可以使用,效率杠杠的。 126 | 此版本可以抓全设备回显,是之前的升级版本. 127 | 128 | 129 | 130 | 131 | -------------------------------------------------------------------------------- /auto_config.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | # -*- coding:utf-8 -*- 3 | 4 | import paramiko,time,telnetlib,sys,os,re 5 | import threading 6 | try: 7 | from config import config 8 | except: 9 | config = {'config_username':'','config_password':'','show_username':'','show_password':'','ssh_port':'22','login_method':''} 10 | 11 | 12 | stdmore = re.compile(r"-[\S\s]*[Mm]ore[\S\s]*-") 13 | hostname_endcondition = re.compile(r"\S+[#>\]]\s*$") 14 | 15 | class ssh_comm(object): 16 | def __init__(self,address,username,password,port=22): 17 | self.client = paramiko.SSHClient() 18 | self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 19 | self.client.connect(address, port=port, username=username, password=password, look_for_keys=False,allow_agent=False) 20 | self.shell = self.client.invoke_shell() 21 | while True: 22 | time.sleep(0.5) 23 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 24 | break 25 | self.shell.recv(4096) 26 | self.shell.send('\n') 27 | output = self.shell.recv(4096) 28 | while True: 29 | if hostname_endcondition.findall(output): 30 | self.hostname = hostname_endcondition.findall(output)[0].strip().strip('<>[]#') 31 | break 32 | while True: 33 | time.sleep(0.1) 34 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 35 | break 36 | output += self.shell.recv(4096) 37 | def recv_all(self,interval,stdjudge,stdconfirm): 38 | endcondition = re.compile(r"%s\S*[#>\]]\s*$"%self.hostname) 39 | while True: 40 | time.sleep(interval) 41 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 42 | break 43 | output = self.shell.recv(99999) 44 | if (stdjudge != '') and (stdjudge in output): 45 | self.shell.send(stdconfirm+'\n') 46 | while True: 47 | if stdmore.findall(output.split('\n')[-1]): 48 | break 49 | elif endcondition.findall(output): 50 | break 51 | while True: 52 | time.sleep(interval) 53 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 54 | break 55 | output += self.shell.recv(99999) 56 | return output 57 | def send_command(self,command_interval,command,stdjudge,stdconfirm): 58 | command += "\n" 59 | self.shell.send(command) 60 | if ('hostname' in command) or ('sysname' in command): 61 | while True: 62 | time.sleep(0.5) 63 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 64 | break 65 | stdout = self.shell.recv(4096) 66 | self.hostname = hostname_endcondition.findall(stdout)[-1].strip().strip('<>[]#') 67 | else: 68 | stdout = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 69 | data = stdout.split('\n') 70 | while stdmore.findall(data[-1]): 71 | self.shell.send(" ") 72 | tmp = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 73 | data = tmp.split('\n') 74 | stdout += tmp 75 | return stdout 76 | def close(self): 77 | if self.client is not None: 78 | self.client.close() 79 | def run(self,cmds,command_interval,stdjudge,stdconfirm): 80 | stderr = ['^','ERROR','Error','error','invalid','Invalid','Ambiguous','ambiguous'] 81 | stdout = '' 82 | res = 'success' 83 | for cmd in cmds.split('\n'): 84 | if cmd.strip(): 85 | stdout += self.send_command(command=cmd,command_interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 86 | for err in stderr: 87 | if err in stdout: 88 | res = 'some command wrong' 89 | return res, stdout 90 | 91 | 92 | def config_dev_ssh(ip, commands): 93 | try_times = 0 94 | while True: 95 | if config['config_username'] != '' and config['config_password'] != '': 96 | username = config['config_username'] 97 | password = config['config_password'] 98 | try_times = 2 99 | else: 100 | username = raw_input('请输入aaa用户名:') 101 | password = raw_input('请输入aaa密码: ') 102 | port = 22 103 | try_times += 1 104 | try: 105 | connection = ssh_comm(address=ip, username=username, password=password, port=port) 106 | break 107 | except: 108 | print 'wrong password,please try agagin!' 109 | if try_times > 2: 110 | sys.exit('wrong password more than tree times,out!') 111 | if password_config['show_username'] != '' and password_config['show_password'] != '': 112 | show_username = config['show_username'] 113 | show_password = config['show_password'] 114 | else: 115 | show_username = username 116 | show_password = password 117 | connection1 = ssh_comm(address=ip, username=show_username, password=show_password, port=port) 118 | for command in commands: 119 | if len(command['config']) != 0: 120 | res,stdout = connection.run(cmds=('\n').join(command['config']),command_interval=0.1,stdjudge='Y/N',stdconfirm='Y') 121 | if len(command['check']) != 0: 122 | res1,stdout1 = connection.run(cmds=('\n').join(command['check']),command_interval=0.1,stdjudge='Y/N',stdconfirm='Y') 123 | print stdout1 124 | if len(command['ping']) != 0: 125 | threads = [] 126 | for ping_host in command['ping']: 127 | threads.append(threading.Thread(target = getpingloss,args=(ping_host,))) 128 | for t in threads: 129 | t.start() 130 | for t in threads: 131 | t.join() 132 | q = raw_input('请问是否继续,按q回车退出,任意键回车继续') 133 | if q == 'q': 134 | sys.exit() 135 | 136 | 137 | 138 | def config_dev_tel(ip, commands): 139 | try_times = 0 140 | while True: 141 | if config['config_username'] != '' and config['config_password'] != '': 142 | username = config['config_username'] 143 | password = config['config_password'] 144 | try_times = 2 145 | else: 146 | username = raw_input('请输入aaa用户名:') 147 | password = raw_input('请输入aaa密码: ') 148 | try: 149 | handler = telnetlib.Telnet(ip,timeout=3) 150 | handler.read_until(config['login_user_identification']) 151 | handler.write(username+'\r') 152 | handler.read_until(config['login_password_identification']) 153 | handler.write(password+'\r') 154 | break 155 | except: 156 | print 'wrong password,please try agagin!' 157 | try_times += 1 158 | if try_times > 2: 159 | sys.exit('wrong password more than tree times,out!') 160 | handler1 = telnetlib.Telnet(ip,timeout=3) 161 | handler1.read_until(config['login_user_identification']) 162 | handler1.write(username+'\r') 163 | handler1.read_until(config['login_password_identification']) 164 | handler1.write(password+'\r') 165 | for command in commands: 166 | if len(command['config']) != 0: 167 | for config_command in command['config']: 168 | handler.write(config_command+'\r') 169 | time.sleep(1) 170 | if len(command['check']) != 0: 171 | for check_command in command['check']: 172 | handler1.write(check_command+'\r') 173 | time.sleep(1) 174 | handler1.write('$$\r') 175 | print handler1.read_until('$$') 176 | if len(command['ping']) != 0: 177 | threads = [] 178 | for ping_host in command['ping']: 179 | threads.append(threading.Thread(target = getpingloss,args=(ping_host,))) 180 | for t in threads: 181 | t.start() 182 | for t in threads: 183 | t.join() 184 | q = raw_input('请问是否继续,按q回车退出,任意键回车继续') 185 | if q == 'q': 186 | sys.exit() 187 | 188 | def getpingloss(ping_host): 189 | print 'ping %s '%ping_host +[i for i in os.popen('ping %s -c 5'%ping_host).read().split(',') if 'packet loss' in i][0] 190 | 191 | def readconfigs(config_name): 192 | f = open(config_name) 193 | results = f.read() 194 | result = {} 195 | ip_list = [] 196 | for i in results.split('$IP:'): 197 | if i != '': 198 | ip = i.split()[0] 199 | commands = [] 200 | for j in range(len(i.split('$CONFIG:'))): 201 | command = {} 202 | if (j > 0) and (i.split('$CONFIG:')[j]) != '': 203 | try: 204 | m = i.split('$CONFIG:')[j].split('$CHECK:')[0] 205 | command['config'] = [ x.strip() for x in m.split('\n') if x.strip() != ''] 206 | except: 207 | m = i.split('$CONFIG:')[j].split('$PING:')[0] 208 | command['config'] = [ x.strip() for x in m.split('\n') if x.strip() != ''] 209 | try: 210 | n = i.split('$CONFIG:')[j].split('$CHECK:')[1].split('$PING:')[0] 211 | command['check'] = [ y.strip() for y in n.split('\n') if y.strip() != ''] 212 | except: 213 | command['check'] = [] 214 | try: 215 | t = i.split('$CONFIG:')[j].split('$CHECK:')[1].split('$PING:')[1] 216 | command['ping'] = [ z.strip() for z in t.split('\n') if z.strip() != ''] 217 | except: 218 | try: 219 | t = i.split('$CONFIG:')[j].split('$PING:')[1] 220 | command['ping'] = [ z.strip() for z in t.split('\n') if z.strip() != ''] 221 | except: 222 | command['ping'] = [] 223 | if command != {}: 224 | commands.append(command) 225 | result[ip] = commands 226 | ip_list.append(ip) 227 | return result,ip_list 228 | 229 | 230 | if __name__== '__main__': 231 | result,ip_list = readconfigs('configuration.txt') 232 | if config['login_method'] == '': 233 | config['login_method'] = raw_input('使用哪种登录方式ssh还是telnet,请输入telnet或者ssh: ') 234 | for i in ip_list: 235 | print(''.ljust(101,'#')) 236 | print 'device_ip: %s is configing !'%i 237 | if config['login_method'] == 'telnet': 238 | config_dev_tel(i,result[i]) 239 | else: 240 | config_dev_ssh(i,result[i]) 241 | print 'device_ip: %s is done !'%i 242 | print(''.ljust(101,'#')) 243 | print('\n') 244 | print "all done!" 245 | -------------------------------------------------------------------------------- /auto_show/config.py: -------------------------------------------------------------------------------- 1 | username = 'test-user' 2 | password = 'test-pass' 3 | hosts = ''' 4 | 10.11.11.11 5 | 10.12.12.12 6 | ''' 7 | cmds = ''' 8 | terminal length 0 9 | show run 10 | show redundancy 11 | show platform 12 | show log 13 | show route 14 | ''' 15 | -------------------------------------------------------------------------------- /auto_show/config.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luffycjf/auto_config_switch_router/f4de72ddb27d4ac339905ce1114592f394f8d738/auto_show/config.pyc -------------------------------------------------------------------------------- /auto_show/onecollect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #-*- coding:utf-8 -*- 3 | # author:jeffrycheng 4 | 5 | import time,re,paramiko,multiprocessing,os 6 | 7 | try: 8 | from config import * 9 | except: 10 | hosts = '' 11 | username = '' 12 | password = '' 13 | cmds = '' 14 | 15 | stdmore = re.compile(r"-[\S\s]*[Mm]ore[\S\s]*-") 16 | hostname_endcondition = re.compile(r"\S+[#>\]]\s*$") 17 | 18 | class ssh_comm(object): 19 | def __init__(self,address,username,password,port=22): 20 | self.client = paramiko.SSHClient() 21 | self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 22 | self.client.connect(address, port=port, username=username, password=password, look_for_keys=False,allow_agent=False) 23 | self.shell = self.client.invoke_shell() 24 | while True: 25 | time.sleep(0.5) 26 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 27 | break 28 | self.shell.recv(4096) 29 | self.shell.send('\n') 30 | output = self.shell.recv(4096) 31 | while True: 32 | if hostname_endcondition.findall(output): 33 | self.hostname = hostname_endcondition.findall(output)[0].strip().strip('<>[]#') 34 | break 35 | while True: 36 | time.sleep(0.1) 37 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 38 | break 39 | output += self.shell.recv(4096) 40 | def recv_all(self,interval,stdjudge,stdconfirm): 41 | endcondition = re.compile(r"%s\S*[#>\]]\s*$"%self.hostname) 42 | while True: 43 | time.sleep(interval) 44 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 45 | break 46 | output = self.shell.recv(99999) 47 | if (stdjudge != '') and (stdjudge in output): 48 | self.shell.send(stdconfirm+'\n') 49 | while True: 50 | if stdmore.findall(output.split('\n')[-1]): 51 | break 52 | elif endcondition.findall(output): 53 | break 54 | while True: 55 | time.sleep(interval) 56 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 57 | break 58 | output += self.shell.recv(99999) 59 | return output 60 | def send_command(self,command_interval,command,stdjudge,stdconfirm): 61 | command += "\n" 62 | self.shell.send(command) 63 | if ('hostname' in command) or ('sysname' in command): 64 | while True: 65 | time.sleep(0.5) 66 | if self.shell.recv_ready() or self.shell.recv_stderr_ready(): 67 | break 68 | stdout = self.shell.recv(4096) 69 | self.hostname = hostname_endcondition.findall(stdout)[-1].strip().strip('<>[]#') 70 | else: 71 | stdout = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 72 | data = stdout.split('\n') 73 | while stdmore.findall(data[-1]): 74 | self.shell.send(" ") 75 | tmp = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 76 | data = tmp.split('\n') 77 | stdout += tmp 78 | return stdout 79 | def close(self): 80 | if self.client is not None: 81 | self.client.close() 82 | def run(self,cmds,command_interval,stdjudge,stdconfirm): 83 | stdout = '' 84 | rc = 'success' 85 | for cmd in cmds.split('\n'): 86 | if cmd.strip(): 87 | stdout += self.send_command(command=cmd,command_interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm) 88 | return rc, stdout 89 | 90 | def writeoutput(address,username,password,cmds): 91 | try: 92 | connection = ssh_comm(address=address, username=username, password=password, port=22) 93 | except: 94 | rc = 'connection failed' 95 | return address,rc 96 | stdjudge = 'Y/N' 97 | stdconfirm = 'Y' 98 | rc,stdout = connection.run(cmds=cmds,command_interval=0.1,stdjudge=stdjudge,stdconfirm=stdconfirm) 99 | connection.close() 100 | hostname = connection.hostname.split('/')[-1].split(':')[-1] 101 | # hostname = os.popen('/usr/local/net-snmp/bin/snmpwalk -v 2c -c tcnw %s sysname -Oqv'%address).read().strip() 102 | if not os.path.exists(hostname): 103 | os.makedirs(hostname) 104 | filename = hostname+'-'+time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time())) 105 | with open ('%s/%s.txt'%(hostname,filename),'w') as f: 106 | f.write(stdout) 107 | return address,rc 108 | 109 | def main(username,password,hosts,cmds): 110 | if username == '': 111 | username = raw_input('请输入aaa用户名:') 112 | if password == '': 113 | password = raw_input('请输入aaa密码: ') 114 | if hosts == '': 115 | hosts = raw_input('请输入主机地址: ') 116 | if cmds == '': 117 | cmds = raw_input('请输入采集命令: ') 118 | host_list = hosts.split('\n') 119 | if len(host_list) < 5: 120 | processnum = len(host_list) 121 | else: 122 | processnum = 5 123 | pool = multiprocessing.Pool(processes=processnum ) 124 | process = [] 125 | for host in host_list: 126 | if host: 127 | process.append(pool.apply_async(writeoutput, (host.strip(),username,password,cmds))) 128 | pool.close() 129 | pool.join() 130 | outs = '' 131 | for o in process: 132 | rc,ip = o.get() 133 | print '%s: %s'%(ip,rc) 134 | 135 | if __name__== '__main__': 136 | main(username,password,hosts,cmds) 137 | -------------------------------------------------------------------------------- /autoconfig_beta/auto_config.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | # -*- coding:utf-8 -*- 3 | 4 | import paramiko,time,telnetlib,sys,os 5 | import multiprocessing 6 | 7 | try: 8 | from config import config 9 | except: 10 | config = {'config_username':'','config_password':'','ssh_port':'22','login_method':'telnet','multiprocess':'2'} 11 | 12 | def config_dev_ssh(ip, commands): 13 | username = config['config_username'] 14 | password = config['config_password'] 15 | port = 22 16 | client = paramiko.SSHClient() 17 | client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 18 | try: 19 | client.connect(ip, port , username, password, timeout=5) 20 | except: 21 | out = "device_ip: %s is can't login\n"%ip 22 | print out 23 | return out 24 | a = client.invoke_shell() 25 | a.recv('') 26 | time.sleep(1) 27 | for command in commands: 28 | a.send(command+'\r') 29 | time.sleep(1) 30 | print 'device_ip: %s is done !'%ip 31 | return a.recv('') 32 | 33 | 34 | 35 | def config_dev_tel(ip, commands): 36 | username = config['config_username'] 37 | password = config['config_password'] 38 | try: 39 | handler = telnetlib.Telnet(ip,timeout=3) 40 | handler.read_until(config['login_user_identification']) 41 | handler.write(username+'\r') 42 | handler.read_until(config['login_password_identification']) 43 | handler.write(password+'\r') 44 | except: 45 | out = "device_ip: %s is can't login\n"%ip 46 | print out 47 | return out 48 | for command in commands: 49 | handler.write(command+'\r') 50 | time.sleep(1) 51 | handler.write('$$\r') 52 | print 'device_ip: %s is done !'%ip 53 | 54 | def readconfigs(config_name): 55 | f = open(config_name) 56 | results = f.read() 57 | result = {} 58 | ip_list = [] 59 | for i in results.split('$IP:'): 60 | if i != '': 61 | for j in i.split('$CONFIG:')[0].split(): 62 | ip = j 63 | commands = [] 64 | for k in i.split('$CONFIG:')[1].split('\n'): 65 | if k != '': 66 | commands.append(k) 67 | result[ip] = commands 68 | ip_list.append(ip) 69 | return result,ip_list 70 | 71 | 72 | if __name__== '__main__': 73 | result,ip_list = readconfigs('configuration.txt') 74 | pool = multiprocessing.Pool(processes = int(config['multiprocess'])) 75 | process = [] 76 | for i in ip_list: 77 | if config['login_method'] == 'telnet': 78 | process.append(pool.apply_async(config_dev_tel, (i,result[i],))) 79 | else: 80 | process.append(pool.apply_async(config_dev_ssh, (i,result[i],))) 81 | pool.close() 82 | pool.join() 83 | print "all done!" 84 | outs = '' 85 | for o in process: 86 | outs += o.get() 87 | with open ('result.txt','a') as f: 88 | f.write(outs) 89 | -------------------------------------------------------------------------------- /autoconfig_beta/config.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | config = { 4 | 'config_username':'test', #有配置权限的帐号,如果不填会让你每次输入 5 | 'config_password':'test', #有配置权限帐号的密码,同上 6 | 'ssh_port':'22', #ssh的端口号,默认是22 7 | 'login_method':'ssh', #登录方式,填写ssh或者telnet 8 | 'login_user_identification':':', #telnet方式需要填写对应设备的登录时账户输入的标识符,本人亲测大部分就是login:和username:,用:就行,不用改 9 | 'login_password_identification':'assword:', #同上,输入密码的标识符 10 | 'multiprocess':'5' #多进程数量 11 | } 12 | 13 | -------------------------------------------------------------------------------- /autoconfig_beta/config.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luffycjf/auto_config_switch_router/f4de72ddb27d4ac339905ce1114592f394f8d738/autoconfig_beta/config.pyc -------------------------------------------------------------------------------- /autoconfig_beta/configuration.txt: -------------------------------------------------------------------------------- 1 | $IP: 2 | 1.1.1.1 3 | 2.2.2.2 4 | $CONFIG: 5 | show run 6 | show clock 7 | 8 | $IP: 9 | 3.3.3.3 10 | $CONFIG: 11 | show time 12 | -------------------------------------------------------------------------------- /autoconfig_beta/result.txt: -------------------------------------------------------------------------------- 1 | device_ip: 1.1.1.1 is can't login 2 | device_ip: 2.2.2.2 is can't login 3 | device_ip: 3.3.3.3 is can't login 4 | -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | config = { 4 | 'config_username':'test', #有配置权限的帐号,如果不填会让你每次输入 5 | 'config_password':'test', #有配置权限帐号的密码,同上 6 | 'show_username':'test_show', #只有show权限的帐号,如果不填会直接使用配置权限帐号 7 | 'show_password':'test_show', #只有show权限的帐号的密码,如果不填会直接使用配置权限帐号的密码 8 | 'ssh_port':'22', #ssh的端口号,默认是22 9 | 'login_method':'', #登录方式,填写ssh或者telnet 10 | 'login_user_identification':':', #telnet方式需要填写对应设备的登录时账户输入的标识符,本人亲测大部分就是login:和username:,用:就行,不用改 11 | 'login_password_identification':'assword:' #同上,输入密码的标识符 12 | } 13 | 14 | -------------------------------------------------------------------------------- /config.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luffycjf/auto_config_switch_router/f4de72ddb27d4ac339905ce1114592f394f8d738/config.pyc -------------------------------------------------------------------------------- /configuration.txt: -------------------------------------------------------------------------------- 1 | $IP: 2 | 10.17.17.11 3 | $CONFIG: 4 | configure terminal 5 | show vrf all 6 | $CHECK: 7 | terminal length 0 8 | show clock 9 | $CONFIG: 10 | configure terminal 11 | show vrf all 12 | show history 13 | $PING: 14 | 10.15.15.40 15 | 16 | 17 | 18 | 19 | $IP: 20 | 10.17.17.16 21 | $CONFIG: 22 | system-view 23 | display vpn-group 24 | $PING: 25 | 10.17.17.16 26 | 10.29.92.12 27 | $CONFIG: 28 | system-view 29 | display vpn-group 30 | $CHECK: 31 | screen-length 0 temporary 32 | display ip vpn-instance 33 | 34 | -------------------------------------------------------------------------------- /jietu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/luffycjf/auto_config_switch_router/f4de72ddb27d4ac339905ce1114592f394f8d738/jietu.png -------------------------------------------------------------------------------- /result.txt: -------------------------------------------------------------------------------- 1 | device_ip: 10.17.17.11 is can't login 2 | device_ip: 10.17.17.16 is can't login 3 | --------------------------------------------------------------------------------