almeira-web/ssh_run.py

36 lines
1.1 KiB
Python

import paramiko
import sys
import io
# Force UTF-8 stdout on Windows
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')
def run_ssh_command(host, user, password, command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=host, username=user, password=password, timeout=60)
stdin, stdout, stderr = client.exec_command(command)
exit_status = stdout.channel.recv_exit_status()
out = stdout.read().decode('utf-8', errors='replace')
err = stderr.read().decode('utf-8', errors='replace')
if out:
print(out)
if err:
print(err, file=sys.stderr)
sys.exit(exit_status)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
finally:
client.close()
if __name__ == "__main__":
cmd = sys.argv[1]
run_ssh_command("161.97.93.156", "carlos", "Innova1978+*?", cmd)