我正在尝试通过SSH连接到使用Python中的paramiko通过另一台计算机进行隧道连接的计算机,但我遇到了一些奇怪的问题。
/.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上运行它。
答案 0 :(得分:6)
我认为你可以坚持第一个解决方案。只需要更改代理命令并确保跳转主机已安装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,就像我一样。
答案 1 :(得分:2)
因此我没有使用ProxyCommand
而是使用端口转发来解决我的问题。
def getForwardedSSHPort(self, tunnnelHostName):
forwarderClient = self.getSSHConnection(tunnnelHostName, None)
transport = forwarderClient.get_transport()
dest_addr = ('169.254.1.2', 22)
local_addr = ('127.0.0.1', 10022)
channel = transport.open_channel('direct-tcpip', dest_addr, local_addr)
remoteClient = self.getSSHConnection( tunnnelHostName, channel)