-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_tools.py
More file actions
executable file
·90 lines (78 loc) · 2.8 KB
/
Copy pathssh_tools.py
File metadata and controls
executable file
·90 lines (78 loc) · 2.8 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
"""
This file contains a library that provides methods to execute a command on a
a remote computer that is running an SSH server
"""
import paramiko
import socket
import time
import os
def is_port_open(host, port):
"""
Returns True if the port on the given host is open, False if it is not
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
sock.close()
return True
except:
return False
class sshConnection(object):
"""
This class contains methods executing commands on any computer running an
SSH server
"""
def __init__(self, serveraddress, port, username, privatekeyfile):
"""
Initializes constants used to connecting to the server and opens an
SSH conneself._privatekeyfilection
"""
self._serveraddress = serveraddress
self._port = port
self._username = username
self._connectionretries = 10
self._privkey = \
paramiko.DSSKey.from_private_key_file(privatekeyfile)
self._ssh = paramiko.SSHClient()
self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to the server
for trial in range(0, self._connectionretries):
if is_port_open(serveraddress, port):
break
elif trial == self._connectionretries:
raise RuntimeError("Failed to connect to port %d on %s after " \
"%s attempts" % \
(port, serveraddress,
self._connectionretries))
else:
time.sleep(1)
self._ssh.connect(serveraddress, username=username,
pkey=self._privkey)
def __del__(self):
self._ssh.close()
def remoteExecute(self, command, verbose=False):
"""
Executes the command over the SSH connection
"""
stdin, stdout, stderr = self._ssh.exec_command(command)
if verbose:
print "STDOUT:"
for line in stdout.readlines():
print line.strip()
print "STDERR:"
for line in stderr.readlines():
print line.strip()
def sendFile(self, localfilename, remotefilename):
"""
Sends a file from the local machine to the remote machine over the
SSH connection
"""
if not os.path.isfile(localfilename):
return False
transport = paramiko.Transport((self._serveraddress, self._port))
transport.connect(username=self._username, pkey=self._privkey)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(localfilename, remotefilename)
sftp.close()
transport.close()
return True