-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathutil.py
More file actions
59 lines (51 loc) · 1.67 KB
/
util.py
File metadata and controls
59 lines (51 loc) · 1.67 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
import StringIO
import select
import socket
import time
import paramiko
def connect_ssh(username, hostname, port, key):
key_f = StringIO.StringIO(key)
pkey = paramiko.RSAKey.from_private_key(key_f)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for _ in range(10):
try:
ssh.connect(hostname, username=username, pkey=pkey)
break
except paramiko.AuthenticationException as e:
raise paramiko.AuthenticationException(e)
except socket.error:
time.sleep(3)
else:
raise RuntimeError('SSH Connection Error')
return ssh
def exec_ssh(ssh, command, pty=False):
tran = ssh.get_transport()
chan = tran.open_session()
# NOTE: pty breaks line ordering on commands like apt-get
if pty:
chan.get_pty(term='vt100', width=80, height=24)
chan.exec_command(command)
output = read_from_ssh(chan)
exit_status = chan.recv_exit_status()
return output, exit_status
def read_from_ssh(chan):
output = ''
while True:
r, w, e = select.select([chan], [], [], 10) # @UnusedVariable
if r:
got_data = False
if chan.recv_ready():
data = r[0].recv(4096)
if data:
got_data = True
output += data
# print("stdout => ", data)
if chan.recv_stderr_ready():
data = r[0].recv_stderr(4096)
if data:
got_data = True
output += data
# print("stderr => ", data)
if not got_data:
return output