在 Python 中通过 SFTP (Paramiko) 上传文件会导致 IOError: Failure [英] File upload through SFTP (Paramiko) in Python gives IOError: Failure

查看:49
本文介绍了在 Python 中通过 SFTP (Paramiko) 上传文件会导致 IOError: Failure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Aim: I am trying to use SFTP through Paramiko in Python to upload files on server pc.

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

What I've done: To test that functionality, I am using my localhost (127.0.0.1) IP. To achieve that I created the following code with the help of Stack Overflow suggestions.

问题:当我运行此代码并输入文件名时,尽管处理了该错误,但仍收到IOError:Failure".这是错误的快照:

Problem: The moment I run this code and enter the file name, I get the "IOError : Failure", despite handling that error. Here's a snapshot of the error:

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

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

Can you point out where's the problem and the method to resolve it? Thanks in advance!

推荐答案

SFTPClient.put (remotepath) 是文件的路径,而不是文件夹.

The second argument of SFTPClient.put (remotepath) is path to a file, not a folder.

所以使用 file_name 而不是 '.':

So use file_name instead of '.':

ftp_client.put(local_path, file_name)

... 假设您已经在 remote_path 中,因为您之前调用了 .chdir.

... assuming you are already in remote_path, as you call .chdir earlier.

为了避免需要.chdir,您可以使用绝对路径:

To avoid a need for .chdir, you can use an absolute path:

ftp_client.put(local_path, remote_path + '/' + file_name) 

这篇关于在 Python 中通过 SFTP (Paramiko) 上传文件会导致 IOError: Failure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