-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathauto_config.py
244 lines (231 loc) · 9.92 KB
/
auto_config.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#! /usr/bin/python
# -*- coding:utf-8 -*-
import paramiko,time,telnetlib,sys,os,re
import threading
try:
from config import config
except:
config = {'config_username':'','config_password':'','show_username':'','show_password':'','ssh_port':'22','login_method':''}
stdmore = re.compile(r"-[\S\s]*[Mm]ore[\S\s]*-")
hostname_endcondition = re.compile(r"\S+[#>\]]\s*$")
class ssh_comm(object):
def __init__(self,address,username,password,port=22):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(address, port=port, username=username, password=password, look_for_keys=False,allow_agent=False)
self.shell = self.client.invoke_shell()
while True:
time.sleep(0.5)
if self.shell.recv_ready() or self.shell.recv_stderr_ready():
break
self.shell.recv(4096)
self.shell.send('\n')
output = self.shell.recv(4096)
while True:
if hostname_endcondition.findall(output):
self.hostname = hostname_endcondition.findall(output)[0].strip().strip('<>[]#')
break
while True:
time.sleep(0.1)
if self.shell.recv_ready() or self.shell.recv_stderr_ready():
break
output += self.shell.recv(4096)
def recv_all(self,interval,stdjudge,stdconfirm):
endcondition = re.compile(r"%s\S*[#>\]]\s*$"%self.hostname)
while True:
time.sleep(interval)
if self.shell.recv_ready() or self.shell.recv_stderr_ready():
break
output = self.shell.recv(99999)
if (stdjudge != '') and (stdjudge in output):
self.shell.send(stdconfirm+'\n')
while True:
if stdmore.findall(output.split('\n')[-1]):
break
elif endcondition.findall(output):
break
while True:
time.sleep(interval)
if self.shell.recv_ready() or self.shell.recv_stderr_ready():
break
output += self.shell.recv(99999)
return output
def send_command(self,command_interval,command,stdjudge,stdconfirm):
command += "\n"
self.shell.send(command)
if ('hostname' in command) or ('sysname' in command):
while True:
time.sleep(0.5)
if self.shell.recv_ready() or self.shell.recv_stderr_ready():
break
stdout = self.shell.recv(4096)
self.hostname = hostname_endcondition.findall(stdout)[-1].strip().strip('<>[]#')
else:
stdout = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm)
data = stdout.split('\n')
while stdmore.findall(data[-1]):
self.shell.send(" ")
tmp = self.recv_all(interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm)
data = tmp.split('\n')
stdout += tmp
return stdout
def close(self):
if self.client is not None:
self.client.close()
def run(self,cmds,command_interval,stdjudge,stdconfirm):
stderr = ['^','ERROR','Error','error','invalid','Invalid','Ambiguous','ambiguous']
stdout = ''
res = 'success'
for cmd in cmds.split('\n'):
if cmd.strip():
stdout += self.send_command(command=cmd,command_interval=command_interval,stdjudge=stdjudge,stdconfirm=stdconfirm)
for err in stderr:
if err in stdout:
res = 'some command wrong'
return res, stdout
def config_dev_ssh(ip, commands):
try_times = 0
while True:
if config['config_username'] != '' and config['config_password'] != '':
username = config['config_username']
password = config['config_password']
try_times = 2
else:
username = raw_input('请输入aaa用户名:')
password = raw_input('请输入aaa密码: ')
port = 22
try_times += 1
try:
connection = ssh_comm(address=ip, username=username, password=password, port=port)
break
except:
print 'wrong password,please try agagin!'
if try_times > 2:
sys.exit('wrong password more than tree times,out!')
if password_config['show_username'] != '' and password_config['show_password'] != '':
show_username = config['show_username']
show_password = config['show_password']
else:
show_username = username
show_password = password
connection1 = ssh_comm(address=ip, username=show_username, password=show_password, port=port)
for command in commands:
if len(command['config']) != 0:
res,stdout = connection.run(cmds=('\n').join(command['config']),command_interval=0.1,stdjudge='Y/N',stdconfirm='Y')
if len(command['check']) != 0:
res1,stdout1 = connection.run(cmds=('\n').join(command['check']),command_interval=0.1,stdjudge='Y/N',stdconfirm='Y')
print stdout1
if len(command['ping']) != 0:
threads = []
for ping_host in command['ping']:
threads.append(threading.Thread(target = getpingloss,args=(ping_host,)))
for t in threads:
t.start()
for t in threads:
t.join()
q = raw_input('请问是否继续,按q回车退出,任意键回车继续')
if q == 'q':
sys.exit()
def config_dev_tel(ip, commands):
try_times = 0
while True:
if config['config_username'] != '' and config['config_password'] != '':
username = config['config_username']
password = config['config_password']
try_times = 2
else:
username = raw_input('请输入aaa用户名:')
password = raw_input('请输入aaa密码: ')
try:
handler = telnetlib.Telnet(ip,timeout=3)
handler.read_until(config['login_user_identification'])
handler.write(username+'\r')
handler.read_until(config['login_password_identification'])
handler.write(password+'\r')
break
except:
print 'wrong password,please try agagin!'
try_times += 1
if try_times > 2:
sys.exit('wrong password more than tree times,out!')
handler1 = telnetlib.Telnet(ip,timeout=3)
handler1.read_until(config['login_user_identification'])
handler1.write(username+'\r')
handler1.read_until(config['login_password_identification'])
handler1.write(password+'\r')
for command in commands:
if len(command['config']) != 0:
for config_command in command['config']:
handler.write(config_command+'\r')
time.sleep(1)
if len(command['check']) != 0:
for check_command in command['check']:
handler1.write(check_command+'\r')
time.sleep(1)
handler1.write('$$\r')
print handler1.read_until('$$')
if len(command['ping']) != 0:
threads = []
for ping_host in command['ping']:
threads.append(threading.Thread(target = getpingloss,args=(ping_host,)))
for t in threads:
t.start()
for t in threads:
t.join()
q = raw_input('请问是否继续,按q回车退出,任意键回车继续')
if q == 'q':
sys.exit()
def getpingloss(ping_host):
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]
def readconfigs(config_name):
f = open(config_name)
results = f.read()
result = {}
ip_list = []
for i in results.split('$IP:'):
if i != '':
ip = i.split()[0]
commands = []
for j in range(len(i.split('$CONFIG:'))):
command = {}
if (j > 0) and (i.split('$CONFIG:')[j]) != '':
try:
m = i.split('$CONFIG:')[j].split('$CHECK:')[0]
command['config'] = [ x.strip() for x in m.split('\n') if x.strip() != '']
except:
m = i.split('$CONFIG:')[j].split('$PING:')[0]
command['config'] = [ x.strip() for x in m.split('\n') if x.strip() != '']
try:
n = i.split('$CONFIG:')[j].split('$CHECK:')[1].split('$PING:')[0]
command['check'] = [ y.strip() for y in n.split('\n') if y.strip() != '']
except:
command['check'] = []
try:
t = i.split('$CONFIG:')[j].split('$CHECK:')[1].split('$PING:')[1]
command['ping'] = [ z.strip() for z in t.split('\n') if z.strip() != '']
except:
try:
t = i.split('$CONFIG:')[j].split('$PING:')[1]
command['ping'] = [ z.strip() for z in t.split('\n') if z.strip() != '']
except:
command['ping'] = []
if command != {}:
commands.append(command)
result[ip] = commands
ip_list.append(ip)
return result,ip_list
if __name__== '__main__':
result,ip_list = readconfigs('configuration.txt')
if config['login_method'] == '':
config['login_method'] = raw_input('使用哪种登录方式ssh还是telnet,请输入telnet或者ssh: ')
for i in ip_list:
print(''.ljust(101,'#'))
print 'device_ip: %s is configing !'%i
if config['login_method'] == 'telnet':
config_dev_tel(i,result[i])
else:
config_dev_ssh(i,result[i])
print 'device_ip: %s is done !'%i
print(''.ljust(101,'#'))
print('\n')
print "all done!"