【问题标题】:How to use Paramiko with host definition in ~/.ssh/config? [closed]如何在 ~/.ssh/config 中使用带有主机定义的 Paramiko? [关闭]
【发布时间】:2020-11-08 12:00:10
【问题描述】:

对于我的 SSH 连接,我使用这个~/.ssh/config

Host gwhost
Hostname gw.hostname.com
User user
IdentityFile /home/user/.ssh/priv_key
ControlMaster auto
ControlPath ~/.ssh/%h-%p-%r.sock
ControlPersist 120

Host *.my-example.com
User user
IdentityFile /home/user/.ssh/priv_key
StrictHostKeyChecking no
ProxyCommand ssh -q 'gwhost' -W %h:22

从终端我可以像这样连接到主机:

ssh one.my-example.com

我想使用 Paramiko 在远程主机上执行一些命令。 我试着这样做:

host = 'one.my-example.com'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
user_config_file = os.path.expanduser("~/.ssh/config")
config = SSHConfig.from_path(user_config_file)

ssh.connect(hostname=host)
stdin, stdout, stderr = ssh.exec_command('ls')
lines = stdout.readlines()
print(lines)

启动后出现此错误

in <lambda>
    retry_on_signal(lambda: sock.connect(addr))
TimeoutError: [Errno 110] Connection timed out

那么我该如何使用~/.ssh/config 或者我不应该使用~/.ssh/config

【问题讨论】:

    标签: python linux ssh paramiko


    【解决方案1】:

    Paramiko 只有very limited support for OpenSSH ssh_config configuration file

    如果绝对不会像 OpenSSH ssh 那样自动使用ssh_config

    您必须使用SSHConfig.from_path 实例化SSHConfig 类。然后使用SSHConfig.lookup 查找您的主机名的配置。然后使用返回的字典来提供SSHClient.connect 的参数。


    强制警告:不要使用AutoAddPolicy - 这样做会失去对MITM attacks 的保护。如需正确解决方案,请参阅Paramiko "Unknown Server"

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 2022-08-21
      • 2021-01-27
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      相关资源
      最近更新 更多