Go語言的協程會並發,執行,可以大大提高效率。
列如,我們通過 ping 來檢測網絡的主機的話。
如果使用shell的話,會檢查一個IP,在檢查下一個IP,速度很慢。
如果我們使用Python 的話,可以使用多線程。
我們這里使用Go的協程來操作,速度是剛剛的。
一個網段,10S中,相當於,一秒鍾處理25個左右的IP,因為ping檢查,有延時性

此腳本,只能在Linux上執行
package main
import (
"fmt"
"os/exec"
"strconv"
"strings"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
start := time.Now()
ip := "10.10.10."
wg.Add(254)
for i := 1; i <= 254; i++ {
//fmt.Println(ip + strconv.Itoa(i))
true_ip := ip + strconv.Itoa(i)
go ping(true_ip)
}
wg.Wait()
cost := time.Since(start)
fmt.Println("執行時間:", cost)
}
func ping(ip string) {
var beaf = "false"
Command := fmt.Sprintf("ping -c 1 %s > /dev/null && echo true || echo false", ip)
output, err := exec.Command("/bin/sh", "-c", Command).Output()
if err != nil {
fmt.Println(err)
return
}
real_ip := strings.TrimSpace(string(output))
if real_ip == beaf {
fmt.Printf("IP: %s 失敗\n", ip)
} else {
fmt.Printf("IP: %s 成功 ping通\n", ip)
}
wg.Done()
}
不得不說,GO語言的並發,是真的香啊,
