準(zhǔn)備工作
-
golang的ssh包
golang.org/x/crypto/ssh
該包不在標(biāo)準(zhǔn)庫(kù)中舰绘,需要單獨(dú)下載。因?yàn)镚FW齿梁,不能直接使用
go get
命令下載烹植,可以去github下載地址:https://github.com/golang/crypto
在
$GOPATH/src
目錄下創(chuàng)建golang.org/x
目錄結(jié)構(gòu),將下載的crypto
包移動(dòng)到$GOPATH/src/golang.or/x
下 -
redis庫(kù)
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),
},
//需要驗(yàn)證服務(wù)端贰锁,不做驗(yàn)證返回nil,沒(méi)有該參數(shù)會(huì)報(bào)錯(cuò)
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的用戶名滤蝠,密碼豌熄,地址,改成自己實(shí)際的
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", // 連接方式锣险,默認(rèn)使用tcp,可省略
Addr: redisAddr,
DB: db, // 選擇要操作的數(shù)據(jù)庫(kù)览闰,默認(rèn)是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