-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker.py
More file actions
68 lines (56 loc) · 2.1 KB
/
worker.py
File metadata and controls
68 lines (56 loc) · 2.1 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
from paramiko import SSHClient, AutoAddPolicy
from paramiko.auth_handler import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
class Config(object):
"""Worker access data"""
def __init__(self, ip, user, pwd, port=22):
self.ip = ip
self.port = port
self.user = user
self.pwd = pwd
class Worker(object):
"""Worker Object to connect and execute commands from the 'chief' worker"""
def __init__(self, config):
self.ip = config.ip
self.port = config.port
self.user = config.user
self.pwd = config.pwd
self.client = None
self.policy = AutoAddPolicy()
def connect(self):
"""Connect to the worker"""
if self.client is None:
try:
client = SSHClient()
client.set_missing_host_key_policy(self.policy)
client.connect(hostname=self.ip,
port=self.port,
username=self.user,
password=self.pwd)
except AuthenticationException:
print("Authentication failed!")
except NoValidConnectionsError:
print("Connection failed!")
finally:
client.exec_command("hostnamectl")
return client
return self.client
def exec_cmd(self, cmd, inBackground=False, timeout=None):
"""Execute command and return status and output"""
""" status 0 means no error"""
status=0
stdout='Process run in background'
self.client = self.connect()
if inBackground:
transport = self.client.get_transport()
channel = transport.open_session()
channel.setblocking(0)
channel.exec_command(cmd)
else:
stdin, stdout, stderr = self.client.exec_command(cmd)
status = stdout.channel.recv_exit_status()
if status != 0:
stdout = stderr
return status, stdout
def disconnect(self):
self.client.close()