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 的解释,需求是从本地连接到远程服务器的数据库。
- 定义域名和端口和格式化
type Endpoint struct {
Host string
Port int
}
func (endpoint *Endpoint) String() string {
return fmt.Sprintf("%s:%d", endpoint.Host, endpoint.Port)
}
- 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)
}
- 开始连接到远程服务器
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)
}
参考文章:
有疑问加站长微信联系(非本文作者)