My first client-server application. It's a simple Python script that gets a list of running processes from Server_1
and writes it to a datetime-named file on Server_2
, every 5 seconds.
I am planning on refactoring this code into one or two functions, maybe one for securing the connection and one for implementing the logic.
I also know nothing about security best-practices, and I'm looking for some pointers. Any feedback on any aspect of the code is welcome.
import os
import paramiko
from time import sleep
from datetime import datetime
SERVER_1 = os.getenv('HOST_1') or ""
SERVER_1_PASS = os.getenv('PASS_1') or ""
SERVER_2 = os.getenv('HOST_2') or ""
SERVER_2_PASS = os.getenv('PASS_2') or ""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(SERVER_1, username='root', password=SERVER_1_PASS)
ssh2 = paramiko.SSHClient()
ssh2.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh2.connect(SERVER_2, username='root', password=SERVER_2_PASS)
while True:
now = datetime.now()
dt_string = now.strftime("%d-%m-%YT%H:%M:%S")
stdin, stdout, stderr = ssh.exec_command("ps -aux")
processes = stdout.readlines()
output = [line.strip() for line in processes]
ftp = ssh2.open_sftp()
try:
file = ftp.file(dt_string, "a", -1)
file.write('\n'.join(output))
file.flush()
ftp.close()
except IOError as e:
print("Could not write to file")
print(e)
sleep(5)
```