在Python中使用SFTP上传文件,但如果路径不存在,则创建目录

我想使用Python在远程服务器上上传文件。我想事先检查远程路径是否确实存在,如果不存在,请创建它。用伪代码:

if(remote_path not exist):

create_path(remote_path)

upload_file(local_file, remote_path)

我正在考虑在Paramiko中执行命令来创建路径(例如mkdir -p remote_path)。我想出了这个:

# 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()

但是这种解决方案对我来说听起来不太好,因为我先关闭了连接,然后再次重新打开。有更好的方法吗?

回答:

SFTP支持常用的FTP命令(chdir,mkdir等),因此请使用以下命令:

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, '.') # At this point, you are in remote_path in either case

sftp.close()


要完全仿真mkdir -p,您可以递归地遍历remote_path:

import os.path

def mkdir_p(sftp, remote_directory):

"""Change to this directory, recursively making new folders if needed.

Returns True if any folders were created."""

if remote_directory == '/':

# absolute path so change directory to root

sftp.chdir('/')

return

if remote_directory == '':

# top-level relative directory must exist

return

try:

sftp.chdir(remote_directory) # sub-directory exists

except IOError:

dirname, basename = os.path.split(remote_directory.rstrip('/'))

mkdir_p(sftp, dirname) # make parent directories

sftp.mkdir(basename) # sub-directory missing, so created it

sftp.chdir(basename)

return True

sftp = paramiko.SFTPClient.from_transport(transport)

mkdir_p(sftp, remote_path)

sftp.put(local_path, '.') # At this point, you are in remote_path

sftp.close()

当然,如果remote_path也包含一个远程文件名,则需要将其拆分,将目录传递给mkdir_p并使用文件名代替“。”。在sftp.put中。

以上是 在Python中使用SFTP上传文件,但如果路径不存在,则创建目录 的全部内容, 来源链接: utcz.com/qa/429879.html

回到顶部