go實(shí)現(xiàn)ssh遠(yuǎn)程執(zhí)行命令

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容