23 Star 157 Fork 53

wida / webssh

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ssh.go 1.49 KB
一键复制 编辑 原始数据 按行查看 历史
wida 提交于 2021-10-28 11:31 . first commit
package webssh
import (
"io/ioutil"
"time"
"golang.org/x/crypto/ssh"
)
type AuthModel int8
const (
PASSWORD AuthModel = iota + 1
PUBLICKEY
)
type SSHClientConfig struct {
AuthModel AuthModel
HostAddr string
User string
Password string
KeyPath string
Timeout time.Duration
}
func SSHClientConfigPassword(hostAddr, user, Password string) *SSHClientConfig {
return &SSHClientConfig{
Timeout: time.Second * 5,
AuthModel: PASSWORD,
HostAddr: hostAddr,
User: user,
Password: Password,
}
}
func SSHClientConfigPulicKey(hostAddr, user, keyPath string) *SSHClientConfig {
return &SSHClientConfig{
Timeout: time.Second * 5,
AuthModel: PUBLICKEY,
HostAddr: hostAddr,
User: user,
KeyPath: keyPath,
}
}
func NewSSHClient(conf *SSHClientConfig) (*ssh.Client, error) {
config := &ssh.ClientConfig{
Timeout: conf.Timeout,
User: conf.User,
HostKeyCallback: ssh.InsecureIgnoreHostKey(), //忽略know_hosts检查
}
switch conf.AuthModel {
case PASSWORD:
config.Auth = []ssh.AuthMethod{ssh.Password(conf.Password)}
case PUBLICKEY:
signer, err := getKey(conf.KeyPath)
if err != nil {
return nil, err
}
config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
}
c, err := ssh.Dial("tcp", conf.HostAddr, config)
if err != nil {
return nil, err
}
return c, nil
}
func getKey(keyPath string) (ssh.Signer, error) {
key, err := ioutil.ReadFile(keyPath)
if err != nil {
return nil, err
}
return ssh.ParsePrivateKey(key)
}
Go
1
https://gitee.com/wida/webssh.git
git@gitee.com:wida/webssh.git
wida
webssh
webssh
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891