0
|
1 """
|
|
2 crappy python ssh wrapper
|
|
3 """
|
|
4
|
|
5 # imports
|
|
6 import subprocess
|
|
7
|
|
8 string = (str, unicode)
|
|
9
|
|
10
|
|
11 def call(command, check=True, echo=True, **kwargs):
|
|
12
|
|
13 cmd_str = command if isinstance(command, string) else subprocess.list2cmdline(command)
|
|
14 kwargs['shell'] = isinstance(command, string)
|
|
15 kwargs['stdout'] = subprocess.PIPE
|
|
16 kwargs['stderr'] = subprocess.PIPE
|
|
17 if echo:
|
|
18 print (cmd_str)
|
|
19 process = subprocess.Popen(command, **kwargs)
|
|
20 stdout, stderr = process.communicate()
|
|
21 if check and process.returncode:
|
|
22 raise subprocess.CalledProcessError(process.returncode, command, stdout)
|
|
23 return process.returncode, stdout, stderr
|
|
24
|
|
25
|
|
26 class Ssh(object):
|
|
27 """primative form of ssh session using subprocess"""
|
|
28
|
|
29 def __init__(self, host, ssh='ssh', scp='scp', verbose=False):
|
|
30 self.host = host
|
|
31 self._ssh = ssh
|
|
32 self._scp = scp
|
|
33 self.verbose=verbose
|
|
34
|
|
35 def command(self, command):
|
|
36
|
|
37 # See:
|
|
38 # http://unix.stackexchange.com/questions/122616/why-do-i-need-a-tty-to-run-sudo-if-i-can-sudo-without-a-password
|
|
39 # http://unix.stackexchange.com/a/122618
|
|
40 return [self._ssh, '-t', self.host, command]
|
|
41
|
|
42 def sudo_command(self, command):
|
|
43 return self.command('sudo ' + command)
|
|
44
|
|
45 def call(self, command):
|
|
46 returncode, output, _ = call(self.command(command),
|
|
47 echo=self.verbose)
|
|
48 return (returncode, output)
|
|
49
|
|
50 def sudo(self, command):
|
|
51 returncode, output, _ = call(self.sudo_command(command),
|
|
52 echo=self.verbose)
|
|
53 return (returncode, output)
|
|
54
|
|
55 def scp(self, src, dest):
|
|
56 """scp a file to the given host"""
|
|
57
|
|
58 command = [self._scp,
|
|
59 src,
|
|
60 '{host}:{dest}'.format(host=self.host, dest=dest)]
|
|
61 returncode, output, _ = call(command)
|
|
62 return (returncode, output)
|