blob: f8e342228837b27cd156da475cdd612ba861d5e1 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
2'''
3Created on 11-Oct-2012
4
5@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
6
7 TestON is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
11
12 TestON is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with TestON. If not, see <http://www.gnu.org/licenses/>.
19
20
21
22'''
23import pexpect
24import struct, fcntl, os, sys, signal
25import sys
26import re
27sys.path.append("../")
28from core import xmldict
29
30class GenerateDriver():
31 '''
32 This will
33 '''
34 def __init__(self):
35 self.default = ''
36 self.prompt = '>'
37 self.LASTRSP =''
38 self.command_dictionary = {}
39 self.config_details = {}
40 self.last_sub_command = None
41 self.commnads_ordered_list = []
42 filePath = "generatedriver.cfg"
43 self.configFile = filePath
44 try :
45 xml = open(filePath).read()
46 self.config_details = xmldict.xml_to_dict(xml)
47 except :
48 print "Error : Config file " + self.configFile + " not defined properly or file path error"
49 sys.exit()
50 print self.config_details
51 self.device_name = ''
52
53 def connect(self,**connectargs):
54 '''
55 Connection will establish to the remote host using ssh.
56 It will take user_name ,ip_address and password as arguments<br>
57 and will return the handle.
58 '''
59 for key in connectargs:
60 vars(self)[key] = connectargs[key]
61
62 ssh_newkey = 'Are you sure you want to continue connecting'
63 refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
64 if self.port:
65 self.handle =pexpect.spawn('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address,maxread=50000)
66 else :
67 self.handle =pexpect.spawn('ssh '+self.user_name+'@'+self.ip_address,maxread=50000)
68
69 self.logfile_handler = open(os.getcwd()+"/GenerateDriver.log","w+")
70 self.handle.logfile = self.logfile_handler
71 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],10)
72
73 if i==0:
74 self.handle.sendline('yes')
75 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT])
76 return self.handle
77 if i==1:
78 self.handle.sendline(self.pwd)
79 self.handle.expect('>|#|$')
80 return self.handle
81 elif i==2:
82 print "ssh: connect to host "+self.ip_address+": Error"
83 return False
84 elif i==3: #timeout
85
86 print "ssh: connect to host "+self.ip_address+": Connection timed out"
87 return False
88 elif i==4:
89 print "ssh: connect to host "+self.ip_address+": Connection refused"
90 return False
91
92 self.handle.sendline("\r")
93 return self.handle
94
95 def execute(self, **execparams):
96 '''
97 This method will execute the command and will check for the expected prompt.
98 '''
99 self.LASTRSP = ''
100 defaultPrompt = '.*[\$>\#]'
101 for key in execparams:
102 vars(self)[key] = execparams[key]
103
104 self.handle.sendline(self.cmd)
105 timeoutVar = self.timeout if self.timeout else 10
106
107 index = self.handle.expect([self.prompt, "byte\s\d+", 'Command not found.', pexpect.TIMEOUT,"\n:",pexpect.EOF], timeout = timeoutVar)
108 if index == 0:
109 self.LASTRSP = self.LASTRSP + self.handle.before
110 #print "Expected Prompt Found"
111 elif index == 1:
112 self.LASTRSP = self.LASTRSP + self.handle.before
113 self.handle.send("\r")
114 print("Found More screen to go , Sending a key to proceed")
115 indexMore = self.handle.expect(["byte\s\d+", self.prompt], timeout = timeoutVar)
116 while indexMore == 0:
117 print "Found another More screen to go , Sending a key to proceed"
118 self.handle.send("\r")
119 indexMore = self.handle.expect(["byte\s\d+", self.prompt,pexpect.EOF,pexpect.TIMEOUT], timeout = timeoutVar)
120 self.LASTRSP = self.LASTRSP + self.handle.before
121 #print self.LASTRSP
122 elif index ==2:
123 print "Command not found"
124 self.LASTRSP = self.LASTRSP + self.handle.before
125 elif index ==3:
126 print "Expected Prompt not found , Time Out!!"
127 return False
128 elif index == 4:
129
130 self.LASTRSP = self.LASTRSP + self.handle.before
131 self.handle.sendcontrol("D")
132 #print "AA"*89
133 indexMore = self.handle.expect(["\n:", self.prompt,pexpect.EOF,pexpect.TIMEOUT], timeout = timeoutVar)
134 while indexMore == 0:
135 self.handle.sendcontrol("D")
136
137 indexMore = self.handle.expect(["\n:", self.prompt,".*",pexpect.EOF,pexpect.TIMEOUT], timeout = timeoutVar)
138 self.LASTRSP = self.LASTRSP + self.handle.before
139
140 return self.LASTRSP
141
142 def configure(self):
143 '''
144 Will start the Configure mode of the device.
145 '''
146 config_result = self.execute(cmd="configure",prompt='\#',timeout=10)
147 return config_result
148
149 def get_command_help(self,command):
150 '''
151 Will get the help of the Command
152 '''
153
154 self.handle.setecho(False)
155 help_keyword = self.config_details['device'][self.device_name]['help_keyword']
156 interrupt_key = self.config_details['device'][self.device_name]['interrupt_key']
157 command_details = self.execute(cmd=command+" "+help_keyword,prompt='\#',timeout=2)
158 #command_details = self.execute(cmd=command+" "+help_keyword,prompt='\#',timeout=2)
159 self.handle.sendcontrol(interrupt_key)
160 #print command_details
161 return command_details
162
163 def get_command_details(self,command):
164 '''
165 Will Update the command_dictionary with the available commands details
166 '''
167
168 temp_dictionary = {}
169 command_resulut = self.get_command_help(command)
170 try :
171 words = command_resulut.split("\n")
172 except AttributeError,e:
173 print e
174 return
175 lines = command_resulut.split("\n")
176 options_list = []
177 for line in lines :
178 value_match = re.search('[\s|\>|\+|\-|\<]{3}(\<(\w+))\s*',line)
179 if value_match:
180 print " Enter Value for "+value_match.group(2)
181 #self.handle.interact()
182 else:
183 match = re.search(r"\s\s[\w|-]+\s\s",line)
184 if match :
185 match_command = match.group(0)
186 print match_command
187 options_list.append(match_command)
188
189 temp_dictionary[command] = options_list
190 self.command_dictionary[command] = options_list
191 self.print_details(self.command_dictionary)
192 print "temp dir: --------"
193 print temp_dictionary
194 print "-------------"
195 return temp_dictionary
196
197 def print_details(self,command_dictionary):
198 '''
199 Will print the details in Tree Format
200 '''
201 self.commnads_ordered_list = command_dictionary.keys()
202 # Sorting the output based on the length of the command string
203 length = len(self.commnads_ordered_list ) - 1
204 sorted = False
205
206 while not sorted:
207 sorted = True
208 for i in range(length):
209 if len(self.commnads_ordered_list[i]) > len(self.commnads_ordered_list[i+1]):
210 sorted = False
211 self.commnads_ordered_list[i], self.commnads_ordered_list[i+1] = self.commnads_ordered_list[i+1], self.commnads_ordered_list[i]
212
213 for key in self.commnads_ordered_list:
214 print key +"\t "+str(command_dictionary[key])
215 print "\n\n"
216
217
218 def get_details_recursive(self,main_comand):
219 try :
220 self.last_sub_command = main_comand.split()[len(main_comand.split())-1]
221 except :
222 self.last_sub_command = ''
223 main_result_dcitionary = self.get_command_details(main_comand)
224 if main_result_dcitionary :
225 for key in main_result_dcitionary.keys():
226 for index, each_option in enumerate(main_result_dcitionary[key]) :
227
228 if re.search(self.config_details['device'][self.device_name]['end_pattern']+"|^\.|^\d",str(main_result_dcitionary[key][index])):
229 print "Reached the last argument for this "+main_comand+" "+str(each_option)+"\n"
230 main_result_dcitionary[key].remove(each_option)
231 return
232 elif self.last_sub_command == str(main_result_dcitionary[key][index]):
233 print "Same command repeating, So Exiting "+main_comand+" "+str(each_option)+"\n"
234 main_result_dcitionary[key].remove(each_option)
235 break
236 result_dcitionary = self.get_details_recursive(main_comand+" "+str(each_option))
237
238 return
239 def create_driver(self):
240 name = self.device_name
241 driver_file_data = 'class '+name +":\n"
242 driver_file_data = driver_file_data + " def __init__( self ):\n"
243 driver_file_data = driver_file_data + " self.prompt = '(.*)'\n self.timeout = 60 \n\n"
244
245 for index,command in enumerate(self.commnads_ordered_list) :
246 api_data = ' def '
247 command_as_api = re.sub(" ","_" , command, 0)
248 command_as_api = re.sub("\.|\-|\\|\/|\/","" , command_as_api, 0)
249 current_letter = 0
250 underscore_count = 0
251 command_temp = ""
252 for c in command_as_api:
253 current_letter = current_letter + 1
254 if c == "_":
255 underscore_count = underscore_count+1
256 else:
257 underscore_count = 0
258 if underscore_count > 1:
259 command_temp = command_temp + ""
260 else:
261 command_temp = command_temp + c
262 if command_temp[len(command_temp)-1] == "_":
263 command_temp = command_temp[0:len(command_temp)-1]
264 command_as_api = command_temp
265 #options = ''
266 #for option in self.command_dictionary[command]:
267 #options = options+',' + option
268
269 #options = re.sub("^\s*,|,$","" , options, 0)
270 api_data = api_data + command_as_api+"(self, *options, **def_args ):\n"
271 api_data = api_data + " '''Possible Options :"+str(self.command_dictionary[command])+"'''\n"
272 api_data = api_data + " arguments= ''\n"
273 api_data = api_data + " for option in options:\n"
274 api_data = api_data + " arguments = arguments + option +' ' \n"
275 api_data = api_data + " prompt = def_args.setdefault('prompt',self.prompt)\n"
276 api_data = api_data + " timeout = def_args.setdefault('timeout',self.timeout)\n"
277
278 api_data = api_data + " self.execute( cmd= \""+ command + " \"+ arguments, prompt = prompt, timeout = timeout ) \n"
279 api_data = api_data + " return main.TRUE\n"
280
281 driver_file_data = driver_file_data + api_data +"\n"
282 driver_file = open(os.getcwd()+"/"+name.lower()+".py", 'w')
283 driver_file.write(driver_file_data)
284 print driver_file_data
285
286 def disconnect(self):
287 result = True
288 return result
289
290 import pexpect
291
292if __name__ == "__main__":
293
294 generate = GenerateDriver()
295 import sys
296 device_name = sys.argv[1]
297 generate.device_name = device_name
298 ip_address = generate.config_details['device'][device_name]['ip_address']
299 user_name = generate.config_details['device'][device_name]['user_name']
300 password = generate.config_details['device'][device_name]['password']
301 command = generate.config_details['device'][device_name]['command']
302 commandlist = re.sub("(\[|\])", "", command)
303 commandlist = list(eval(command+','))
304 connect_handle = generate.connect(user_name = user_name ,ip_address = ip_address, pwd = password , port = None)
305 if connect_handle :
306 # generate.configure()
307
308 for root_command in commandlist :
309 generate.get_details_recursive(root_command)
310
311 generate.create_driver()
312 generate.disconnect()
313 #generate.get_command_details(main_command)
314 else :
315 print "Connection Failed to the host"
316
317