2016-11-18 40 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()) 
相关问题