您可以将类似文件的对象作为参数传递给Python中的pysftp.CnOpts吗
我有一个 Python 脚本,它使用 pysftp 创建到远程主机的 SFTP 连接,如下所示:
cnopts = pysftp.CnOpts(knownhosts='known_hosts') # REFERENCE A STATIC FILE
sftp = pysftp.Connection(host=parm0, username=parm1, password=parm2, cnopts=cnopts)
文件“known_hosts”位于 Python 脚本所在的同一目录中。我想消除静态 Know_hosts 文件并将类似文件的对象传递给 pysftp.CnOpts() ,如下所示:
remote_public_key = subprocess.getoutput('ssh-keyscan myRemoteSFTPServer.com')
key_buffer.write(remote_public_key)
key_buffer.seek(0)
cnopts = pysftp.CnOpts(knownhosts=key_buffer.read()) # REFERENCE A FILE LIKE OBJECT
sftp = pysftp.Connection(host=parm0, username=parm1, password=parm2, cnopts=cnopts)
但是,这失败了。是否可以将类似文件的对象作为参数传递给 pysftp.CnOpts,如果可以,我该怎么做?
I have a Python script that uses pysftp to create an SFTP connection to a remote host as shown:
cnopts = pysftp.CnOpts(knownhosts='known_hosts') # REFERENCE A STATIC FILE
sftp = pysftp.Connection(host=parm0, username=parm1, password=parm2, cnopts=cnopts)
The file "known_hosts" lives in the same directory where the Python script lives. I would like to eliminate the static know_hosts file and pass a file like object to pysftp.CnOpts() like this:
remote_public_key = subprocess.getoutput('ssh-keyscan myRemoteSFTPServer.com')
key_buffer.write(remote_public_key)
key_buffer.seek(0)
cnopts = pysftp.CnOpts(knownhosts=key_buffer.read()) # REFERENCE A FILE LIKE OBJECT
sftp = pysftp.Connection(host=parm0, username=parm1, password=parm2, cnopts=cnopts)
However, this fails. Is it possible to pass a file like object as a parameter to pysftp.CnOpts, and if so, how do I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试
只传递类似文件的对象?如果您执行 key_buffer.read() ,这将相当于
缓冲区中的任何内容,并且 pysftp 可能会尝试将其解释为文件名。
否则,
(
NamedTemporaryFile
会在with
块的末尾自动删除。)Did you try
to just pass in the file-like object? If you do
key_buffer.read()
, that'd be equivalent toor whatever is in the buffer, and
pysftp
would likely try to interpret that as a filename.Failing that,
(
NamedTemporaryFile
s are automagically deleted at the end of thewith
block.)谢谢@AKX。我最终重写了我的 Python 脚本以使用 Paramiko 而不是 pysftp 并得到了一个可行的解决方案。首先,我创建了一个名为 get_remote Server_key 的函数来生成 SSH 密钥。然后我调用了 Paramiko Transport 对象的 add_server_key(pkey) 方法。这样我就不必传递类似文件的对象。
Thanks @AKX. I ended up rewriting my Python script to use Paramiko instead of pysftp and have a working solution. First I created a function called get_remote Server_key to generate an SSH key. Then I called the add_server_key(pkey) method of the Paramiko Transport object. This way I don't have to pass a file like object.