有没有办法在Go中进行基于动态套接字的端口转发,例如SSH中的-d开关?

I used to use a batch script to create an SSH tunnel that would be usable as a socks5 proxy. Today, I thought I'd implement it in Go, both to learn the language and to remove the need for me to constantly run a batch script file whenever the connection drops.

Right now, how I do this is to use plink. The command to do this with plink is:

plink -N -C -D 8888 -pw password username@example.com

And here is my Go code:

package main

import (
    "os"
    "os/exec"
    "log"
)

func runPlink() {
    command := exec.Command("plink.exe", "-N", "-C", "-D", "8888", "-pw", "password", "username@example.com")

    if output, err := command.CombinedOutput(); err != nil {
        log.Println(string(output), err.Error())
        runPlink()
    }
}

func main() {
    if _, err := os.Stat("plink.exe"); os.IsNotExist(err) {
        log.Fatalln("Cannot find plink.exe. Please copy it next to this application.")
    }

    runPlink()
}

I would like to make this application self-contained, so that it doesn't rely on the existence of plink.exe to work.

Is there a way to achieve this in Go?

This might not be ideal, but you could pretty easily use a combination of https://github.com/jteeuwen/go-bindata and https://github.com/getlantern/byteexec - essentially you would embed the plink executable inside of your own executable, then load it and run it with something like:

func runPlink() {
    programBytes, err := Asset("plink.exe")
    be, err := byteexec.New(programBytes)
    if err != nil {
        log.Fatalf("Uh oh: %s", err)
    }
    cmd := be.Command("-N", "-C", "-D", "8888", "-pw", "password", "username@example.com")
    if output, err := cmd.CombinedOutput(); err != nil {
        log.Println(string(output), err.Error())
        runPlink()
    }
}