-
Notifications
You must be signed in to change notification settings - Fork 5
/
linux.py
162 lines (138 loc) · 6.37 KB
/
linux.py
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
from paramiko import SSHClient,Transport, RSAKey, AutoAddPolicy
from sshtunnel import SSHTunnelForwarder
from scp import SCPClient
from pathlib import Path
import os
import time
class linux():
# client = None
def __init__(self, host, username="root", keyFile='', password='',port_forward=False,port=""):
self.error = ""
self.host = host
self.keyFile = keyFile
self.username = username
self.password = password
self.port_forward = port_forward
if port:
self.port = int(port)
if not self.port_forward:
if self.keyFile != '':
self.client = self.connect(self.host,self.username,keyFile=self.keyFile,password=self.password)
else:
self.client = self.connect(self.host,self.username,password=self.password)
else:
if keyFile != '':
self.client,self.sshTunnel = self.connect(self.host,self.username,keyFile=self.keyFile,password=self.password,port_forward=self.port_forward,port=self.port)
self.tunnelPort = self.sshTunnel.local_bind_port
# print(f"Binded init port is {self.tunnelPort}")
else:
self.client,self.sshTunnel = self.connect(self.host,self.username,keyFile=self.keyFile,port_forward=self.port_forward,port=self.port)
if self.client:
self.scp = self.connectSCP(self.client)
def connect(self,host,username,keyFile="",password='',port_forward=False,port=""):
try:
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(AutoAddPolicy())
if self.port_forward:
if self.keyFile != '':
try:
if password != "":
client.connect(host, username=username, key_filename=keyFile,passphrase=password, look_for_keys=True, timeout=5000)
else:
client.connect(host, username=username, key_filename=keyFile, look_for_keys=True, timeout=5000)
sshTunnel = SSHTunnelForwarder(
(host, 22),
ssh_pkey=keyFile,
ssh_username=username,
ssh_private_key_password=password,
remote_bind_address=('127.0.0.1', port))
except Exception as e:
self.error = e
return None
else:
sshTunnel = SSHTunnelForwarder(
(host, 22),
ssh_username=username,
ssh_password=password,
remote_bind_address=('127.0.0.1', port))
client.connect(host, username=username, password=password, look_for_keys=True, timeout=5000)
sshTunnel.start()
return client,sshTunnel
else:
if keyFile != '':
try:
if password != "":
client.connect(host, username=username, key_filename=keyFile, passphrase=password, look_for_keys=True, timeout=5000)
else:
client.connect(host, username=username, key_filename=keyFile, look_for_keys=True, timeout=5000)
except Exception as e:
self.error = e
return None
else:
client.connect(host, username=username, password=password, look_for_keys=True, timeout=5000)
return client
except Exception as e:
self.error = e
return None
def connectSCP(self, client):
scp = SCPClient(client.get_transport())
return scp
def disconnect(self):
if self.client:
self.client.close()
self.client = None
if self.port_forward:
self.sshTunnel.stop()
self.sshTunnel = None
def reboot(self,timeout):
# Not implimented yet!
pass
def command(self, command, args=[], elevate=False, runAs=None, timeout=300):
if self.client:
if timeout == 0:
timeout = 300
try:
if elevate:
stdin, stdout, stderr = self.client.exec_command("sudo {0} {1}".format(command, " ".join(args)).strip(),timeout=timeout)
elif runAs:
stdin, stdout, stderr = self.client.exec_command("sudo -u {0} {1} {2}".format(runAs,command, " ".join(args)).strip(),timeout=timeout)
else:
stdin, stdout, stderr = self.client.exec_command("{0} {1}".format(command, " ".join(args)).strip(),timeout=timeout)
response=[]
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
response += stdout.readlines()
else:
time.sleep(0.25)
response += stdout.readlines()
response = "".join(response)
errors = stderr.readlines()
exitCode = stdout.channel.recv_exit_status() # Cant be killed by system exit exception
return (exitCode, response, errors)
except Exception as e:
return (503, "", "{0}".format(e))
def upload(self, localFile, remotePath):
if self.scp:
try:
self.scp.put(localFile,remotePath)
return True
except:
return False
return False
def download(self, remoteFile, localPath, createMissingFolders):
if self.scp:
try:
if createMissingFolders:
splitChar = "\\"
if splitChar not in localPath:
splitChar = "/"
if not os.path.isdir(localPath.rsplit(splitChar,1)[0]):
os.makedirs(localPath.rsplit(splitChar,1)[0])
self.scp.get(remoteFile,localPath)
return True
except:
return False
return False
def __del__(self):
self.disconnect()