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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码