feat: ws获取网络连接进程
This commit is contained in:
20
src/modules/ws/model/net_connect.go
Normal file
20
src/modules/ws/model/net_connect.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package model
|
||||
|
||||
import "github.com/shirou/gopsutil/v3/net"
|
||||
|
||||
// NetConnectData 网络连接进程数据
|
||||
type NetConnectData struct {
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Laddr net.Addr `json:"localaddr"`
|
||||
Raddr net.Addr `json:"remoteaddr"`
|
||||
PID int32 `json:"PID"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// NetConnectQuery 网络连接进程查询
|
||||
type NetConnectQuery struct {
|
||||
Port int32 `json:"port"`
|
||||
ProcessName string `json:"processName"`
|
||||
ProcessID int32 `json:"processID"`
|
||||
}
|
||||
53
src/modules/ws/processor/net_connect.go
Normal file
53
src/modules/ws/processor/net_connect.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"ems.agt/src/modules/ws/model"
|
||||
"github.com/shirou/gopsutil/v3/net"
|
||||
"github.com/shirou/gopsutil/v3/process"
|
||||
)
|
||||
|
||||
// GetNetConnections 获取网络连接进程
|
||||
func GetNetConnections(data any) ([]byte, error) {
|
||||
msgByte, _ := json.Marshal(data)
|
||||
var query model.NetConnectQuery
|
||||
err := json.Unmarshal(msgByte, &query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result := []model.NetConnectData{}
|
||||
for _, netType := range [...]string{"tcp", "udp"} {
|
||||
connections, _ := net.Connections(netType)
|
||||
if err == nil {
|
||||
for _, conn := range connections {
|
||||
if query.ProcessID > 0 && query.ProcessID != conn.Pid {
|
||||
continue
|
||||
}
|
||||
proc, err := process.NewProcess(conn.Pid)
|
||||
if err == nil {
|
||||
name, _ := proc.Name()
|
||||
if name != "" && query.ProcessName != "" && !strings.Contains(name, query.ProcessName) {
|
||||
continue
|
||||
}
|
||||
if query.Port > 0 && query.Port != int32(conn.Laddr.Port) && query.Port != int32(conn.Raddr.Port) {
|
||||
continue
|
||||
}
|
||||
result = append(result, model.NetConnectData{
|
||||
Type: netType,
|
||||
Status: conn.Status,
|
||||
Laddr: conn.Laddr,
|
||||
Raddr: conn.Raddr,
|
||||
PID: conn.Pid,
|
||||
Name: name,
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
resultByte, err := json.Marshal(result)
|
||||
return resultByte, err
|
||||
}
|
||||
@@ -23,6 +23,12 @@ func (s *WSReceiveImpl) Receive(client *model.WSClient, reqMsg model.WSRequest)
|
||||
return err
|
||||
}
|
||||
client.MsgChan <- res
|
||||
case "net":
|
||||
res, err := processor.GetNetConnections(reqMsg.Data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client.MsgChan <- res
|
||||
default:
|
||||
return fmt.Errorf("message type not supported")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user