草庐IT

go - 使用 channel 捕获 Goroutine 的输出和错误

coder 2024-07-05 原文

我有一个调用函数的 for 循环 runCommand()它在交换机上运行远程命令并打印输出。该函数在每次迭代时在 goroutine 中调用,我使用的是 sync.Waitgroup同步 goroutines。现在,我需要一种方法来捕获 runCommand() 的输出和任何错误作用于 channel 。我已经阅读了很多文章并观看了很多关于将 channel 与 goroutines 一起使用的视频,但这是我第一次编写并发应用程序,我似乎无法理解这个想法。

基本上,我的程序从命令行获取主机名列表,然后异步连接到每个主机,在其上运行配置命令,并打印输出。如果出现错误,我的程序可以继续配置其余主机。

我将如何以惯用的方式将每次调用的输出或错误发送到 runCommand()到一个 channel 然后接收打印输出或错误?

这是我的代码:

package main

import (
    "fmt"
    "golang.org/x/crypto/ssh"
    "os"
    "time"
    "sync"
)

func main() {
    hosts := os.Args[1:]
    clientConf := configureClient("user", "password")

    var wg sync.WaitGroup
    for _, host := range hosts {
        wg.Add(1)
        go runCommand(host, &clientConf, &wg)
    }
    wg.Wait()

    fmt.Println("Configuration complete!")
}

// Run a remote command
func runCommand(host string, config *ssh.ClientConfig, wg *sync.WaitGroup) {
    defer wg.Done()
    // Connect to the client
    client, err := ssh.Dial("tcp", host+":22", config)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer client.Close()
    // Create a session
    session, err := client.NewSession()
    if err != nil {
        fmt.Println(err)
        return
    }
    defer session.Close()
    // Get the session output
    output, err := session.Output("show lldp ne")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Print(string(output))
    fmt.Printf("Connection to %s closed.\n", host)
}

