Repository navigation
Expand file tree
/
Copy pathshell.py
More file actions
169 lines (146 loc) · 6.02 KB
/
Copy pathshell.py
File metadata and controls
169 lines (146 loc) · 6.02 KB
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
# Copyright 2013 GridCentric Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import select
import socket
import subprocess
import time
from . logger import log
from . util import wait_for
class SecureShell(object):
def __init__(self, host, key_path, user, port):
self.host = host
self.key_path = key_path
self.user = user
self.port = port
assert self.host
assert self.key_path
assert self.user
assert self.port
def ssh_args(self):
return [
'ssh',
'-p', str(self.port),
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'StrictHostKeyChecking=no',
"-o", "PasswordAuthentication=no",
"-i", self.key_path,
"%s@%s" % (self.user, self.host),
]
def check_output(self, command, input=None,
expected_rc=0, expected_output=None,
exc=False):
# Run the given command through a shell on the other end.
command = self.ssh_args() + ['sh', '-c', "'%s'" % command]
ssh = subprocess.Popen(command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
# Always execute the command in one go, we don't support
# running long running commands in the test framework.
(stdout, stderr) = ssh.communicate(input)
(stdout, stderr) = (stdout.strip(), stderr.strip())
if (expected_rc != None and expected_rc != ssh.returncode) or \
(expected_output != None and stdout != expected_output):
errormsg = 'Command failed: %s\n' \
'returncode: %d\n' \
'-------------------------\n' \
'stdout:\n%s\n' \
'-------------------------\n' \
'stderr:\n%s' % (" ".join(command), ssh.returncode, stdout, stderr)
if exc:
raise Exception(errormsg)
log.error(errormsg)
assert (expected_rc == None or expected_rc == ssh.returncode)
assert (expected_output == None or expected_output == stdout)
return (stdout, stderr)
def is_alive(self):
'''Runs a dummy command through the shell. Returns True if the
shell is responsive, false otherwise. Useful for ensuring the
shell is operational.'''
try:
self.check_output('true', exc=True)
return True
except:
return False
class RootShell(SecureShell):
'''The RootShell implements a subclass of the SecureShell,
except we check if a sudo prefix is necessary when running commands.'''
def __init__(self, *args, **kwargs):
SecureShell.__init__(self, *args, **kwargs)
self.sudo = []
(whoami, err) = self.check_output('whoami')
if whoami != 'root':
self.sudo = ['sudo']
def ssh_args(self):
return super(RootShell,self).ssh_args() + self.sudo
def wait_for_shell(shell):
wait_for('shell %s to respond' % shell.host, shell.is_alive)
class WinShell(object):
def __init__(self, host, port):
self.host = host
self.port = port
log.debug("Creating link to %s on port %d." % (self.host, self.port))
def _connect(self):
# When attempting to connect immediately after boot, the
# TestListener service may not yet be initialized. Until the
# service binds the port, we'll get connection refused errors.
retries = 100
while True:
try:
retries -= 1
sock = socket.create_connection((self.host, self.port), 5)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return sock
except socket.error, exc:
log.debug("Failed to connect to %s: %s. Retrying." % \
(self.host, exc))
time.sleep(1)
if retries <= 0:
raise
def check_output(self, command, expected_output="ok", timeout=10):
sock = self._connect()
try:
log.debug("Link I: %s" % command)
sock.sendall(command)
# If timeout is None, we don't expect a response back.
if timeout is None:
return
# Do a nonblocking wait for 'timeout'.
sock.setblocking(0)
ready = select.select([sock], [], [], timeout)
if len(ready[0]) > 0 and ready[0][0] == sock:
response = sock.recv(8192)
log.debug("Link O: %s" % response.strip())
if expected_output is None or \
response.strip() == expected_output:
return response, ""
else:
raise ValueError("Link command '%s' sent unexpected " % \
command +
"response: %s. Expecting: %s." % \
(response, expected_output))
else:
raise RuntimeError("Link command '%s' timed out." % command)
finally:
sock.close()
def is_alive(self):
'''Returns True if the link is operational.'''
try:
sock = self._connect()
sock.close()
return True
except:
return False