gateway: Cleanup code into run_cmd

pull/92/head
remittor 1 year ago
parent a321f269f6
commit 17fccdc2b3

@ -899,51 +899,51 @@ class Gateway():
def run_cmd(self, command, msg = None, timeout = None, die_on_error = True): def run_cmd(self, command, msg = None, timeout = None, die_on_error = True):
error = 0 error = 0
if self.use_ssh: if self.use_ssh:
ssh = self.get_ssh(self.verbose) ssh = self.get_ssh(self.verbose)
else: else:
tn = self.get_telnet(self.verbose) tn = self.get_telnet(self.verbose)
if (msg): if msg:
print(msg) print(msg)
cmdlist = [ ] cmdlist = [ ]
if isinstance(command, str): if isinstance(command, str):
cmdlist.append(command) cmdlist.append(command)
else: else:
cmdlist = command cmdlist = command
if not cmdlist: if not cmdlist:
raise ValueError('Incorrect command list') raise ValueError('Incorrect command list')
for idx, cmd in enumerate(cmdlist): for idx, cmd in enumerate(cmdlist):
if self.use_ssh: if self.use_ssh:
channel = ssh.open_session() channel = ssh.open_session()
if timeout is not None: if timeout is not None:
saved_timeout = ssh.get_timeout() saved_timeout = ssh.get_timeout()
ssh.set_timeout(int(timeout * 1000)) ssh.set_timeout(int(timeout * 1000))
#channel.pty('xterm') #channel.pty('xterm')
#print("exec = '{}'".format(cmd)) #print("exec = '{}'".format(cmd))
channel.execute(cmd) channel.execute(cmd)
try: try:
channel.wait_eof() channel.wait_eof()
except ssh2.exceptions.Timeout: except ssh2.exceptions.Timeout:
ssh.set_timeout(100) ssh.set_timeout(100)
error = -4 error = -4
if die_on_error: if die_on_error:
die(f'SSH execute command timed out! CMD: "{cmd}"') die(f'SSH execute command timed out! CMD: "{cmd}"')
if timeout is not None: if timeout is not None:
ssh.set_timeout(saved_timeout) ssh.set_timeout(saved_timeout)
try: try:
channel.close() channel.close()
channel.wait_closed() channel.wait_closed()
except Exception: except Exception:
pass pass
#status = channel.get_exit_status() #status = channel.get_exit_status()
else: # telnet else: # telnet
cmd += '\n' cmd += '\n'
tn.write(cmd.encode('ascii')) tn.write(cmd.encode('ascii'))
tn.read_until(tn.prompt, timeout = 4 if timeout is None else timeout) tn.read_until(tn.prompt, timeout = 4 if timeout is None else timeout)
if error != 0: if error != 0:
break break
if not self.use_ssh: if not self.use_ssh:
tn.write(b"exit\n") tn.write(b"exit\n")
tn.close() tn.close()
return True if error == 0 else None return True if error == 0 else None
def download(self, fn_remote, fn_local, verbose = 1): def download(self, fn_remote, fn_local, verbose = 1):

Loading…
Cancel
Save