Go SSH Tunnel

Tunneling protocol

In computer networks, a tunneling protocol is a communications protocol that allows for the movement of data from one network to another. It involves allowing private networkcommunications to be sent across a public network (such as the Internet) through a process called encapsulation.

上面是維基百科的 tunnel 的解釋,需求是從本地連接到遠程服務(wù)器的數(shù)據(jù)庫。

  1. 定義域名和端口和格式化
type Endpoint struct {
   Host string
   Port int
}

func (endpoint *Endpoint) String() string {
   return fmt.Sprintf("%s:%d", endpoint.Host, endpoint.Port)
}
  1. SSH Tunnel 配置
type SSHTunnel struct {
    Local  *Endpoint
    Server *Endpoint
    Remote *Endpoint

    Config *ssh.ClientConfig
}
// 通過密鑰連接:
func PrivateKeyFile(file string) ssh.AuthMethod {
    key, err := ioutil.ReadFile(file)
    if err != nil {
        return nil
    }
    signer, err := ssh.ParsePrivateKey(key)
    if err != nil {
        return nil
    }
    return ssh.PublicKeys(signer)
}
  1. 開始連接到遠程服務(wù)器
func (tunnel *SSHTunnel) Start(ch *chan bool) error {
    listener, err := net.Listen("tcp", tunnel.Local.String())
    *ch <- true
    if err != nil {
        return err
    }
    defer listener.Close()

    for {
        conn, err := listener.Accept()
        if err != nil {
            return err
        }
        go tunnel.forward(conn)

    }
}

func (tunnel *SSHTunnel) forward(localConn net.Conn) {
    serverConn, err := ssh.Dial("tcp", tunnel.Server.String(), tunnel.Config)
    if err != nil {
        return
    }

    remoteConn, err := serverConn.Dial("tcp", tunnel.Remote.String())
    if err != nil {
        return
    }
    copyConn := func(writer, reader net.Conn) {
        _, err := io.Copy(writer, reader)
        if err != nil {
        }
    }

    go copyConn(localConn, remoteConn)
    go copyConn(remoteConn, localConn)
}

參考文章:

  1. https://sosedoff.com/2015/05/25/ssh-port-forwarding-with-go.html

  2. http://blog.ralch.com/tutorial/golang-ssh-tunneling/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容