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

  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/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容