如何在 ~/.ssh/config 中使用带有主机定义的 Paramiko?
How to use Paramiko with host definition in ~/.ssh/config?
对于我的 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
?
Paramiko 只有 very limited support for OpenSSH ssh_config
configuration file.
If 肯定不会像 OpenSSH ssh
那样自动使用 ssh_config
。
您必须使用 SSHConfig.from_path
. And then use SSHConfig.lookup
to lookup configuration for your hostname. And then use the returned dictionary to feed the arguments of SSHClient.connect
.
实例化 SSHConfig
class
强制性警告:请勿使用 AutoAddPolicy
– 您正在失去针对 MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
的保护
对于我的 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
?
Paramiko 只有 very limited support for OpenSSH ssh_config
configuration file.
If 肯定不会像 OpenSSH ssh
那样自动使用 ssh_config
。
您必须使用 SSHConfig.from_path
. And then use SSHConfig.lookup
to lookup configuration for your hostname. And then use the returned dictionary to feed the arguments of SSHClient.connect
.
SSHConfig
class
强制性警告:请勿使用 AutoAddPolicy
– 您正在失去针对 MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".