天天看點

python實作ssh端口轉發

nginx配置本地開發調式

比如laravel架構的env配置檔案,可以由nginx來配置環境變量,進而實作不同環境的不同配置,有development,production等,我們可以在本地配置一個local.env,将nginx請求打通到本地,由于mysql,redis這些都是不同的遠端主機,是以我們還要修改local.env裡面的這些遠端主機的ip,改為本地,然後通過ssh端口轉發到遠端端口。

端口轉發指令

ssh -fNg -p 22 -L 6279:遠端redis的host:6379 使用者名@跳闆機的host

ssh -fNg -p 22 -L 3356:遠端mysql的host:3306 使用者名@跳闆機的host

-f 背景啟用

-N 不打開遠端shell,處于等待狀态

-g 啟用網關功能

但是每次使用這個指令都要開啟兩個cmd黑視窗,不像mac,有自帶的指令管理

python實作多端口轉發(多線程)

from sshtunnel import SSHTunnelForwarder
import threading
import socket
import os
import sys

# 擷取項目根目錄
def app_path():
    if hasattr(sys, 'frozen'):
        return os.path.dirname(os.path.dirname(os.path.dirname(sys.executable))) #使用pyinstaller打包後的exe目錄
    return os.path.dirname(__file__)

def get_host_ip():
    """
    查詢本機ip位址
    :return: ip
    """
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    finally:
        s.close()
    return ip

app_path = app_path()

#區域網路ip
local_host = get_host_ip()

def forwardSSH(user,password,ssh_host,ssh_port,local_host,local_port,remote_host,remote_port):
    server = SSHTunnelForwarder(
            ssh_username=user,
            ssh_password=password,
            ssh_address_or_host=(ssh_host, ssh_port),
            local_bind_address=(local_host, local_port),
            remote_bind_address=(remote_host, remote_port)
    )
    # 守護線程
    server.daemon_forward_servers=False
    server.start()
    if server.is_active:
        print('本地端口{}:{}已轉發至遠端端口{}:{}'.format(local_host,server.local_bind_port,remote_host,remote_port))
    else :
        print('本地端口{}:{}轉發失敗,請重試')

#讀取配置檔案
with open(app_path + '/config.txt') as f:
    lines = f.readlines()
    t = locals()
    i = 1
    for line in lines:
        data = line.split(",")

        user = str(data[0].strip("\'"))
        password = str(data[1].strip("\'"))
        ssh_host = str(data[2].strip("\'"))
        ssh_port = int(data[3].strip("\'"))
        local_port = int(data[4].strip("\'"))
        remote_host = str(data[5].strip("\'"))
        remote_port = int(data[6].rstrip("\n").strip("\'"))
        #print(local_port,remote_host,remote_port)
        t[str(i)] = threading.Thread(forwardSSH(user,password,ssh_host,ssh_port,local_host,local_port,remote_host,remote_port))
        t[str(i)].start()
           

其中config.txt配置如下,可以配置n多個,因為是多線程調用

使用者名,密碼,ssh跳闆機host,22端口,本地轉發端口,遠端主機host,遠端主機端口

zhangsan,asdasfzcxeqwdasd,跳闆機host,22,6279,遠端redis主機host,6379 zhangsan,asdasfzcxeqwdasd,跳闆機host,22,3356,遠端mysql主機host,3306

打包成exe(注意site-packages要換成自己python包的目錄)

pyinstaller forward.py -p D:\Anaconda3\Lib\site-packages -i logo.ico
python實作ssh端口轉發

運作dist下的exe,而不是build

運作效果(這裡還要自己改下應用圖示)

python實作ssh端口轉發

分享到這裡就結束了,這也算是一個小工具吧,還可以做成界面化的配置,裝個B,發給别的小夥伴,我這裡就懶得折騰了,有疑惑或者遇到問題的小夥伴,可以私聊我一起交流學習!!!