golang并发ping主机的方法
利用了golang对高并发的良好支持,同目录下将ip每行一个写入pinglist.txt文件即可
其实这个功能用linux一条命令就能搞定:
cat pinglist.txt | xargs -P 10 -I {} ping -fc 100 {}
package main import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "strings" "sync" "runtime" ) func RunCMD(command string) string { in := bytes.NewBuffer(nil) cmd := exec.Command("sh") cmd.Stdin = in in.WriteString(command + "\n") stdout, err := cmd.StdoutPipe() if err != nil { log.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { log.Fatal(err) } opBytes, err := ioutil.ReadAll(stdout) if err != nil { log.Fatal(err) } return string(opBytes) } func ping(ip string) string { cmd := "ping -fc 100 " + ip return RunCMD(cmd) } var ips = []string{} func main() { runtime.GOMAXPROCS(runtime.NumCPU()) fileName := "pinglist.txt" f, err := os.Open(fileName) if err != nil { fmt.Println(err) } buf := bufio.NewReader(f) for { line, err := buf.ReadString('\n') line = strings.TrimSpace(line) if err != nil { if err == io.EOF { //fmt.Println("File read over!") break } fmt.Println(err) } ips = append(ips, line) } wg := &sync.WaitGroup{} ch := make(chan string, len(ips)) //fmt.Println(ips) for i:= 0; i < len(ips); i++ { wg.Add(1) go func(i int) { ch <- ping(ips[i]) wg.Done() }(i) } wg.Wait() //fmt.Println(len(ch)) for i := 0; i < len(ips); i++ { fmt.Println(<-ch) } }
相关推荐
txj 2020-09-08
travelinrain 2020-07-27
higheels 2020-07-27
wq0 2020-07-18
Jieen 2020-07-08
luobotoutou 2020-06-16
屿刃 2020-06-14
TinyDolphin 2020-06-13
大老张学编程 2020-06-12
kenson 2020-06-08
PlayerL 2020-06-03
LeoHan 2020-05-31
wenjs00 2020-05-29
comeonxueRong 2020-05-17
furongwei 2020-05-04
BingGoGo技术 2020-04-07
wanggongzhen 2020-03-27
89284553 2020-03-23