Package TestON :: Package bin :: Module generatedriver
[hide private]
[frames] | no frames]

Source Code for Module TestON.bin.generatedriver

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