doukanwen4114 2016-11-18 18:52
浏览 155
已采纳

在一个SSH会话中运行多个命令

I need to run multiple commands in a single 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())

I read through the source file (session.go) and for the Session.Run command and it says:

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

For my use case I need to issue the first command to log the session in, and then issue subsequent commands once I am logged in.

Is there an alternate way to run multiple commands using the same ssh session?

  • 写回答

2条回答 默认 最新

  • duanqiu9104 2016-11-18 20:48
    关注

    Thanks to @JimB I am now doing this instead:

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

    And then running it the same as before:

    if err := session.Run(command); err != nil {
        panic("Failed to run command: " + command + "
    Because: " + err.Error())
    }
    fmt.Println(output.String())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败