ssh - Upload files using SFTP in Python, but create directories if path doesn't exist -
i want upload file on remote server python. i'd check beforehand if remote path existing, , if isn't, create it. in pseudocode:
if(remote_path not exist): create_path(remote_path) upload_file(local_file, remote_path)
i thinking executing command in paramiko create path (e.g. mkdir -p remote_path
). came this:
# didn't test 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 solution doesn't sound me, because close connection , reopen again. there improve way it?
sftp supports usual ftp commands (chdir, mkdir, etc...), utilize those:
sftp = paramiko.sftpclient.from_transport(transport) try: sftp.chdir(remote_path) # test if remote_path exists except ioerror: sftp.mkdir(remote_path) # create remote_path sftp.chdir(remote_path) sftp.put(local_path, '.') # @ point, in remote_path in either case sftp.close()
to emulate mkdir -p
, can work through remote_path recursively:
import os.path def mkdir_p(sftp, remote_directory): """change directory, recursively making new folders if needed. returns true if folders created.""" if remote_directory == '/': # absolute path alter directory root sftp.chdir('/') homecoming if remote_directory == '': # top-level relative directory must exist homecoming try: sftp.chdir(remote_directory) # sub-directory exists except ioerror: dirname, basename = os.path.split(remote_directory.rstrip('/')) mkdir_p(sftp, dirname) # create parent directories sftp.mkdir(basename) # sub-directory missing, created sftp.chdir(basename) homecoming true sftp = paramiko.sftpclient.from_transport(transport) mkdir_p(sftp, remote_path) sftp.put(local_path, '.') # @ point, in remote_path sftp.close()
of course, if remote_path contains remote file name, needs split off, directory beingness passed mkdir_p , filename used instead of '.' in sftp.put.
python ssh sftp paramiko
No comments:
Post a Comment