利用了golang对高并发的良好支持,同目录下将ip每行一个写入pinglist.txt文件即可
其实这个功能用linux一条命令就能搞定:
cat pinglist.txt | xargs -P 10 -I {} ping -fc 100 {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
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) } } |
以上这篇golang并发ping主机的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Jailman/article/details/81286726