How to connect to redis through ssh tunnel in Go?

huangapple go评论73阅读模式
英文:

How to connect to redis through ssh tunnel in Go?

问题

我正在尝试在Go语言中使用redigo库进行SSH隧道与Redis通信。通常情况下,我会通过命令行执行以下操作:

ssh user@host -p port

然后连接到Redis主机:

redis-cli -h redisHost
英文:

I'm trying to see if its possible to do an ssh tunnel with redis in go. I'm using the redigo library.

Through command line I typically do something like:

ssh user@host -p port

then redis-cli -h redisHost

答案1

得分: 2

使用Redigo库中的网络拨号函数(network dial)可以这样做:

func dial(network, addr string) (net.Conn, error) {
    user := "user"
    password := "password"
    sshAddr := "example.com:22"
    redisAddr := ":6379"
    config := &ssh.ClientConfig{
        User: user,
        Auth: []ssh.AuthMethod{
            ssh.Password(password),
        },
    }
    netConn, err := net.Dial("tcp", sshAddr)
    if err != nil {
        return nil, err
    }
    clientConn, chans, reqs, err := ssh.NewClientConn(netConn, sshAddr, config)
    if err != nil {
        netConn.Close()
        return nil, err
    }
    client := ssh.NewClient(clientConn, chans, reqs)
    conn, err := client.Dial("tcp", redisAddr)
    if err != nil {
        client.Close()
        return nil, err
    }
    return conn, nil
}

如果应用程序需要创建多个与服务器的连接,则可以在每次拨号时创建一个client并重复使用。

上述代码未经编译和测试。

英文:

Use a network dial function like this with Redigo:

func dial(network, addr string) (net.Conn, error) {
        user := "user"
        password := "password"
        sshAddr := "example.com:22"
        redisAddr := ":6379"
		config := &ssh.ClientConfig{
			User: user,
			Auth: []ssh.AuthMethod{
				ssh.Password(passord),
			},
		}
		netConn, err := net.Dial("tcp", sshAddr)
		if err != nil {
			return nil, err
		}
		clientConn, chans, reqs, err := ssh.NewClientConn(netConn, sshAddr, config)
		if err != nil {
			netConn.Close()
			return nil, err
		}
		client := ssh.NewClient(clientConn, chans, reqs)
		conn, err := client.Dial("tcp", redisAddr)
		if err != nil {
			client.Close()
			return nil, err
		}
		conn, nil
}

If the application creates multiple connections to the server, then create client once and reuse on each dial.

The code above is uncompiled and untested.

huangapple
  • 本文由 发表于 2017年7月13日 14:33:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/45073014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定