使用 Golang 实现 SSH 隧道功能

文章目录:

  • 目标
    • golang.org/x/crypto
    • gopkg.in/yaml.v2
  • 注意
    • 本文讲的是客户端部分

文章使用到的软件:

  • Mac 12.0 Beta(macOS Monterey),处理器为:M1
  • Goland 2021.1.3
  • Golang 1.17beta1

使用 Golang 实现 SSH 隧道功能

目标

  • 通过Go在客户端实现ssh隧道功能并连接到服务器的mysql

Go程序

在工作目录创建一个go应用程序,并配置SSH的信息....还是看注释吧! 阿巴阿巴阿巴

package main

func main() {
	// 设置SSH配置
	config := &ssh.ClientConfig{
  	// 服务器用户名
		User: "",
		Auth: []ssh.AuthMethod{
    	// 服务器密码
			ssh.Password(""),
		},
		Timeout: 30 * time.Second,
		HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			return nil
		},
	}
  
	// 设置本地监听器,格式:地址:端口
  localListener, err := net.Listen("tcp", "localhost:13306")
	if err != nil {
		fmt.Printf("net.Listen failed: %v\n", err)
	}
  
  for {
		localConn, err := localListener.Accept()
		if err != nil {
			fmt.Printf("localListener.Accept failed: %v\n", err)
		}
		go forward(localConn, config)
	}
}

// 转发
func forward(localConn net.Conn, config *ssh.ClientConfig) {
	// 设置服务器地址,格式:地址:端口
	sshClientConn, err := ssh.Dial("tcp", "", config)
	if err != nil {
		fmt.Printf("ssh.Dial failed: %s", err)
	}

	// 设置远程地址,格式:地址:端口(请在服务器通过 ifconfig 查看地址)
	sshConn, err := sshClientConn.Dial("tcp", "")

	// 将localConn.Reader复制到sshConn.Writer
	go func() {
		_, err = io.Copy(sshConn, localConn)
		if err != nil {
			fmt.Printf("io.Copy failed: %v", err)
		}
	}()

	// 将sshConn.Reader复制到localConn.Writer
	go func() {
		_, err = io.Copy(localConn, sshConn)
		if err != nil {
			fmt.Printf("io.Copy failed: %v", err)
		}
	}()
}

快速安排

给不想写的朋友们安排了一个扩展包 (早说嘛...)

go get -u github.com/dtapps/dtapps/go-ssh-tunnel

扩展包使用

package main

import (
	"github.com/dtapps/dtapps/go-ssh-tunnel/dssh"
)

func main() {
	dssh.Tunnel("root", "", ":22", ":3306", "localhost:13306")
}

使用 Golang 实现 SSH 隧道功能

上一篇:指针的讨论


下一篇:ES8中的Async和Await