无需输入密码的 Paramiko 或 sshtunnel 和 ssh-agent

Paramiko or sshtunnel and ssh-agent without entering passphrase

我正在尝试使用 sshtunnel 创建到服务器的隧道。我正在使用 ssh-key 和 ssh-agent:

from sshtunnel import SSHTunnelForwarder

with SSHTunnelForwarder(
    (proxyhost, 22),
    ssh_username=ssh_username,
    #ssh_private_key_password=PASSPHRASE, # with this line it works
    remote_bind_address=('127.0.0.1', 3306),
) as tunnel:
    pass

找到了正确的私钥,当我将密码作为参数时,隧道就建立了(见上面的注释行)。

但是我已经用 ssh-agent 解锁了我的 ssh 私钥(我在重启后第一次使用 ssh 时只被要求提供我的 ssh 密码)。是否可以让 paramiko/sshtunnel 在不提示输入密码的情况下获取解锁的私钥?我想避免将我的密码存储在磁盘上的任何位置。

我在这个问题上遇到了麻烦,最后想出了一个解决方案。我试图使用 alembic 进行 运行 迁移,需要通过 ssh 隧道。如果它是 运行ning,SSHTunnel 应该可以访问您的代理,但它也会产生如下错误:

    ERROR [sshtunnel.SSHTunnelForwarder:1233][MainThread] Password is required for key  

通过导入 paramiko 然后使用 paramiko.agent.Agent().get_keys().

,我能够访问存储在 macOS 钥匙串中的加密密钥

这是您更新后的代码:

from sshtunnel import SSHTunnelForwarder
import paramiko

with SSHTunnelForwarder(
    (proxyhost, 22),
    ssh_username=ssh_username,
    ssh_pkey=paramiko.agent.Agent().get_keys(),
    remote_bind_address=('127.0.0.1', 3306),
) as tunnel:
    pass