fix: 解决系统不存在 netstat 命令的问题 (#588)

This commit is contained in:
ssongliu 2023-04-12 11:22:29 +08:00 committed by GitHub
parent f092927ab8
commit aeb9135cde
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 24 deletions

View file

@ -114,8 +114,10 @@ func (u *FirewallService) SearchWithPage(req dto.RuleSearch) (int64, interface{}
if req.Type == "port" {
apps := u.loadPortByApp()
for i := 0; i < len(backDatas); i++ {
backDatas[i].IsUsed = common.ScanPortWithProtocol(backDatas[i].Port, backDatas[i].Protocol)
port, _ := strconv.Atoi(backDatas[i].Port)
backDatas[i].IsUsed = common.ScanPort(port)
if backDatas[i].Protocol == "udp" {
backDatas[i].IsUsed = common.ScanUDPPort(port)
continue
}
for _, app := range apps {
@ -368,10 +370,7 @@ func (u *FirewallService) loadPortByApp() []portOfApp {
}
func (u *FirewallService) PingStatus() (string, error) {
stdout, err := cmd.Exec("sudo cat /etc/sysctl.conf | grep net/ipv4/icmp_echo_ignore_all= ")
if err != nil {
return constant.StatusDisable, fmt.Errorf("load firewall ping status failed, err: %s", stdout)
}
stdout, _ := cmd.Exec("sudo cat /etc/sysctl.conf | grep net/ipv4/icmp_echo_ignore_all= ")
if stdout == "net/ipv4/icmp_echo_ignore_all=1\n" {
return constant.StatusEnable, nil
}

View file

@ -11,8 +11,6 @@ import (
"sort"
"strconv"
"strings"
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
)
func CompareVersion(version1 string, version2 string) bool {
@ -85,7 +83,6 @@ func RandStr(n int) string {
}
func ScanPort(port int) bool {
ln, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if err != nil {
return true
@ -94,24 +91,12 @@ func ScanPort(port int) bool {
return false
}
func ScanPortWithProtocol(port, Protocol string) bool {
command := "netstat -ntpl"
if Protocol == "udp" {
command = "netstat -nupl"
}
stdout, err := cmd.Execf("%s | awk '{print $4}' ", command)
func ScanUDPPort(port int) bool {
ln, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
if err != nil {
return false
}
lines := strings.Split(stdout, "\n")
if len(lines) == 0 {
return false
}
for _, line := range lines {
if strings.HasSuffix(line, ":"+port) {
return true
}
return true
}
defer ln.Close()
return false
}