blob: 9ae90fb26f69226f37e3acdc30008390d2707265 [file] [log] [blame]
adminbae64d82013-08-01 10:50:15 -07001#!/usr/bin/env python
2'''
3Created on 24-Oct-2012
4
5@authors: Anil Kumar (anilkumar.s@paxterrasolutions.com),
6 Raghav Kashyap(raghavkashyap@paxterrasolutions.com)
7
8
9 TestON is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 2 of the License, or
12 (at your option) any later version.
13
14 TestON is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with TestON. If not, see <http://www.gnu.org/licenses/>.
21
22
23
24'''
25import pexpect
26import struct, fcntl, os, sys, signal
27import sys, re
28sys.path.append("../")
29
30from drivers.component import Component
31class CLI(Component):
32 '''
33 This will define common functions for CLI included.
34 '''
35 def __init__(self):
36 super(Component, self).__init__()
37
38 def connect(self,**connectargs):
39 '''
40 Connection will establish to the remote host using ssh.
41 It will take user_name ,ip_address and password as arguments<br>
42 and will return the handle.
43 '''
44 for key in connectargs:
45 vars(self)[key] = connectargs[key]
46
47 connect_result = super(CLI, self).connect()
48 ssh_newkey = 'Are you sure you want to continue connecting'
49 refused = "ssh: connect to host "+self.ip_address+" port 22: Connection refused"
50 if self.port:
51 self.handle =pexpect.spawn('ssh -p '+self.port+' '+self.user_name+'@'+self.ip_address,maxread=50000)
52 else :
53 self.handle =pexpect.spawn('ssh -X '+self.user_name+'@'+self.ip_address,maxread=50000)
54
55 self.handle.logfile = self.logfile_handler
Jon Halla0c6b9a2014-05-01 12:39:47 -070056 i = 5
57 while i == 5:
58 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused,'teston>','>|#|\$'],120)
59 if i==0:
60 main.log.info("ssh key confirmation received, send yes")
61 self.handle.sendline('yes')
62 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
63 if i==1:
64 main.log.info("ssh connection asked for password, gave password")
65 self.handle.sendline(self.pwd)
66 self.handle.expect('>|#|\$')
67 elif i==2:
68 main.log.error("Connection timeout")
69 return main.FALSE
70 elif i==3: #timeout
71 main.log.error("No route to the Host "+self.user_name+"@"+self.ip_address)
72 return main.FALSE
73 elif i==4:
74 main.log.error("ssh: connect to host "+self.ip_address+" port 22: Connection refused")
75 return main.FALSE
76 elif i==6:
77 main.log.info("Password not required logged in")
adminbae64d82013-08-01 10:50:15 -070078
Jon Halle80ef8c2014-04-29 15:29:13 -070079 self.handle.sendline("\n")
Jon Halla0c6b9a2014-05-01 12:39:47 -070080 self.handle.expect('>|#|\$')
adminbae64d82013-08-01 10:50:15 -070081 return self.handle
82
83
84 def disconnect(self):
85 result = super(CLI, self).disconnect(self)
86 result = main.TRUE
87 #self.execute(cmd="exit",timeout=120,prompt="(.*)")
88
89
90 def execute(self, **execparams):
91 '''
92 It facilitates the command line execution of a given command. It has arguments as :
93 cmd => represents command to be executed,
94 prompt => represents expect command prompt or output,
95 timeout => timeout for command execution,
96 more => to provide a key press if it is on.
97
98 It will return output of command exection.
99 '''
100
101 result = super(CLI, self).execute(self)
adminaef00552014-05-08 09:18:36 -0700102 defaultPrompt = '.*[$>\#]'
adminbae64d82013-08-01 10:50:15 -0700103 args = utilities.parse_args(["CMD", "TIMEOUT", "PROMPT", "MORE"], **execparams)
104 expectPrompt = args["PROMPT"] if args["PROMPT"] else defaultPrompt
105 self.LASTRSP = ""
106 timeoutVar = args["TIMEOUT"] if args["TIMEOUT"] else 10
107 cmd = ''
108 if args["CMD"]:
109 cmd = args["CMD"]
110 else :
111 return 0
112 if args["MORE"] == None:
113 args["MORE"] = " "
114 self.handle.sendline(cmd)
115 self.lastCommand = cmd
116 index = self.handle.expect([expectPrompt, "--More--", 'Command not found.', pexpect.TIMEOUT,"^:$"], timeout = timeoutVar)
117 if index == 0:
118 self.LASTRSP = self.LASTRSP + self.handle.before + self.handle.after
119 main.log.info("Executed :"+str(cmd)+" \t\t Expected Prompt '"+ str(expectPrompt)+"' Found")
120 elif index == 1:
121 self.LASTRSP = self.LASTRSP + self.handle.before
122 self.handle.send(args["MORE"])
123 main.log.info("Found More screen to go , Sending a key to proceed")
124 indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
125 while indexMore == 0:
126 main.log.info("Found anoother More screen to go , Sending a key to proceed")
127 self.handle.send(args["MORE"])
128 indexMore = self.handle.expect(["--More--", expectPrompt], timeout = timeoutVar)
129 self.LASTRSP = self.LASTRSP + self.handle.before
130 elif index ==2:
131 main.log.error("Command not found")
132 self.LASTRSP = self.LASTRSP + self.handle.before
133 elif index ==3:
134 main.log.error("Expected Prompt not found , Time Out!!")
135 main.log.error( expectPrompt )
136 return "Expected Prompt not found , Time Out!!"
137
138 elif index == 4:
139 self.LASTRSP = self.LASTRSP + self.handle.before
140 #self.handle.send(args["MORE"])
141 self.handle.sendcontrol("D")
142 main.log.info("Found More screen to go , Sending a key to proceed")
143 indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
144 while indexMore == 0:
145 main.log.info("Found anoother More screen to go , Sending a key to proceed")
146 self.handle.sendcontrol("D")
147 indexMore = self.handle.expect(["^:$", expectPrompt], timeout = timeoutVar)
148 self.LASTRSP = self.LASTRSP + self.handle.before
149
150 main.last_response = self.remove_contol_chars(self.LASTRSP)
151 return self.LASTRSP
152
153 def remove_contol_chars(self,response):
154 #RE_XML_ILLEGAL = '([\u0000-\u0008\u000b-\u000c\u000e-\u001f\ufffe-\uffff])|([%s-%s][^%s-%s])|([^%s-%s][%s-%s])|([%s-%s]$)|(^[%s-%s])'%(unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff),unichr(0xd800),unichr(0xdbff),unichr(0xdc00),unichr(0xdfff))
155 #response = re.sub(RE_XML_ILLEGAL, "\n", response)
156 response = re.sub(r"[\x01-\x1F\x7F]", "", response)
157 #response = re.sub(r"\[\d+\;1H", "\n", response)
158 response = re.sub(r"\[\d+\;\d+H", "", response)
159 return response
160
161 def runAsSudoUser(self,handle,pwd,default):
162
163 i = handle.expect([".ssword:*",default, pexpect.EOF])
164 if i==0:
165 handle.sendline(pwd)
adminaef00552014-05-08 09:18:36 -0700166 handle.sendline("\r")
adminbae64d82013-08-01 10:50:15 -0700167
168 if i==1:
169 handle.expect(default)
170
171 if i==2:
172 main.log.error("Unable to run as Sudo user")
173
174 return handle
175
176 def onfail(self):
177 if main.componentDictionary[self.name].has_key('onfail'):
178 commandList = main.componentDictionary[self.name]['onfail'].split(",")
179 for command in commandList :
180 response = self.execute(cmd=command,prompt="(.*)",timeout=120)
181
182 def secureCopy(self,user_name, ip_address,filepath, pwd,dst_path):
183
184 #scp openflow@192.168.56.101:/home/openflow/sample /home/paxterra/Desktop/
185
186 '''
187 Connection will establish to the remote host using ssh.
188 It will take user_name ,ip_address and password as arguments<br>
189 and will return the handle.
190 '''
191 ssh_newkey = 'Are you sure you want to continue connecting'
192 refused = "ssh: connect to host "+ip_address+" port 22: Connection refused"
193 self.handle =pexpect.spawn('scp '+user_name+'@'+ip_address+':'+filepath+' '+dst_path)
194 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT,refused],120)
195
196 if i==0:
197 main.log.info("ssh key confirmation received, send yes")
198 self.handle.sendline('yes')
199 i=self.handle.expect([ssh_newkey,'password:',pexpect.EOF])
200 if i==1:
201 main.log.info("ssh connection asked for password, gave password")
202 self.handle.sendline(pwd)
203 #self.handle.expect(user_name)
204
205 elif i==2:
206 main.log.error("Connection timeout")
207 pass
208 elif i==3: #timeout
209 main.log.error("No route to the Host "+user_name+"@"+ip_address)
210 return main.FALSE
211 elif i==4:
212 main.log.error("ssh: connect to host "+ip_address+" port 22: Connection refused")
213 return main.FALSE
214
adminaef00552014-05-08 09:18:36 -0700215 self.handle.sendline("\r")
adminbae64d82013-08-01 10:50:15 -0700216
217 return self.handle
218