Go SSH Tunnel

2019-07-30  本文已影响0人  七秒钟回忆待续

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 的解释,需求是从本地连接到远程服务器的数据库。

  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. 开始连接到远程服务器
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/

上一篇下一篇

猜你喜欢

热点阅读