連接埠轉送是在兩個主機之間建立隧道的有用技術,允許透過中間伺服器安全地中繼流量。在 Go 中,可以使用 golang.org/x/crypto/ssh 套件來實現連接埠轉送。
基本的連接埠轉送設定包括:
這是一個簡單的Go 程式碼範例,示範從本機連接埠(9000) 到遠端連接埠( 9999)在遠端伺服器上:
<code class="go">package main import ( "io" "log" "net" "golang.org/x/crypto/ssh" ) const ( localAddrString = "localhost:9000" remoteAddrString = "localhost:9999" serverAddrString = "192.168.1.100:22" username = "root" password = "password" ) func forward(localConn net.Conn, config *ssh.ClientConfig) { // Establish SSH connection to remote server sshClientConn, err := ssh.Dial("tcp", serverAddrString, config) if err != nil { log.Fatalf("ssh.Dial failed: %s", err) } defer sshClientConn.Close() // Establish connection to remote destination port sshConn, err := sshClientConn.Dial("tcp", remoteAddrString) if err != nil { log.Fatalf("sshClientConn.Dial failed: %s", err) } defer sshConn.Close() // Relay data between local and remote connections go func() { if _, err := io.Copy(sshConn, localConn); err != nil { log.Fatalf("io.Copy failed: %v", err) } }() go func() { if _, err := io.Copy(localConn, sshConn); err != nil { log.Fatalf("io.Copy failed: %v", err) } }() } func main() { // Configure SSH client config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } // Create local listener localListener, err := net.Listen("tcp", localAddrString) if err != nil { log.Fatalf("net.Listen failed: %v", err) } // Accept incoming connections and forward them for { localConn, err := localListener.Accept() if err != nil { log.Fatalf("listener.Accept failed: %v", err) } go forward(localConn, config) } }</code>
此程式碼首先在連接埠9000 上建立本機偵聽器,然後建立與遠端SSH 伺服器的用戶端連線。接下來,將啟動到遠端伺服器上的目標連接埠 (9999) 的 SSH 連線。最後,資料透過 goroutine 在本地和遠端連線之間中繼。
以上是如何在 Go 中實現簡單的 SSH 連接埠轉送?的詳細內容。更多資訊請關注PHP中文網其他相關文章!