ExecCommandPing 执行系统Ping命令检测主机存活
(ip string)
| 532 | |
| 533 | // ExecCommandPing 执行系统Ping命令检测主机存活 |
| 534 | func ExecCommandPing(ip string) bool { |
| 535 | // 过滤黑名单字符(命令注入防护) |
| 536 | for _, char := range pingForbiddenChars { |
| 537 | if strings.Contains(ip, char) { |
| 538 | return false |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | var command *exec.Cmd |
| 543 | // 根据操作系统选择不同的ping命令 |
| 544 | switch runtime.GOOS { |
| 545 | case "windows": |
| 546 | command = exec.Command("cmd", "/c", "ping -n 1 -w 1 "+ip+" && echo true || echo false") |
| 547 | case "darwin": |
| 548 | command = exec.Command("/bin/bash", "-c", "ping -c 1 -W 1 "+ip+" && echo true || echo false") |
| 549 | default: // linux |
| 550 | command = exec.Command("/bin/bash", "-c", "ping -c 1 -w 1 "+ip+" && echo true || echo false") |
| 551 | } |
| 552 | |
| 553 | // 捕获命令输出 |
| 554 | var outinfo bytes.Buffer |
| 555 | command.Stdout = &outinfo |
| 556 | |
| 557 | // 执行命令 |
| 558 | if err := command.Start(); err != nil { |
| 559 | return false |
| 560 | } |
| 561 | |
| 562 | if err := command.Wait(); err != nil { |
| 563 | return false |
| 564 | } |
| 565 | |
| 566 | // 分析输出结果 |
| 567 | output := outinfo.String() |
| 568 | return strings.Contains(output, "true") && strings.Count(output, ip) > 2 && !containsPingError(output) |
| 569 | } |
| 570 | |
| 571 | // makemsg 构造ICMP echo请求消息 |
| 572 | func makemsg(host string) []byte { |