准备工作
-
golang的ssh包
golang.org/x/crypto/ssh
该包不在标准库中,需要单独下载。因为GFW,不能直接使用
go get
命令下载,可以去github下载地址:https://github.com/golang/crypto
在
$GOPATH/src
目录下创建golang.org/x
目录结构,将下载的crypto
包移动到$GOPATH/src/golang.or/x
下 -
redis库
redigo
,github地址:https://github.com/gomodule/redigogo-redis/redis
,github地址:https://github.com/go-redis/redis
获取SSH连接
func getSSHClient(user, pass, addr string) (*ssh.Client, error) {
config := &ssh.ClientConfig{
User:user,
Auth:[]ssh.AuthMethod{
ssh.Password(pass),
},
//需要验证服务端,不做验证返回nil,没有该参数会报错
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
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
}
client := ssh.NewClient(clientConn, chans, reqs)
return client, nil
}
连接Redis(redigo)
func getRedisConn(redisAddr string) (redis.Conn, error) {
// ssh的用户名,密码,地址,改成自己实际的
sshClient, err := getSSHClient("user", "password", "ip+port")
if nil != err {
return nil, err
}
conn, err := sshClient.Dial("tcp", redisAddr)
if nil != err {
fmt.Println("dial to redis addr err: ", err)
return nil, err
}
redisConn := redis.NewConn(conn, -1, -1)
return redisConn, nil
}
得到redis.Conn
就可以直接使用,使用方法参照redigo的文档:https://godoc.org/github.com/gomodule/redigo/redis
连接Redis(go-redis/redis)
func getRedisClient(redisAddr string, db int) (*redis.Client, error) {
cli, err := getSSHClient("user", "pass", "ip+port")
if nil != err {
log.Printf("get ssh client err: %v\n", err)
return nil, err
}
redisCli := redis.NewClient(&redis.Options{
Network: "tcp", // 连接方式,默认使用tcp,可省略
Addr: redisAddr,
DB: db, // 选择要操作的数据库,默认是0 (redis中select index命令)
Dialer: func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
return cli.Dial(network, addr)
},
})
if err = redisCli.Ping().Err(); nil != err {
log.Printf("connect to redis err: %v\n", err)
return nil, err
}
return redisCli, nil
}
同样,得到*redis.Client
后就可以操作redis了。go-redis/redis
的参考文档:https://godoc.org/github.com/go-redis/redis