Skip to content

Instantly share code, notes, and snippets.

@kallydev
Last active March 1, 2022 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kallydev/26b694dfffe5ddeda39961203f5b24d2 to your computer and use it in GitHub Desktop.
Save kallydev/26b694dfffe5ddeda39961203f5b24d2 to your computer and use it in GitHub Desktop.
Using SSH Tunnel to connect to Redis in Go.
package redis_test
import (
"github.com/go-redis/redis"
"golang.org/x/crypto/ssh"
"io/ioutil"
"net"
"testing"
)
var redisClient *redis.Client
const (
sshUsername = "ubuntu"
sshAddress = "server.kallydev.com:22"
sshPrivateKeyPath = "/Users/kallydev/.ssh/private.pem"
redisAddress = "127.0.0.1:6379"
redisPassword = "password"
)
func init() {
redisClient = redis.NewClient(&redis.Options{
Password: redisPassword,
Dialer: func() (net.Conn, error) {
privateKey, err := ioutil.ReadFile(sshPrivateKeyPath)
if err != nil {
return nil, err
}
signer, err := ssh.ParsePrivateKey(privateKey)
if err != nil {
return nil, err
}
tcpConn, err := net.Dial("tcp", sshAddress)
if err != nil {
return nil, err
}
sshConn, newCh, requestCh, err := ssh.NewClientConn(tcpConn, sshAddress, &ssh.ClientConfig{
User: sshUsername,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil {
_ = tcpConn.Close()
return nil, err
}
sshClient := ssh.NewClient(sshConn, newCh, requestCh)
redisClient, err := sshClient.Dial("tcp", redisAddress)
if err != nil {
_ = sshClient.Close()
return nil, err
}
return redisClient, nil
},
})
}
func TestName(t *testing.T) {
t.Log(redisClient.Ping().Result())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment