gpt4 book ai didi

go - 在一个 SSH session 中运行多个命令

转载 作者:IT王子 更新时间:2023-10-29 01:41:51 25 4
gpt4 key购买 nike

我需要在单个 ssh session 中运行多个命令:

// 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 命令,它说:

A Session only accepts one call to Run, Start, Shell, Output, or CombinedOutput.

对于我的用例,我需要发出第一个命令来登录 session ,然后在登录后发出后续命令。

有没有其他方法可以使用同一个 ssh session 运行多个命令?

最佳答案

感谢@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())

关于go - 在一个 SSH session 中运行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40684160/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com