golang使用ssh遠程連接服務器並執行命令


安裝golang.org/x

直接去github上面,把https://github.com/zieckey/golang.org,把整個目錄拷貝下來放到你的gopath下面即可。記住在gopath的src下面,一定是golang.org/x/... 

使用

package main

import (
	"fmt"
	"golang.org/x/crypto/ssh"
	"log"
	"net"
	"time"
)

//連接的配置
type ClientConfig struct {
	Host       string       //ip
	Port       int64        // 端口
	Username   string       //用戶名
	Password   string       //密碼
	Client	   *ssh.Client //ssh client
	LastResult string       //最近一次運行的結果
}

func (cliConf *ClientConfig) createClient(host string, port int64, username, password string) {
	var (
		client  *ssh.Client
		err     error
	)
	cliConf.Host = host
	cliConf.Port = port
	cliConf.Username = username
	cliConf.Password = password
	cliConf.Port = port

	//一般傳入四個參數:user,[]ssh.AuthMethod{ssh.Password(password)}, HostKeyCallback,超時時間,
	config := ssh.ClientConfig{
		User: cliConf.Username,
		Auth: []ssh.AuthMethod{ssh.Password(password)},
		HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
			return nil
		},
		Timeout: 10 * time.Second,
	}
	addr := fmt.Sprintf("%s:%d", cliConf.Host, cliConf.Port)

	//獲取client
	if client, err = ssh.Dial("tcp", addr, &config); err != nil {
		log.Fatalln("error occurred:", err)
	}

	cliConf.Client = client
}

func (cliConf *ClientConfig) RunShell(shell string) string {
	var (
		session  *ssh.Session
		err     error
	)

	//獲取session,這個session是用來遠程執行操作的
	if session, err = cliConf.Client.NewSession(); err != nil {
		log.Fatalln("error occurred:", err)
	}

	//執行shell
	if output, err := session.CombinedOutput(shell); err != nil {
		log.Fatalln("error occurred:", err)
	} else {
		cliConf.LastResult = string(output)
	}
	return cliConf.LastResult
}

func main() {
	cliConf := new(ClientConfig)
	cliConf.createClient("xxxx.xxx.xx.xx", 22, "root", "xxxxxxxxx")
	/*
	可以看到我們這里每次執行一條命令都會創建一條session
	這是因為一條session默認只能執行一條命令
	並且兩條命令不可以分開寫
	比如:
	cliConf.RunShell("cd /opt")
	cliConf.RunShell("ls")
	這兩條命令是無法連續的,下面的ls查看的依舊是~目錄
	因此我們可以連着寫,使用;分割
	 */
	fmt.Println(cliConf.RunShell("cd /opt; ls -l"))
	/*
	total 20
	drwxr-xr-x 3 root root 4096 Nov 18 14:05 hadoop
	drwxr-xr-x 3 root root 4096 Nov 18 14:20 hive
	drwxr-xr-x 3 root root 4096 Nov 18 15:07 java
	drwxr-xr-x 3 root root 4096 Nov  4 23:01 kafka
	drwxr-xr-x 3 root root 4096 Nov  4 22:54 zookeeper
	 */
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM