title: Golang通过exec模块实现Ping连通性检测案例
date: 2022-04-22 23:07:10.0
updated: 2022-04-22 23:07:10.0
url: https://liumou.site/doc/455
categories:

  • 开发
  • GO
    tags:
  • Go

源码

import (
    "fmt"
    "os/exec"
    "runtime"
)

// 小写函数名称只能在当前文件调用
func pingcmd(host string) bool {
    // 实例化一个执行任务
    cmds := exec.Command("ping", host)
    // 开始执行
    err := cmds.Run()
    // 判断执行状态(只获取成功或者失败)
    if err != nil {
        fmt.Println("Connection failed: ", host)
        return false
    }else {
        fmt.Println("Connection successful:  ", host)
        return true
    }
}
// 大写开头的函数可被外部调用
func PingStatus(host string) bool {
    // 检测ping是否连接成功
    fmt.Println("Pinging ", host)
    // 获取当前系统类型
    sysType := runtime.GOOS
    // 打印当前系统类型
    fmt.Println("Current system type: ", sysType)
    // 根据系统类型设置对应的参数
    if sysType == "windows" {
        // Windows 系统下直接使用ping ip
        status := pingcmd(host)
        return status
    }else{
        // 非windows下需要使用-c 指定数据包数量
        host := host + " -c 5"
        status := pingcmd(host)
        return status
    }
    return false
}
func main() {
    d := PingStatus("baidu.com")
    if d {
        fmt.Println("ok")
    }else {
        fmt.Println("Errors")
    }
}

执行结果

Pinging  baidu.com
Current system type:  windows
Connection successful:   baidu.com
ok