doulangchao8934 2015-10-23 18:25
浏览 123
已采纳

有没有办法在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?

  • 写回答

1条回答 默认 最新

  • doubi2014 2015-10-23 19:47
    关注

    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()
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?