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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
| package main
import ( "bufio" "fmt" "os" "regexp" "sync" "time"
"os/exec" "strings"
"golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" )
var ( core int = 200 interval time.Duration = 20 ipsArr = []string{} )
func main() {
file, err := os.Open("ips.txt") if err != nil { fmt.Println("打开文件失败:", err) return } defer file.Close()
ipPattern := `(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})` re := regexp.MustCompile(ipPattern)
scanner := bufio.NewScanner(file)
for scanner.Scan() { line := scanner.Text() ips := re.FindAllString(line, -1) ipsArr = append(ipsArr, ips...) } fmt.Println("总ip地址个数:", len(ipsArr)) ipsChannl := make(chan string, len(ipsArr)) for i := 0; i < len(ipsArr); i++ { ipsChannl <- ipsArr[i] }
count := 0
close(ipsChannl)
results := make(chan string, len(ipsArr))
var wg sync.WaitGroup for i := 0; i < core; i++ { wg.Add(1) time.Sleep(time.Millisecond * interval) go func(id int) { defer wg.Done() PING(id, ipsChannl, results, &count, len(ipsArr)) }(i) } stop := false for ip := range results { saveToText(ip) if stop { break } } go func() { wg.Wait() close(results) stop = true }()
if err := scanner.Err(); err != nil { fmt.Println("解析文件失败:", err) }
}
func PING(id int, ips <-chan string, results chan string, count *int, total int) { *count += 1 time.Sleep(time.Microsecond * 100)
for ip := range ips { fmt.Printf("协程编号: %d ,开始处理任务: %s ,当前进度:%d / %d \n", id, ip, *count, total)
target := ip cmd := exec.Command("C:\\Windows\\System32\\ping.exe", "-n", "2", target)
output, err := cmd.CombinedOutput() if err != nil { fmt.Println("Ping命令执行失败:", err) return }
decoder := simplifiedchinese.GBK.NewDecoder() output, _, _ = transform.Bytes(decoder, output)
outputStr := string(output)
lines := strings.Split(outputStr, "\r\n") for _, line := range lines { if strings.Contains(line, "时间=") { parts := strings.Split(line, "时间=") if len(parts) >= 2 { delayPart := parts[1] delay := strings.Split(delayPart, "ms")[0]
fmt.Printf("IP ping成功:%s ,延迟:%s ms\n", ip, delay) results <- (delay + "ms " + ip)
} } } } }
func saveToText(ip string) { file, err := os.OpenFile("reachable_ips.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777) if err != nil { fmt.Println("打开文档出错:", err) return } defer file.Close()
_, err = fmt.Fprintln(file, ip) if err != nil { fmt.Println("写入数据出错:", err) } }
|