Home > Article > Backend Development > How to Implement Simple SSH Port Forwarding Using Golang?
Simple SSH Port Forwarding Utilizing Golang: Debunking the Complexity
Creating SSH port forwards in Go can be a straightforward task, contrary to initial assumptions. In this article, we aim to demystify the process and provide a clear understanding of how to achieve port forwarding in Golang.
Understanding the Concept
To establish an SSH port forward, we need to create a connection between a local and a remote port. The data from the local port is forwarded over the SSH connection to the remote port. This allows for secure access to services or applications running on the remote machine via the local port.
Implementing a Simple Port Forwarder
Let's delve into the nuts and bolts of port forwarding. Here's the key code snippet that accomplishes our goal:
<code class="go">package main import ( "io" "log" "net" "golang.org/x/crypto/ssh" ) var ( username = "root" password = "password" serverAddrString = "192.168.1.100:22" localAddrString = "localhost:9000" remoteAddrString = "localhost:9999" ) func main() { // Configure SSH connection config := &ssh.ClientConfig{ User: username, Auth: []ssh.AuthMethod{ ssh.Password(password), }, } // Listen for local port connections localListener, err := net.Listen("tcp", localAddrString) if err != nil { log.Fatalf("net.Listen failed: %v", err) } for { // Accept local port connections localConn, err := localListener.Accept() if err != nil { log.Fatalf("listen.Accept failed: %v", err) } // Create SSH connection and dial remote port sshClientConn, err := ssh.Dial("tcp", serverAddrString, config) if err != nil { log.Fatalf("ssh.Dial failed: %s", err) } // Establish remote port connection sshConn, err := sshClientConn.Dial("tcp", remoteAddrString) // Copy data between local and remote connections 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) } }() } }</code>
How it Works
Key Points
This example provides a concise and easy-to-follow implementation of simple SSH port forwarding in Golang. By understanding each step of the process, you can effectively utilize port forwarding for secure network communication.
The above is the detailed content of How to Implement Simple SSH Port Forwarding Using Golang?. For more information, please follow other related articles on the PHP Chinese website!