//根据端口号查进程pid func PortToPid(port int) int { res := -1 var outBytes bytes.Buffer var cmd *exec.Cmd goos := runtime.GOOS switch goos { case "windows": cmdStr := fmt.Sprintf("netstat -ano -p tcp | findstr %d", port) cmd = exec.Command("cmd", "/c", cmdStr) break case "linux": cmdStr := fmt.Sprintf("lsof -i:%d", port) cmd = exec.Command("bash","-c",cmdStr) fmt.Println(cmdStr) fmt.Println(cmd) break } cmd.Stdout = &outBytes cmd.Run() resStr := outBytes.String() r := regexp.MustCompile(`\s\d+\s`).FindAllString(resStr, -1) if len(r) > 0 { pid, err := strconv.Atoi(strings.TrimSpace(r[0])) if err != nil { res = -1 } else { res = pid } } return res }
go执行windows或Linux下的cmd命令
最新推荐文章于 2024-05-18 01:05:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)