Python – Upload a file in Python via SFTP (Paramiko) to give IOError : Failure

Upload a file in Python via SFTP (Paramiko) to give IOError : Failure… here is a solution to the problem.

Upload a file in Python via SFTP (Paramiko) to give IOError : Failure

Goal: I’m trying to upload a file on a server PC using SFTP via Paramiko in Python.

What I did: To test the feature, I used my localhost (127.0.0.1) IP. To do this, I created the following code with the help of Stack Overflow suggestions.

Problem: When I run this code and enter the filename, I get “IOError: Failed”, despite handling that error. This is a snapshot of the error:

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

Can you point out what the problem is and how to fix it?
Thanks in advance!

Solution

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

So use file_name instead of ‘.':

ftp_client.put(local_path, file_name)

… Let’s say you’re already in remote_path because you called .chdir earlier.


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

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

Related Problems and Solutions