使用Python中的SFTP(Paramiko)上传文件时出现IOError:Failure错误

3
目的:我想使用Python中的Paramiko通过SFTP上传服务器上的文件。
我已经做了什么:为了测试这个功能,我正在使用我的本地主机IP地址(127.0.0.1)。为了实现这一点,我根据Stack Overflow的建议创建了以下代码。
问题:当我运行这段代码并输入文件名时,尽管处理了该错误,但我会收到“IOError: Failure”的错误。以下是错误的快照:

enter image description here

import paramiko as pk
import os

userName = "sk"
ip = "127.0.0.1"
pwd = "1234"
client=""

try:
    client = pk.SSHClient()
    client.set_missing_host_key_policy(pk.AutoAddPolicy())
    client.connect(hostname=ip, port=22, username=userName, password=pwd)

    print '\nConnection Successful!' 

# This exception takes care of Authentication error& exceptions
except pk.AuthenticationException:
    print 'ERROR : Authentication failed because of irrelevant details!'

# This exception will take care of the rest of the error& exceptions
except:
    print 'ERROR : Could not connect to %s.'%ip

local_path = '/home/sk'
remote_path = '/home/%s/Desktop'%userName

#File Upload
file_name = raw_input('Enter the name of the file to upload :')
local_path = os.path.join(local_path, file_name)

ftp_client = client.open_sftp()
try:
    ftp_client.chdir(remote_path) #Test if remote path exists
except IOError:
    ftp_client.mkdir(remote_path) #Create remote path
    ftp_client.chdir(remote_path)

ftp_client.put(local_path, '.') #At this point, you are in remote_path in either case
ftp_client.close()

client.close()

你能指出问题所在和解决方法吗? 提前感谢!

1个回答

3
SFTPClient.put的第二个参数(remotepath)是指向一个文件的路径,而不是一个文件夹。
所以请使用file_name代替'.'
ftp_client.put(local_path, file_name)

假设你已经在 `remote_path` 内部,因为你之前调用了 `.chdir`。
为了避免使用.chdir,您可以使用绝对路径:
ftp_client.put(local_path, remote_path + '/' + file_name) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接