package?main
import?(
????"fmt"
????"golang.org/x/crypto/ssh"
????"log"
????"time"
)
func?main(){
????sshHost?:=?"192.168.6.126"
????sshUser?:=?"root"
????sshPassword?:=?"123456"
????sshType?:=?"password"
????sshPort?:=?22
????//創(chuàng)建sshp登陸配置
????config?:=?&ssh.ClientConfig{
????????Timeout:?????????5*time.Second,//ssh?連接time?out?時(shí)間一秒鐘,?如果ssh驗(yàn)證錯(cuò)誤?會(huì)在一秒內(nèi)返回
????????User:????????????sshUser,
????????HostKeyCallback:?ssh.InsecureIgnoreHostKey(),?//這個(gè)可以,?但是不夠安全
????????//HostKeyCallback:?hostKeyCallBackFunc(h.Host),
????}
????if?sshType?==?"password"?{
????????config.Auth?=?[]ssh.AuthMethod{ssh.Password(sshPassword)}
????}
????//dial?獲取ssh?client
????addr?:=?fmt.Sprintf("%s:%d",?sshHost,?sshPort)
????sshClient,?err?:=?ssh.Dial("tcp",?addr,?config)
????if?err?!=?nil?{
????????log.Fatal("創(chuàng)建ssh?client?失敗",err)
????}
????defer?sshClient.Close()
????//創(chuàng)建ssh-session
????session,?err?:=?sshClient.NewSession()
????if?err?!=?nil?{
????????log.Fatal("創(chuàng)建ssh?session?失敗",err)
????}
????defer?session.Close()
????//執(zhí)行遠(yuǎn)程命令
????combo,err?:=?session.CombinedOutput("whoami;?cd?/root/;?ls?-al;echo?Hello?>?hello.txt;echo?hello;curl?http://baidu.com")
????if?err?!=?nil?{
????????log.Fatal("遠(yuǎn)程執(zhí)行cmd?失敗",err)
????}
????log.Println("命令輸出:",string(combo))
}
源碼來(lái)自:https://www.cnblogs.com/you-men/p/14163364.html