Home > database >  How to grab output when using ssh library in Golang
How to grab output when using ssh library in Golang

Time:08-17

I'm coding a small project to manage Cisco switch, It's all good until I need to grab output from Stout. Here is my code.

func Return_current_user(conn *ssh.Client) {
    session, err := conn.NewSession()
    if err != nil {
        log.Fatal("Failed to create session %v: ", err)
    }
    
    sdtin, _ := session.StdinPipe()
    session.Stdout = os.Stdout
    session.Stdin = os.Stdin
    session.Shell()

    cmds := []string{
        "conf t",
        "show users",
        
    }
    for _, cmd := range cmds {
        fmt.Fprintf(sdtin, "%s\n", cmd)
    }
    session.Wait()
    session.Close()
}

Here is my output in the screen:

NAME     LINE         TIME         IDLE          PID COMMENT
admin    pts/0        Aug 16 06:13 00:02       29059 (192.168.57.1)
NAME     LINE         TIME         IDLE          PID COMMENT
admin    pts/0        Aug 16 06:13 00:02       29059 (192.168.57.1)

I can only make the output of the remote command appear but How can I save those outputs in another variable to process in the future. Thank you very much.

CodePudding user response:

Don't override session.Stdout with os.Stdout, which will just send output to the console, but read from the Reader returned from session.StdoutPipe() instead.

  •  Tags:  
  • go
  • Related