Home > Article > Backend Development > How to Create a Simple SSH Port Forward Using Golang?
Problem:
Programmatically creating a basic TCP port forward over SSH in Golang for users familiar with Ruby.
Solution:
To tackle this challenge, it's essential to understand the crucial steps involved:
Code:
<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>
The above is the detailed content of How to Create a Simple SSH Port Forward Using Golang?. For more information, please follow other related articles on the PHP Chinese website!