Python实现跨机器隧道打通

场景

有一个机房,机房内的机器与外界网络不通,但是机房提供了一台机器让我们可以访问到机房内的机器,对于这台机器我们称为跳板机。同时提供对外的服务部署在机房外的一台机器上,现在需要访问到跳板机或者机房内机器(ssh)。如图

其中api_server可以免密登录jump_server,jump_server可以免密登录private_server

ssh到jump server

python 复制代码
client = paramiko.SSHClient()
# client.load_system_host_keys()
# 允许连接不在know_hosts文件中的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='jump_server_ip', port=22, username='root', password='pwd')
# 私钥方式
# pkey = paramiko.RSAKey.from_private_key_file(id_rsa_path)  # 私钥
# client.connect(hostname=hostname, port=port, username=username, pkey=pkey)  
stdin, stdout, stderr = client.exec_command('pwd')  # 执行命令
code, out, err = stdout.channel.recv_exit_status(), stdout.read(), stderr.read()
client.close()

ssh到private server

python 复制代码
with sshtunnel.open_tunnel(
    ssh_address_or_host='jump_server_ip',
    ssh_username='root',
    ssh_password='pwd',
    # ssh_pkey='local_id_rda',
    remote_bind_address=('private_server_ip', 22),
    # local_bind_address=('127.0.0.1', 10022)  # 绑定本机10022端口
) as tunnel:
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname='127.0.0.1', port=tunnel.local_bind_port, username='root', password='pwd')
    # pkey = paramiko.RSAKey.from_private_key_file('jump_id_rda')  # 跳板机的私钥
    # client.connect(hostname='127.0.0.1', port=tunnel.local_bind_port, username='root', pkey=pkey)
    stdin, stdout, stderr = client.exec_command('pwd')
    code, out, err = stdout.channel.recv_exit_status(), stdout.read(), stderr.read()
    client.close()

这里其实相当于将private_server的22端口转发到到本地的一个端口,再利用paramiko连接本地的端口。private_server上并没有配置api_server的公钥,所以不能用api_server的私钥登录。但是jump_server与private_server是可以免密登录的,可以利用jump_server的私钥登录,所以我将jump_server的私钥拷到了api_server上。

相关推荐
独泪了无痕4 小时前
MyBatis魔法堂:结果集映射
后端·mybatis
copyer_xyf5 小时前
LangChain 调用 LLM
后端·python·agent
copyer_xyf5 小时前
Prompt 组织管理
后端·python·agent
摇滚侠7 小时前
SpringMVC 入门到实战 文件上传 75-77
java·后端·spring·maven·intellij-idea
fox_lht9 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
大鸡腿同学9 小时前
用 AI 肝了一个星期的智能客服助手,看看怎么个事
后端
IT_陈寒9 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
张忠琳9 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
Rain50910 小时前
2.1 Nest.js 项目初始化与模块化架构
开发语言·前端·javascript·后端·架构·数据分析·node.js