I want to ssh into a server, and execute a number of bash commands on that server after logging in to that server, and I want to do that with a python script. I am limited to use subprocess (I am not allowed to import other modules like pexpect or paramiko) Here is the code I have so far:
import sys
import os
import subprocess
import time
user = "let's say a user"
host = "the remote server's ip"
sshCommand = "sshpass -p 'the remote server's password' ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s" %(user, host)
process1 = subprocess.Popen(sshCommand, shell=True, stdout = subprocess.PIPE)
copyfileCommand = "scp afile.file user@serverip: path of server directory"
process2 = subprocess.Popen(copyfileCommand, shell=True, stdin = process1.stdout, stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
pwdcommand = "pwd"
process3 = subprocess.Popen(pwdcommand, shell=True, stdin = process2.stdout, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = process3.communicate()[0]
From what I understand, to execute the second command after the first one, I need to set stdin of second command to the stdout of first command, and by the same logic, do it for the third command. However, when the script is executed to the third command, pwd gives me my local computer's path instead of the path on the remote server, and the file i want to copy to the remote server is also not copied. What am i doing wrong? This is just the first few command that I need to execute on the remote server, once I understand how it works, the other commands is easy.
thank you