問題:
以程式設計方式在Golang 中透過SSSSH連接埠轉送熟悉Ruby 的使用者。
解決方案:
要應對這一挑戰,必須了解所涉及的關鍵步驟:
代碼:
<code class="go">package main import ( "io" "log" "net" "golang.org/x/crypto/ssh" ) // Configuration parameters for SSH connection var ( username = "root" password = "password" serverAddrString = "192.168.1.100:22" localAddrString = "localhost:9000" remoteAddrString = "localhost:9999" ) 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) } // Connect to remote port sshConn, err := sshClientConn.Dial("tcp", remoteAddrString) if err != nil { log.Fatalf("sshConn.Dial failed: %s", err) } // Create goroutines for bidirectional data transfer go func() { _, err = io.Copy(sshConn, localConn) if err != nil { log.Fatalf("io.Copy failed: %v", err) } }() go func() { _, err = io.Copy(localConn, sshConn) if 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) } // Monitor listener for new connections for { localConn, err := localListener.Accept() if err != nil { log.Fatalf("localListener.Accept failed: %v", err) } go forward(localConn, config) } }</code>
以上是如何使用 Golang 建立簡單的 SSH 連接埠轉送?的詳細內容。更多資訊請關注PHP中文網其他相關文章!