File upload through SFTP (Paramiko) in Python gives IOError: Failure

倾然丶 夕夏残阳落幕 提交于 2019-12-08 07:37:21

问题


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

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.

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!


回答1:


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

So use file_name instead of '.':

ftp_client.put(local_path, file_name)

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


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

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


来源:https://stackoverflow.com/questions/49663947/file-upload-through-sftp-paramiko-in-python-gives-ioerror-failure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!