我需要在一个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 :(得分:2)
感谢@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())