【问题标题】:File upload through SFTP (Paramiko) in Python gives IOError: Failure在 Python 中通过 SFTP (Paramiko) 上传文件会产生 IOError: Failure
【发布时间】:2018-04-05 04:01:41
【问题描述】:

目标:我正在尝试通过 Python 中的 Paramiko 使用 SFTP 在服务器 pc 上上传文件。

我所做的:为了测试该功能,我使用了我的 localhost (127.0.0.1) IP。为了实现这一点,我在 Stack Overflow 建议的帮助下创建了以下代码。

问题:当我运行此代码并输入文件名时,我得到了“IOError:Failure”,尽管处理了该错误。这是错误的快照:

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

您能指出问题出在哪里以及解决问题的方法吗? 提前致谢!

【问题讨论】:

    标签: python ssh sftp paramiko


    【解决方案1】:

    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) 
    

    【讨论】: