简体   繁体   English

Paramiko 的 SFTP Python 连接

[英]Paramiko's SFTP Python connection

I'm trying to set up an SFTP connection with Python (v2.7) using Paramiko's library http://docs.paramiko.org/en/2.1/api/sftp.html我正在尝试使用 Paramiko 的库http://docs.paramiko.org/en/2.1/api/sftp.html与 Python (v2.7) 建立 SFTP 连接

From bits and pieces online I was able to (I think so anyway) connect using a private encrypted certificate.从网上的零碎开始,我能够(无论如何我都这么认为)使用私有加密证书进行连接。

This looks as follows:这看起来如下:

import paramiko
sftp = paramiko.SSHClient()

hostname = "sftp.host.com"
port = 8022
username = "sftplogin"

k = paramiko.RSAKey.from_private_key_file("private.pem", password="XXX")
sftp.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "Connecting..."
sftp.connect(hostname, port, username=username, pkey=k )
print "Connected to: " + hostname + ":" + port
print sftp.getcwd()
sftp.close()

At this point, I'm just trying to see if I'm not delusional and in fact did not connect, so I'm attempting to print a getcwd() to get the current directory ... Sadly I'm getting nowhere, as it's returning this error:在这一点上,我只是想看看我是否没有妄想并且实际上没有连接,所以我试图打印一个 getcwd() 来获取当前目录......遗憾的是我无处可去,因为它返回此错误:

AttributeError: 'SSHClient' object has no attribute 'getcwd' AttributeError: 'SSHClient' 对象没有属性 'getcwd'

Can anyone tell me why?谁能告诉我为什么? What am I doing wrong?我究竟做错了什么?

Thanks in advance!提前致谢!

This has worked for me.这对我有用。

import os
import paramiko

host = "sftp.host.com"
port = 8022
transport = paramiko.Transport((host, port))
username = "sftplogin"
mykey = paramiko.RSAKey.from_private_key_file("private_export.pem", password="XXX")
print "Connecting..."
transport.connect(username = username, pkey = mykey)
sftp = paramiko.SFTPClient.from_transport(transport)
print "Connected."
print sftp.listdir()
sftp.close()
transport.close()
print "Closed connection."

You instantiated a paramiko.SSHClient object, but you're trying to execute SFTP Client methods .您实例化了一个paramiko.SSHClient对象,但您正在尝试执行SFTP Client methods

You should be able to execute this to demonstrate that fact:您应该能够执行此操作来证明这一事实:

sftp.exec_command('pwd')

But I think you meant to instantiate the SFTP class, rather than the SSH client, so that is probably where you went wrong.但我认为您打算实例化 SFTP 类,而不是 SSH 客户端,所以这可能是您出错的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM