mirror of
https://gitee.com/dromara/mayfly-go
synced 2025-11-02 23:40:24 +08:00
59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net"
|
|
"time"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
)
|
|
|
|
func SSHConnect(user, password, host, key string, port int) (*ssh.Client, error) {
|
|
var (
|
|
auth []ssh.AuthMethod
|
|
addr string
|
|
clientConfig *ssh.ClientConfig
|
|
client *ssh.Client
|
|
config ssh.Config
|
|
//session *ssh.Session
|
|
err error
|
|
)
|
|
|
|
// get auth method
|
|
auth = make([]ssh.AuthMethod, 0)
|
|
if key == "" {
|
|
auth = append(auth, ssh.Password(password))
|
|
} else {
|
|
pemBytes, err := ioutil.ReadFile(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var signer ssh.Signer
|
|
if password == "" {
|
|
signer, err = ssh.ParsePrivateKey(pemBytes)
|
|
} else {
|
|
signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(password))
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
auth = append(auth, ssh.PublicKeys(signer))
|
|
}
|
|
|
|
clientConfig = &ssh.ClientConfig{
|
|
User: user,
|
|
Auth: auth,
|
|
Timeout: 30 * time.Second,
|
|
Config: config,
|
|
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
|
return nil
|
|
},
|
|
}
|
|
addr = fmt.Sprintf("%s:%d", host, port)
|
|
|
|
client, err = ssh.Dial("tcp", addr, clientConfig)
|
|
return client, err
|
|
}
|