gpt4 book ai didi

python - paramiko.Proxycommand 无法设置套接字

转载 作者:太空狗 更新时间:2023-10-30 02:11:34 28 4
gpt4 key购买 nike

我正在尝试使用 paramiko 通过 SSH 连接到通过另一台计算机隧道传输的计算机在 Python 中,但我遇到了一些奇怪的问题。

我在 /.ssh/config 中的配置文件如下所示:

Host remoteA
HostName 169.254.1.1
User root
IdentityFile ~/.ssh/id_dss.openssh.remoteA
ForwardX11 no
StrictHostKeyChecking no
ForwardAgent yes
UserKnownHostsFile /dev/null
Host remoteB
User root
IdentityFile ~/.ssh/id_dss.openssh.remoteB
ForwardX11 no
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
ProxyCommand ssh -W 169.254.1.2:22 remoteA

我的 python 代码是这样的:

from paramiko import SSHClient,SSHConfig,SSHException
import getpass
import paramiko
def getSSHConnection(hostName):
config = SSHConfig()
user = getpass.getuser()
config.parse(open('C:/Users/' + user +'/.ssh/config'))
host=config.lookup(hostName)
# setup SSH client
client = SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#Check for proxy settings
try:
print host ['proxycommand']
proxy = paramiko.ProxyCommand(host['proxycommand'])
except:
proxy = None
#Setup the SSH connection
try:
if (proxy is None):
client.connect(host['hostname'],22,username=host['user'],key_filename=host['identityfile'])
else:
client.connect(host['hostname'],22,username=host['user'], key_filename=host['identityfile'],sock=proxy)
except SSHException,ex:
print ex
return client
ssh_client = getSSHConnection('remoteA')
# run a command
print "\nRun a command"
cmd = 'ps aux'
stdin,stdout,stderr = ssh_client.exec_command(cmd)
print stdout.read()
ssh_client = getSSHConnection('remoteB')
# run a command
print "\nRun a command"
cmd = 'ps aux'
stdin,stdout,stderr = ssh_client.exec_command(cmd)
print stdout.read()

首先,当连接到 remoteA 时,它工作得很好,但是当连接到 remoteB 时,它在以下步骤中崩溃:proxy = paramiko.ProxyCommand(host['proxycommand'])

File "C:\Python27\lib\site-packages\paramiko\client.py",line 291,in connect
for (family,socktype,proto,canonname,sockaddr) in socket.getaddrinfo(hostname,port, socket.AF_UNSPEC,socket.SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed

在 Cygwin 中,我可以使用命令 ssh remoteB 进行连接,所以我知道配置文件应该没问题。如果它有什么不同,我在 Windows 7 上运行它。

最佳答案

我认为您可以坚持第一个解决方案。只是你需要更改你的代理命令并确保你的跳转主机已安装 nc

我使用这样的代理命令

proxy = paramiko.ProxyCommand("ssh -o StrictHostKeyChecking=no jumphostIP nc targethostIP 22")

我发现这个 WiKi 非常有用 http://en.wikibooks.org/wiki/OpenSSH/Cookbook/Proxies_and_Jump_Hosts只需使用实际值,而不是像我所做的那样使用 %h 和 %p。

关于python - paramiko.Proxycommand 无法设置套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609443/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com