1 Star 0 Fork 1

爱狸狸爱生活 / goboot

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ssh_helper.go 2.70 KB
一键复制 编辑 原始数据 按行查看 历史
package ssh
import (
"bytes"
"fmt"
"golang.org/x/crypto/ssh"
"log"
"strconv"
"time"
)
func RunSSHCommandWithCipher(host string, port int, account, password string, commands []string, ciphers []string) (string, error) {
var content string
if len(commands) <= 0 || len(account) <= 0 || len(password) <= 0 || port <= 0 {
return content, fmt.Errorf("parameter is empty")
}
config := &ssh.ClientConfig{
User: account,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 3 * time.Second,
}
if ciphers != nil {
config.Ciphers = ciphers
}
cli, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config)
if err != nil {
log.Println(err.Error())
return "", err
}
defer cli.Close()
// Create sesssion
sess, err := cli.NewSession()
if err != nil {
return "", err
}
defer sess.Close()
// StdinPipe for commands
stdin, err := sess.StdinPipe()
if err != nil {
log.Println(err)
return "", err
}
// Uncomment to store output in variable
var out bytes.Buffer
var stderr bytes.Buffer
sess.Stdout = &out
sess.Stderr = &stderr
// Enable system stdout
// Comment these if you uncomment to store in variable
//sess.Stdout = os.Stdout
//sess.Stderr = os.Stderr
// Start remote shell
err = sess.Shell()
if err != nil {
log.Println(fmt.Sprint(err) + ": " + stderr.String())
return "", fmt.Errorf("err#%v, %s", err.Error(), stderr.String())
}
for _, cmd := range commands {
_, err = fmt.Fprintf(stdin, "%s\n", cmd)
if err != nil {
log.Println(fmt.Sprint(err) + ": " + stderr.String())
return "", fmt.Errorf("err#%v, %s", err.Error(), stderr.String())
}
}
// Wait for sess to finish
err = sess.Wait()
if err != nil {
log.Println(err)
}
content = out.String()
return content, nil
}
func RunSSHCommand(host string, port int, account, password string, commands []string) (string, error) {
return RunSSHCommandWithCipher(host, port, account, password, commands, nil)
}
//SSHAccountVerify 验证SSH账号密码是否正确
func SSHAccountVerifyWithCipher(host string, port int, account, password string, ciphers []string) (bool, error) {
config := &ssh.ClientConfig{
User: account,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 3 * time.Second,
}
if ciphers != nil && len(ciphers) > 0 {
config.Ciphers = ciphers
}
cli, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config)
if err != nil {
log.Println(err.Error())
return false, err
}
defer cli.Close()
return true, nil
}
func SSHAccountVerify(host string, port int, account, password string) (bool, error) {
return SSHAccountVerifyWithCipher(host, port, account, password, nil)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ixxyy/goboot.git
git@gitee.com:ixxyy/goboot.git
ixxyy
goboot
goboot
v0.1.20

搜索帮助

344bd9b3 5694891 D2dac590 5694891