Python wrapper for running instances of trisurf-ng
Samo Penic
2017-01-07 1c8250e29706cc8a28402062ff61a9b9bf41a684
commit | author | age
8ab985 1 import paramiko
SP 2
3
4 class Connection:
5     def __init__(self, hostname, port=22, username=None, password=None):
6         self.hostname=hostname
7         self.port=port
8         if(username!=None):
9             self.username=username
10         else:
11             self.username=''
12         if(password!=None):
13             self.password=password
14         else:
15             self.password=''
16         self.ssh=paramiko.SSHClient()
17         self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
18         self.connected=False
19         return
20     
21     def connect(self, Timeout=5):
22         if(not self.connected):
23             try:
24                 print("Trying to connect to: "+self.username+"@"+self.hostname+":"+str(self.port)+".")
25                 self.ssh.connect(self.hostname, username=self.username, password=self.password, port=self.port, timeout=Timeout)
26                 self.connected=True
27             except:
28                 print("Error establishing connection with "+self.username+"@"+self.hostname+":"+str(self.port)+".")
29                 exit(1)
30         else:
31             print("Already connected!")
32         return
33
34     def disconnect(self):
35         if(self.connected):
36             try:
37                 self.ssh.close()
38             except:
39                 print("Cannot disconect. Unknown error.")
40         else:
41             print("Cannot disconect. Already disconnected.")
42         self.connected=False
43
44     def execute(self,command):
45         if(self.connected):
46             try:
47                 stdin,stdout,stderr=self.ssh.exec_command(command)
48                 output=stdout.readlines()
49                 errors=stderr.readlines()
50             #    print(errors)
51                 return(output)
52             except:
53                 print("Cannot execute remote commands")
54         else:
55             print("Cannot execute remote commands. Connect first.")
56
57     def send_file(self, local, remote):
58         sftp=self.ssh.open_sftp()
59         sftp.put(local,remote)
60         sftp.close()
61
62     def receive_file(self,remote,local):
63         sftp=self.ssh.open_sftp()
64         sftp.get(remote,local)
65         sftp.close()
66
67     def mkdir_remote(self,directory):
68         sftp=self.ssh.open_sftp()
69         sftp.mkdir(directory)
70         sftp.close()
71
72