Python實現(xiàn)隧道打通機制

場景

有一個機房,機房內(nèi)的機器與外界網(wǎng)絡(luò)不通,但是機房提供了一臺機器讓我們可以訪問到機房內(nèi)的機器,對于這臺機器我們稱為跳板機。同時提供對外的服務(wù)部署在機房外的一臺機器上,現(xiàn)在需要訪問到跳板機或者機房內(nèi)機器(ssh)。如圖


image.png

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

ssh到j(luò)ump server

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')  # 執(zhí)行命令
code, out, err = stdout.channel.recv_exit_status(), stdout.read(), stderr.read()
client.close()

ssh到private server

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()

這里其實相當(dāng)于將private_server的22端口轉(zhuǎn)發(fā)到到本地的一個端口,再利用paramiko連接本地的端口。private_server上并沒有配置api_server的公鑰,所以不能用api_server的私鑰登錄。但是jump_server與private_server是可以免密登錄的,可以利用jump_server的私鑰登錄,所以我將jump_server的私鑰拷到了api_server上。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容