golang官方包:
https://studygolang.com/pkgdoc
os
支持获取当前进程pid并kill、但是仅仅限于获取当前进程pid
FindProcess().Kill() os.Getpid()
基础用法;但是却没有提供依据端口号获取对应的pid,所以还是执行shell指令对结果集进行过滤获取pid
// 获取8299端口对应进程号并kill
processInfo := exec.Command("/bin/sh", "-c",`lsof -i:8299 | awk '{print $2}' | awk 'NR==2{print}'`)
if pid, err := processInfo.Output(); err != nil {
fmt.Println(err.Error())
}else{
fmt.Println(string(pid))
processExit := exec.Command("/bin/sh", "-c",`kill `+string(pid))
if _, err := processExit.Output(); err != nil {
fmt.Println(err.Error())
}
}
and
// 传入查询的端口号
// 返回端口号对应的进程PID,若没有找到相关进程,返回-1
func portInUse(portNumber int) int {
res := -1
var outBytes bytes.Buffer
cmdStr := fmt.Sprintf("netstat -ano -p tcp | findstr %d", portNumber)
cmd := exec.Command("cmd", "/c", cmdStr)
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
}
端口检测:
func ScanPort(protocol string, hostname string, port int) bool {
fmt.Printf("scanning port %d \n", port)
p := strconv.Itoa(port)
addr := net.JoinHostPort(hostname, p)
conn, err := net.DialTimeout(protocol, addr, 3*time.Second)
if err != nil {
return false
}
defer conn.Close()
return true
}
参考博客:
https://www.jb51.net/article/208384.htm