73 lines
1.7 KiB
Go
73 lines
1.7 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
|
||
"github.com/redis/go-redis/v9"
|
||
"golang.org/x/crypto/ssh"
|
||
)
|
||
|
||
func GetRedisClient(redisAddr string, port string, password string, db int, sshConfig *SSHConfig) (*redis.Client, error) {
|
||
ctx := context.Background()
|
||
|
||
options := &redis.Options{
|
||
Network: "tcp", // 连接方式,默认使用tcp,可省略
|
||
Addr: net.JoinHostPort(redisAddr, port),
|
||
Password: password,
|
||
DB: db, // 选择要操作的数据库,默认是0 (redis中select index命令)
|
||
|
||
}
|
||
|
||
var sshClient *ssh.Client = nil
|
||
if sshConfig != nil {
|
||
var err error
|
||
sshClient, err = getSSHClient("user", "pass", "ip+port")
|
||
if nil != err {
|
||
log.Printf("get ssh client err: %v\n", err)
|
||
return nil, err
|
||
}
|
||
options.Dialer = func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
|
||
return sshClient.Dial(network, addr)
|
||
}
|
||
}
|
||
|
||
redisClient := redis.NewClient(options)
|
||
if err := redisClient.Ping(ctx).Err(); nil != err {
|
||
log.Printf("connect to redis err: %v\n", err)
|
||
return nil, err
|
||
}
|
||
|
||
return redisClient, nil
|
||
}
|
||
|
||
func getSSHClient(user, pass, addr string) (*ssh.Client, error) {
|
||
config := &ssh.ClientConfig{
|
||
User: user,
|
||
Auth: []ssh.AuthMethod{
|
||
ssh.Password(pass),
|
||
},
|
||
//需要验证服务端,不做验证返回nil,没有该参数会报错
|
||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||
}
|
||
|
||
sshConn, err := net.Dial("tcp", addr)
|
||
if nil != err {
|
||
fmt.Println("net dial err: ", err)
|
||
return nil, err
|
||
}
|
||
|
||
clientConn, chans, reqs, err := ssh.NewClientConn(sshConn, addr, config)
|
||
if nil != err {
|
||
sshConn.Close()
|
||
fmt.Println("ssh client conn err: ", err)
|
||
return nil, err
|
||
}
|
||
|
||
sshClient := ssh.NewClient(clientConn, chans, reqs)
|
||
|
||
return sshClient, nil
|
||
}
|