1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your comment, can you give me clearer example of how to read from io.Reader.
0

You could capture the session's output to a bytes buffer instead of os.

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()

    //here
    var b, e bytes.Buffer
    session.Stdout = &b
    session.Stderr = &e

    session.Shell()

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

    session.Wait()
    session.Close()

    fmt.Println(b.string())
    fmt.Println(e.string())
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.