fra*_*zon 24 python ssh sftp paramiko
我想用Python上传远程服务器上的文件.我想事先检查远程路径是否真的存在,如果不存在,则要创建它.在伪代码中:
if(remote_path not exist):
create_path(remote_path)
upload_file(local_file, remote_path)
Run Code Online (Sandbox Code Playgroud)
我正在考虑在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()
Run Code Online (Sandbox Code Playgroud)
但是这个解决方案对我来说听起来不太好,因为我关闭连接然后再次重新打开它.有没有更好的方法呢?
ise*_*dev 42
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()
Run Code Online (Sandbox Code Playgroud)
要完全模拟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()
Run Code Online (Sandbox Code Playgroud)
当然,如果remote_path还包含远程文件名,则需要将其拆分,将目录传递给mkdir_p并使用文件名而不是'.' 在sftp.put中.
更简单,更易读的东西
def mkdir_p(sftp, remote, is_dir=False):
"""
emulates mkdir_p if required.
sftp - is a valid sftp object
remote - remote path to create.
"""
dirs_ = []
if is_dir:
dir_ = remote
else:
dir_, basename = os.path.split(remote)
while len(dir_) > 1:
dirs_.append(dir_)
dir_, _ = os.path.split(dir_)
if len(dir_) == 1 and not dir_.startswith("/"):
dirs_.append(dir_) # For a remote path like y/x.txt
while len(dirs_):
dir_ = dirs_.pop()
try:
sftp.stat(dir_)
except:
print "making ... dir", dir_
sftp.mkdir(dir_)
Run Code Online (Sandbox Code Playgroud)
小智 6
今天不得不这样做。这是我如何做到的。
def mkdir_p(sftp, remote_directory):
dir_path = str()
for dir_folder in remote_directory.split("/"):
if dir_folder == "":
continue
dir_path += r"/{0}".format(dir_folder)
try:
sftp.listdir(dir_path)
except IOError:
sftp.mkdir(dir_path)
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用 pysftp 包:
import pysftp as sftp
#used to pypass key login
cnopts = sftp.CnOpts()
cnopts.hostkeys = None
srv = sftp.Connection(host="10.2.2.2",username="ritesh",password="ritesh",cnopts=cnopts)
srv.makedirs("a3/a2/a1", mode=777) # will happily make all non-existing directories
Run Code Online (Sandbox Code Playgroud)
您可以检查此链接以获取更多详细信息: https://pysftp.readthedocs.io/en/release_0.2.9/cookbook.html#pysftp-connection-mkdir
归档时间: |
|
查看次数: |
37769 次 |
最近记录: |