使用GO語言靈活批量ssh登入伺服器執行操作

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

go語言是一門新興語言,能夠在很多地方發揮總用。初學go語言,做了這麼一個小工具,也算是練練手了。

 

這個小程式實現的功能是從使用者指定的檔案中讀取相關配置,然後根據使用者指令執行相關操作。

 

代碼如下:

package mainimport ("fmt""golang.org/x/crypto/ssh""os""io""bufio""encoding/csv""strings""container/list")var (num int)func main() {if len(os.Args) == 1{fmt.Println("請輸入檔案名稱參數")return}list := listNode(os.Args[1])fmt.Println("請選擇執行的語句")fmt.Scanln(&num)if num <= list.Len(){fmt.Println("您選擇的是 ", num)ssh_to_do(list,num)}else {fmt.Println("您輸入有誤! num:",num)}}func ssh_to_do(list *list.List, num int) {if num != 0 {i := 1for node := list.Front(); node != nil; node = node.Next() {if i == num {switch value := node.Value.(type) {case BatchNode:SSH_do(value.User, value.Password, value.Ip_port, value.Cmd)}}i++}} else {for node := list.Front(); node != nil; node = node.Next() {switch value := node.Value.(type) {case BatchNode:SSH_do(value.User, value.Password, value.Ip_port, value.Cmd)}}}}func listNode(fileName string) *list.List {list := readNode(fileName)fmt.Printf("共計 %d 條資料\n", list.Len())i := 1for node := list.Front(); node != nil; node = node.Next() {switch value := node.Value.(type) {case BatchNode:fmt.Println(i, "  ", value.String())}i++}return list}func SSH_do(user, password, ip_port string, cmd string) {PassWd := []ssh.AuthMethod{ssh.Password(password)}Conf := ssh.ClientConfig{User: user, Auth: PassWd}Client, _ := ssh.Dial("tcp", ip_port, &Conf)defer Client.Close()for {command := cmdif session, err := Client.NewSession(); err == nil {defer session.Close()session.Stdout = os.Stdoutsession.Stderr = os.Stderrsession.Run(command)break}}}type BatchNode struct {User     stringPassword stringIp_port  stringCmd      string}func (batchNode *BatchNode) String() string {return "ssh " + batchNode.User + "@" + batchNode.Ip_port + "  with password: " + batchNode.Password + "  and run: " + batchNode.Cmd}func readNode(fileName string) *list.List {inputFile, err := os.Open(fileName)if err != nil {fmt.Printf("在開啟檔案的時候出現錯誤\n檔案存在嗎?\n有許可權嗎?\n")return list.New()}defer inputFile.Close()batchNodeList := list.New()inputReader := bufio.NewReader(inputFile)for {inputString, err := inputReader.ReadString('\n')r := csv.NewReader(strings.NewReader(string(inputString)))for {record, err := r.Read()if err == io.EOF {break}if err != nil {fmt.Println("error !!! ", err)continue}batchNode := BatchNode{record[0], record[1], record[2], record[3]}batchNodeList.PushBack(batchNode)}if err == io.EOF {break}}return batchNodeList}

 

我的檔案內容是:

gavin,xxxx,192.168.1.128:22,echo ok1 >>a.datagavin,xxxx,192.168.1.128:22,echo ok2 >>a.datagavin,xxxx,192.168.1.128:22,echo ok3 >>a.datagavin,xxxx,192.168.1.128:22,echo ok4 >>a.data

小程式限制使用csv格式的檔案內容,這種格式也方便被excel處理

啟動並執行結果如下:
共計 4 條資料
1    ssh gavin@192.168.1.128:22  with password: root  and run: echo ok1 >>a.data
2    ssh gavin@192.168.1.128:22  with password: root  and run: echo ok2 >>a.data
3    ssh gavin@192.168.1.128:22  with password: root  and run: echo ok3 >>a.data
4    ssh gavin@192.168.1.128:22  with password: root  and run: echo ok4 >>a.data
請選擇執行的語句
1
您選擇的是  1

 

 

去線上查看:

 

如果輸入的是0,則執行所有配置項。也就是說如果有固定執行的任務,可以很方便地批量去操控了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.