almeira-web/scripts/run_remote_script.py

41 lines
1.3 KiB
Python

import paramiko
import sys
import io
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
HOST = "161.97.93.156"
USER = "carlos"
PASSWORD = "Innova1978+*?"
def upload_and_execute(local_file, remote_file="/tmp/remote_script.py"):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=HOST, username=USER, password=PASSWORD, timeout=30)
sftp = client.open_sftp()
sftp.put(local_file, remote_file)
sftp.close()
cmd = f'echo "{PASSWORD}" | sudo -S python3 {remote_file}'
stdin, stdout, stderr = client.exec_command(cmd)
out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace')
if out:
print(out, end='')
if err:
# filter sudo password prompt
filtered = [l for l in err.splitlines() if '[sudo] password' not in l]
if filtered:
print("[ERR]:\n" + "\n".join(filtered))
client.close()
if __name__ == '__main__':
local = sys.argv[1] if len(sys.argv) > 1 else 'scripts/test_single_optimize.py'
upload_and_execute(local)