英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论