英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论