在我的公司,我们目前有一个 REST API,只能由特定的跳转框访问。

我想从运行我的 Python 代码的服务器 ssh 到这个盒子,以进行休息调用。

我在下面写了这段代码,但是当我运行它时它挂起并且没有做任何事情:

from sshtunnel import SSHTunnelForwarder 
import requests 
 
remote_user = 'me' 
remote_host = 'jump.box.net' 
remote_port = 22 
local_host = '10.30.22.218' 
local_port = 443 
 
server = SSHTunnelForwarder( 
   (remote_host, remote_port), 
   ssh_username=remote_user, 
   ssh_private_key_password='mypassword', 
   ssh_private_key='~/.ssh/mykey', 
   remote_bind_address=(local_host, local_port), 
   ) 
 
server.start() 
 
r = requests.get(url = 'https://ourinternalendpoint.com/api/stuff',verify=False).content 
print(r) 
server.stop() 

本地主机IP其实就是ourinternalendpoint域的IP。

我做错了什么?我知道 remote_host 名称是正确的,端口、用户、私钥和 ssh-ing 密码也是正确的。

server.start() 命令也完成了。它卡在 get 请求上。

我在 Linux 服务器上执行此操作,如果需要,我愿意使用 Bash 为我的 Python 脚本进行端口转发。

请您参考如下方法:

我设法解决了这个问题!主要变化是代码:

from sshtunnel import SSHTunnelForwarder 
import requests 
import paramiko 
 
pkey = paramiko.RSAKey.from_private_key_file(private_key_path, password=private_key_password) 
 
server = SSHTunnelForwarder( 
    (remote_host, ssh_port), 
    ssh_username=remote_user, 
    ssh_private_key=pkey, 
    remote_bind_address=('internal_url.com', 443), 
    local_bind_address=('localhost', 1478) 
) 
 
server.start() 
try: 
    r = requests.get(url = 'https://internal_url:1478/some/endpoint',verify=False) 
finally: 
    server.stop()` 

我还必须添加到/etc/hosts: 的映射,我必须添加如下一行:

127.0.0.1 internal_url 


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!