How to grab output when using ssh library in Golang

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

How to grab output when using ssh library in Golang

问题

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

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

这是我在屏幕上的输出:

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'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.

答案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:

确定