How to grab output when using ssh library in Golang

huangapple go评论108阅读模式
英文:

How to grab output when using ssh library in Golang

问题

我正在编写一个小项目来管理 Cisco 交换机,一切都很好,直到我需要从标准输出中获取输出。以下是我的代码。

  1. func Return_current_user(conn *ssh.Client) {
  2. session, err := conn.NewSession()
  3. if err != nil {
  4. log.Fatal("Failed to create session %v: ", err)
  5. }
  6. sdtin, _ := session.StdinPipe()
  7. session.Stdout = os.Stdout
  8. session.Stdin = os.Stdin
  9. session.Shell()
  10. cmds := []string{
  11. "conf t",
  12. "show users",
  13. }
  14. for _, cmd := range cmds {
  15. fmt.Fprintf(sdtin, "%s\n", cmd)
  16. }
  17. session.Wait()
  18. session.Close()
  19. }

这是我在屏幕上的输出:

  1. NAME LINE TIME IDLE PID COMMENT
  2. admin pts/0 Aug 16 06:13 00:02 29059 (192.168.57.1)
  3. NAME LINE TIME IDLE PID COMMENT
  4. admin pts/0 Aug 16 06:13 00:02 29059 (192.168.57.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.

  1. func Return_current_user(conn *ssh.Client) {
  2. session, err := conn.NewSession()
  3. if err != nil {
  4. log.Fatal("Failed to create session %v: ", err)
  5. }
  6. sdtin, _ := session.StdinPipe()
  7. session.Stdout = os.Stdout
  8. session.Stdin = os.Stdin
  9. session.Shell()
  10. cmds := []string{
  11. "conf t",
  12. "show users",
  13. }
  14. for _, cmd := range cmds {
  15. fmt.Fprintf(sdtin, "%s\n", cmd)
  16. }
  17. session.Wait()
  18. session.Close()
  19. }

Here is my output in the screen:

  1. NAME LINE TIME IDLE PID COMMENT
  2. admin pts/0 Aug 16 06:13 00:02 29059 (192.168.57.1)
  3. NAME LINE TIME IDLE PID COMMENT
  4. 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.

答案1

得分: 1

不要用os.Stdout覆盖session.Stdout,后者只会将输出发送到控制台,而应该从session.StdoutPipe()返回的Reader中读取。

英文:

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.

huangapple
  • 本文由 发表于 2022年8月16日 14:38:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/73369734.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定