2016-11-18 38 views
1

我需要在一個SSH會話中運行多個命令:運行在一個SSH多個命令會話

// Define the client configuration 
config := &ssh.ClientConfig{ 
    User: USERNAME, 
    Auth: []ssh.AuthMethod{ 
     ssh.PublicKeys(pem), 
    }, 
} 

// Connect to the machine 
client, err := ssh.Dial("tcp", HOSTNAME + ":" + PORT, config) 
if err != nil { 
    panic("Failed to dial: " + err.Error()) 
} 

// Create a session 
session, err := client.NewSession() 
if err != nil { 
    panic("Failed to create session: " + err.Error()) 
} 
defer session.Close() 

// Start running commands! 
var output bytes.Buffer 
session.Stdout = &output 

// 1) Login to swarm registry 
fmt.Println("Logging into swarm registry...") 
if err := session.Run("docker login ..."); err != nil { 
    panic("Failed to login to swarm registry: " + err.Error()) 
} 
fmt.Println(output.String()) 

// 2) List all of the docker processes 
fmt.Println("List swarm processes...") 
if err := session.Run("docker ps"); err != nil { // <-------- FAILS HERE 
    panic("Failed to list swarm processes: " + err.Error()) 
} 
fmt.Println(output.String()) 

我通過源文件(session.go),併爲Session.Run命令來讀取和它說:

會話只接受一次對Run,Start,Shell,Output或CombinedOutput的調用。

對於我的使用情況下,我需要發出的第一個命令登錄會話,然後發出隨後的命令,一旦我在我登錄。

有沒有使用相同的運行多個命令的替代方法ssh會話?

+0

你試過屏幕 HTTP://www.tecmint。 com/screen-command-examples-to-manage-linux-terminals/ – Xenwar

+0

在單個會話中執行多個命令的唯一方法是在shell腳本中一起執行它們,或者通過解析shell輸出並寫入輸入。這與您在命令行上使用ssh相同。 – JimB

+0

@Tyler:交互式地使用遠程shell並不是真正的建議,它更多的是最後的選擇,而且通常使用「expect」這樣的東西。至於在腳本中發送一系列命令,您需要哪個示例?您已經在這裏實現了它,只需發送要由遠程shell解釋的文本(請記住,ssh只是一個遠程「安全shell」,而不是一般的RPC系統) – JimB

回答

1

感謝@JimB我現在做這個:

// Create a single command that is semicolon seperated 
commands := []string{ 
    "docker login", 
    "docker ps", 
} 
command := strings.Join(commands, "; ") 

,然後運行它像以前一樣:

if err := session.Run(command); err != nil { 
    panic("Failed to run command: " + command + "\nBecause: " + err.Error()) 
} 
fmt.Println(output.String()) 
相關問題