Paramiko is a python library that allows you to make SSH connections. Useful when you want to automate things as you can easily ssh into remote server from your local computer.

The code down below will let you ssh to a remote server via Paramiko and then SCP files from that server to some other remote server ie. copying/transferring files from one remote server to another remote server.

Here’s what it does:

  • SSH to remote-server-1
  • Execute a psql command to export entries as a CSV file on the server
  • SCP that generated file to remote-server-2
  • Remove the generated file from remote-server-1 once its successfully copied.

Here we are copying files from remote_server_1 to remote_server_2. We ssh into remote_server_1 and then with the help of paramiko’s exec_command method, execute the terminal command to log into psql and generate a file (ie. whatever’s in ‘export’ variable). Once we execute the psql command, it will ask for password of the user. We provide the password by writing it to the stdin: stdin.write(“psql_passwordn”).

We then wait until the command has finished executing: If the execution was successful (ie status == 0), we execute another command to copy the file to remote_server_2. This command may look complex, but all we are doing here is executing scp with the help of expect. Then we finally delete the file from remote_server_1: p.exec_command(‘rm ‘ + str(ids) + ‘.csv’) .

Hope this was helpful!