From dd0713bbe2f1993fdbf555de537017672bf24e5f Mon Sep 17 00:00:00 2001 From: HynoR <20227709+HynoR@users.noreply.github.com> Date: Fri, 5 Dec 2025 18:19:13 +0800 Subject: [PATCH] feat: Implement fallback user information retrieval in SSH session handling * Added a new function to retrieve user information using the 'who' command as a fallback when host.Users() fails. * Enhanced error handling to ensure proper response when user information cannot be retrieved. --- agent/utils/websocket/process_data.go | 52 +++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/agent/utils/websocket/process_data.go b/agent/utils/websocket/process_data.go index 8f8cd01d1..aead47c6d 100644 --- a/agent/utils/websocket/process_data.go +++ b/agent/utils/websocket/process_data.go @@ -3,12 +3,14 @@ package websocket import ( "encoding/json" "fmt" - "github.com/1Panel-dev/1Panel/agent/utils/common" "sort" "strings" "sync" "time" + "github.com/1Panel-dev/1Panel/agent/utils/cmd" + "github.com/1Panel-dev/1Panel/agent/utils/common" + "github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/utils/files" "github.com/shirou/gopsutil/v4/host" @@ -258,8 +260,11 @@ func getSSHSessions(config SSHSessionConfig) (res []byte, err error) { } users, err = host.Users() if err != nil { - res, err = json.Marshal(result) - return + users, err = fallbackUserInfo() + if err != nil { + res, err = json.Marshal(nil) + return + } } for _, proc := range processes { name, _ := proc.Name() @@ -300,6 +305,47 @@ func getSSHSessions(config SSHSessionConfig) (res []byte, err error) { return } +func fallbackUserInfo() ([]host.UserStat, error) { + whoCmd, err := cmd.RunDefaultWithStdoutBashC("who") + if err != nil { + return nil, err + } + + var users []host.UserStat + lines := strings.Split(whoCmd, "\n") + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + fields := strings.Fields(line) + if len(fields) < 4 { + continue + } + + user := host.UserStat{ + User: fields[0], + Terminal: fields[1], + } + + dateTimeStr := fields[2] + " " + fields[3] + if t, err := time.Parse("2006-01-02 15:04", dateTimeStr); err == nil { + user.Started = int(t.Unix()) + } + + if len(fields) >= 5 { + hostStr := fields[4] + hostStr = strings.TrimPrefix(hostStr, "(") + hostStr = strings.TrimSuffix(hostStr, ")") + user.Host = hostStr + } + + users = append(users, user) + } + + return users, nil +} + var netTypes = [...]string{"tcp", "udp"} func getNetConnections(config NetConfig) (res []byte, err error) {