目标:我试图通过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()
你能指出问题的位置和解决方法吗? 提前谢谢!
答案 0 :(得分:0)
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)