I am running a python script - ssh.py on my local machine to transfer file and directory from one remote server (ip = 35.189.168.20) to another remote server (ip = 10.243.96.94)
This is how my code looks:
HOST = "35.189.168.207"
USER = "sovith"
PASS = "xxx"
destHost = "10.243.96.94"
destUser = "root"
destPass = "xxx"
#SSH Connection
client1=paramiko.SSHClient()
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client1.connect(HOST,username=USER,password=PASS)
#SFTP inside SSH server connection
with pysftp.Connection(host=destHost, username=destUser, password=destPass) as sftp:
#put build directory - sftp.put_r(source, destination)
sftp.put_r('/home/sovith/build' , '/var/tmp')
sftp.close()
client1.close()
Let me just tell you that all directory paths and everything is correct. I just feel that there's some logically mistake inside the code. The output i got after execution is :
Traceback (most recent call last):
File "ssh.py", line 108, in <module>
func()
File "ssh.py", line 99, in func
sftp.put_r('/home/sovith/nfmbuild' , '/var/tmp')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pysftp/__init__.py", line 427, in put_r
os.chdir(localpath)
FileNotFoundError: [Errno 2] No such file or directory: '/home/sovith/build'
Can you just correct the mistake from my code or suggest any better method to accomplish the task. In simpler words, i want a script to copy files and directory between two remote server.
That's not possible. Not the way you do it. The fact that you open a connection to one remote server, does not make the following code magically work, as if it was executed on that server. It still runs on the local machine. So the code is trying to upload local files (which do not exist).
There's actually no way to transfer files between two remote SFTP servers from local machine.
In general, you will need to download the files from the first server to a local temporary directory. And then upload them to the second server.
See Python PySFTP transfer files from one remote server to another remote server
Another option is to connect to one remote server using SSH and then run SFTP client on the server to transfer the files to/from the second server.
But that's not copying from one SFTP server to another SFTP server. That's copying from one SSH server to SFTP server. You need an SSH access, mere SFTP access is not enough.
To execute a command of a remote SSH server, use pysftp Connection.execute
. Though using pysftp to execute a command on a server is a bit overkill. You can use directly Paramiko instead:
Python Paramiko - Run command
(pysftp is just a wrapper around Paramiko with more advanced SFTP functions)