I want to upload a file on a remote server with Python. I'd like to check beforehand if the remote path is really existing, and if it isn't, to create it. In pseudocode:
if(remote_path not exist):
create_path(remote_path)
upload_file(local_file, remote_path)
I was thinking about executing a command in Paramiko to create the path (e.g. mkdir -p remote_path
). I came up with this:
# I didn't test this code
import paramiko, sys
ssh = paramiko.SSHClient()
ssh.connect(myhost, 22, myusername, mypassword)
ssh.exec_command('mkdir -p ' + remote_path)
ssh.close
transport = paramiko.Transport((myhost, 22))
transport.connect(username = myusername, password = mypassword)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_path, remote_path)
sftp.close()
transport.close()
But this solution doesn't sound good to me, because I close the connection and then reopen it again. Is there a better way to do it?
Had to do this today. Here is how I did it.
Paramiko contains a mkdir function:
http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html#paramiko.sftp_si.SFTPServerInterface.mkdir
Something simpler and slightly more readable too
Assuming sftp operations are expensive, I would go with:
SFTP supports the usual FTP commands (chdir, mkdir, etc...), so use those:
To fully emulate
mkdir -p
, you can work through remote_path recursively:Of course, if remote_path also contains a remote file name, then it needs to be split off, the directory being passed to mkdir_p and the filename used instead of '.' in sftp.put.