我需要连接到 SFTP,下载最新的文件,然后更改文件名并再次加载到同一 SFTP 文件夹并删除“原始名称”文件。我已使用用户名和密码通过 FTP 完成此操作,但在本例中,SFTP 有一个密钥文件 (.ppk)。如何将密钥文件设置为密码?
谢谢!
import pysftp
srv = pysftp.Connection(host="your_FTP_server", username="your_username",
password="your_password")
# Get the directory and file listing
data = srv.listdir()
# Closes the connection
srv.close()
# Prints out the directories and files, line by line
for i in data:
print i
要使用密钥文件进行连接,您需要在创建连接时传递密钥文件的路径。为此,您需要将参数“private_key”设置为文件的路径。
上面的代码应该如下所示:
srv = pysftp.Connection(host="you_FTP_server", username="your_username", private_key="./Path/To/File")
当pySFTP发起连接时,它会尝试使用你传入的文件。如果由于密钥文件而失败,则会抛出身份验证异常。
这是我找到答案的链接:https://pysftp.readthedocs.io/en/release_0.2.7/pysftp.html.
指定仅当服务器有密码时才使用“密码”,这一点很重要。如果您的私钥受密码保护,则必须使用“private_key_pass”。
因此,要使用公钥/私钥连接到远程服务器,您需要:
1)上传公钥到服务器
2)用你的私钥+私钥密码创建连接:
srv = pysftp.Connection(host="host", username="username", private_key="file_with_private_key", private_key_pass="password")
我遇到了类似的问题,下面提到的步骤可能会对您有所帮助。它对我有用
pip install 'pysftp>=0.2.8'
sftp_client = pysftp.Connection(host='x.x.x.x',username='ftpuser-name ',private_key="filename")
您可以使用 paramiko 代替 Pysftp。如果您有 putty 格式的私钥,请首先将其更改为 openssh 格式。使用腻子生成。之后,您可以将 openssl 私钥传递给 paramiko 并执行 sftp。
# get private key for paramiko
private_key_content= 'ohik2n3xxxxxxxxxx'
in_memory_private_key_file = io.StringIO(private_key_content)
private_key = paramiko.RSAKey.from_private_key(in_memory_private_key_file, password=private_key_passphrase)
# create SSH client and connect to sftp host
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(sftp_host, username=sftp_user, pkey=private_key, allow_agent=False, look_for_keys=False,
disabled_algorithms={'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']})
sftp_client = ssh_client.open_sftp()
sftp_client.chdir(sftp_folder)
sftp_client.putfo(data, output_filename)
```