【golang】windows下根据端口找到对应进程并杀死
package main
import (
"fmt"
"golang.org/x/text/encoding/simplifiedchinese"
"os"
"os/exec"
"strings"
)
//main 根据端口找到服务并杀死对应进程
func main() {
if len(os.Args) < 2 {
fmt.Println("缺少端口参数")
}
c1 := exec.Command("powershell.exe", "netstat", "-ano")
output, _ := c1.CombinedOutput()
decodeBytes, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(output)
strNetstat := string(decodeBytes)
Port := os.Args[1]
Pid := "0"
for _, v := range strings.Split(strNetstat, "\r\n") {
for {
if strings.Contains(v, " ") {
v = strings.ReplaceAll(v, " ", " ")
} else {
break
}
}
strings.Trim(v, " ")
arrTmp := strings.Split(v, " ")
arr := make([]string, 0)
for _, vv := range arrTmp {
if vv != "" {
arr = append(arr, vv)
}
}
if len(arr) == 5 && fmt.Sprintf("0.0.0.0:%v", Port) == arr[1] {
Pid = arr[4]
break
}
}
if Pid == "0" {
fmt.Printf("没找到端口号为%v的服务\n", Port)
return
}
c2 := exec.Command("powershell.exe", "taskkill -PID ", Pid, "-F")
output, _ = c2.CombinedOutput()
decodeBytes, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(output)
delStr := string(decodeBytes)
fmt.Printf("找到端口为%v的服务,%s\n", Port, delStr)
}