// Set up client configuration
func configureClient(user, password string) ssh.ClientConfig {
    var sshConf ssh.Config
    sshConf.SetDefaults()
    // Append supported ciphers
    sshConf.Ciphers = append(sshConf.Ciphers, "aes128-cbc", "aes256-cbc", "3des-cbc", "des-cbc", "aes192-cbc")
    // Create client config
    clientConf := &ssh.ClientConfig{
        Config:          sshConf,
        User:            user,
        Auth:            []ssh.AuthMethod{ssh.Password(password)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout:         time.Second * 5,
    }
    return *clientConf
}

编辑: 我按照建议摆脱了 Waitgroup,现在我需要通过在打印输出和打印 Connection to <host> closed. 之前打印主机名来跟踪哪个输出属于哪个主机。 goroutine 完成时的消息。例如:

$ go run main.go host1[,host2[,...]]
Connecting to <host1>
[Output]
...
[Error]
Connection to <host1> closed.

Connecting to <host2>
...
Connection to <host2> closed.

Configuration complete!

我知道上面不一定会处理 host1host2按顺序,但我需要分别在输出/错误之前和之后为连接和关闭消息打印正确的主机值。我尝试推迟在 runCommand() 中打印结束消息功能,但消息在输出/错误之前打印出来。在每次 goroutine 调用后在 for 循环中打印结束消息也无法按预期工作。

更新代码:

package main

import (
    "fmt"
    "golang.org/x/crypto/ssh"
    "os"
    "time"
)

type CmdResult struct {
    Host string
    Output string
    Err error
}

func main() {
    start := time.Now()

    hosts := os.Args[1:]
    clientConf := configureClient("user", "password")
    results := make(chan CmdResult)

    for _, host := range hosts {
        go runCommand(host, &clientConf, results)
    }
    for i := 0; i < len(hosts); i++ {
        output := <- results
        fmt.Println(output.Host)
        if output.Output != "" {
            fmt.Printf("%s\n", output.Output)
        }
        if output.Err != nil {
            fmt.Printf("Error: %v\n", output.Err)
        }
    }
    fmt.Printf("Configuration complete! [%s]\n", time.Since(start).String())
}

// Run a remote command
func runCommand(host string, config *ssh.ClientConfig, ch chan CmdResult) {
    // This is printing before the output/error(s).
    // Does the same when moved to the bottom of this function.
    defer fmt.Printf("Connection to %s closed.\n", host)

    // Connect to the client
    client, err := ssh.Dial("tcp", host+":22", config)
    if err != nil {
        ch <- CmdResult{host, "", err}
        return
    }
    defer client.Close()
    // Create a session
    session, err := client.NewSession()
    if err != nil {
        ch <- CmdResult{host, "", err}
        return
    }
    defer session.Close()
    // Get the session output
    output, err := session.Output("show lldp ne")
    if err != nil {
        ch <- CmdResult{host, "", err}
        return
    }
    ch <- CmdResult{host, string(output), nil}
}

// Set up client configuration
func configureClient(user, password string) ssh.ClientConfig {
    var sshConf ssh.Config
    sshConf.SetDefaults()
    // Append supported ciphers
    sshConf.Ciphers = append(sshConf.Ciphers, "aes128-cbc", "aes256-cbc", "3des-cbc", "des-cbc", "aes192-cbc")
    // Create client config
    clientConf := &ssh.ClientConfig{
        Config:          sshConf,
        User:            user,
        Auth:            []ssh.AuthMethod{ssh.Password(password)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout:         time.Second * 5,
    }
    return *clientConf
}

最佳答案

如果您使用无缓冲 channel ,您实际上不需要 sync.WaitGroup,因为您可以为将在 channel 上发送的每个 goroutine 调用 channel 上的接收操作符一次。每个接收操作都将阻塞,直到发送语句准备就绪,从而导致与 WaitGroup 相同的行为。

要做到这一点,请将 runCommand 更改为在所有条件下都在函数退出之前恰好执行一次 send 语句。

首先,创建一个类型以通过 channel 发送:

type CommandResult struct {
    Output      string
    Err         error
}

并编辑您的 main() {...} 以在 channel 上执行接收操作的次数与将发送到 channel 的 goroutine 的数量相同:

func main() {
    ch := make(chan CommandResult) // initialize an unbuffered channel
    // rest of your setup
    for _, host := range hosts {
        go runCommand(host, &clientConf, ch) // pass in the channel
    }
    for x := 0; x < len(hosts); x++ {
        fmt.Println(<-ch) // this will block until one is ready to send
    }

并编辑您的 runCommand 函数以接受 channel ,删除对 WaitGroup 的引用,并在所有条件下只执行一次发送:

func runCommand(host string, config *ssh.ClientConfig, ch chan CommandResult) {
    // do stuff that generates output, err; then when ready to exit function:
    ch <- CommandResult{output, err}
}

编辑:问题更新为标准输出消息顺序要求

I'd like to get nicely formatted output that ignores the order of events

在这种情况下,从 runCommand 中删除所有打印消息,您将把所有输出放入您在 channel 上传递的元素中,以便将它们组合在一起。编辑 CommandResult 类型以包含您要组织的其他字段,例如:

type CommandResult struct {
    Host        string
    Output      string
    Err         error
}

如果您不需要对结果进行排序,您可以继续打印收到的数据,例如

for x := 0; x < len(hosts); x++ {
    r := <-ch
    fmt.Printf("Host: %s----\nOutput: %s\n", r.Host, r.Output)
    if r.Err != nil {
        fmt.Printf("Error: %s\n", r.Err)
    }
}

如果您确实需要对结果进行排序,那么在您的 main goroutine 中,将在 channel 上接收到的元素添加到一个 slice 中:

    ...
    results := make([]CommandResult, 0, len(hosts))
    for x := 0; x < len(hosts); x++ {
        results = append(results, <-ch) // this will block until one is ready to send
    }

然后你可以使用the sort package在 Go 标准库中对结果进行排序以进行打印。例如,您可以按主机的字母顺序对它们进行排序。或者您可以将结果放入以主机字符串作为键而不是 slice 的映射中,以允许您按原始主机列表的顺序打印。

关于go - 使用 channel 捕获 Goroutine 的输出和错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981528/

有关go - 使用 channel 捕获 Goroutine 的输出和错误的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  5. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  6. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  7. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  8. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  9. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  10. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

随机推荐