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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3