go ssh开箱即用,注意几点

package main

import (
"bytes"
"fmt"
"go-test/src/model"
"golang.org/x/crypto/ssh"
"log"
)

func sshAuthMethod(passwd, pkFile, pkPasswd string) (auth []ssh.AuthMethod) {
// pkfile存在, 就进行密钥验证, 如果不存在,则跳过密钥验证。

// 密码不为空, 则添加密码验证。
if passwd != "" {
auth = append(auth, ssh.Password(passwd))
}

return auth
}




func main() {
model.DbInit("conf.toml.template")
sshConfig := ssh.Config{
Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", "arcfour256", "arcfour128", "aes128-cbc", "3des-cbc", "aes192-cbc", "aes256-cbc"},
}
//DefaultTimeout := time.Duration(1) * time.Minute


config := ssh.ClientConfig{
User: "root",
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
//Timeout: DefaultTimeout, 默认0即可
Config: sshConfig,
Auth: sshAuthMethod("xxxxx@","",""),

}

client, err2 := ssh.Dial("tcp", "192.168.9.107:22", &config)

if err2 != nil{
fmt.Println(err2)
}
defer client.Close()
session,err4:=client.NewSession()
if err4!= nil{
fmt.Println(err4)
}
defer session.Close()



var b bytes.Buffer //优先RUN之前
session.Stdout = &b


if err := session.Run("ifconfig"); err != nil {
log.Fatal("Failed to run: " + err.Error())
}

fmt.Println(b.String())








}
posted @   技术颜良  阅读(480)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2018-03-21 ELK 之三:Kibana 使用与Tomcat、Nginx 日志格式处理
2018-03-21 ELK 日志分析实例
点击右上角即可分享
微信分享提示