Skip to content

Instantly share code, notes, and snippets.

@clr
Created April 8, 2025 19:44
Show Gist options
  • Save clr/393ddd1c22b69fef3818beb3d86f20e8 to your computer and use it in GitHub Desktop.
Save clr/393ddd1c22b69fef3818beb3d86f20e8 to your computer and use it in GitHub Desktop.
Go agent that establishes a reverse tunnel.
package main
import (
"fmt"
"log"
"net"
"os"
"os/exec"
"golang.org/x/crypto/ssh"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: agent <start|stop>")
return
}
command := os.Args[1]
switch command {
case "start":
startAgent()
case "stop":
stopAgent()
default:
fmt.Println("Unknown command. Use 'start' or 'stop'.")
}
}
func startAgent() {
fmt.Println("Starting agent...")
// SSH configuration
sshConfig := &ssh.ClientConfig{
User: "your-username", // Replace with your SSH username
Auth: []ssh.AuthMethod{
ssh.Password("your-password"), // Replace with your SSH password
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Connect to the SSH server
serverAddress := "domainhub.net:22"
client, err := ssh.Dial("tcp", serverAddress, sshConfig)
if err != nil {
log.Fatalf("Failed to connect to SSH server: %v", err)
}
defer client.Close()
// Set up reverse tunnel
localAddress := "localhost:2020"
remoteAddress := "localhost:2020"
listener, err := client.Listen("tcp", remoteAddress)
if err != nil {
log.Fatalf("Failed to set up reverse tunnel: %v", err)
}
defer listener.Close()
fmt.Printf("Reverse tunnel established: %s -> %s\n", localAddress, remoteAddress)
// Keep the tunnel open
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept connection: %v", err)
continue
}
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
defer conn.Close()
fmt.Println("Connection established:", conn.RemoteAddr())
// Handle the connection (e.g., forward data)
}
func stopAgent() {
fmt.Println("Stopping agent...")
// Simple mechanism to stop the agent (e.g., kill the process)
cmd := exec.Command("pkill", "-f", "agent")
err := cmd.Run()
if err != nil {
log.Fatalf("Failed to stop agent: %v", err)
}
fmt.Println("Agent stopped.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment