-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefault_handler.go
More file actions
87 lines (71 loc) · 2.3 KB
/
Copy pathdefault_handler.go
File metadata and controls
87 lines (71 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package sshserver
import (
"fmt"
"strings"
"syscall"
"time"
)
// DefaultCommandHandler provides a basic implementation of CommandHandler
type DefaultCommandHandler struct {
commands map[string]func() (string, error)
}
// NewDefaultHandler creates a new DefaultCommandHandler with basic commands
func NewDefaultHandler() *DefaultCommandHandler {
h := &DefaultCommandHandler{
commands: make(map[string]func() (string, error)),
}
// Register default commands
h.RegisterCommand("hello", func() (string, error) {
return "Hello from SSH Server!", nil
})
h.RegisterCommand("getDate", func() (string, error) {
return fmt.Sprintf("Current server time: %s", time.Now().Format(time.RFC3339)), nil
})
h.RegisterCommand("uptime", func() (string, error) {
var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info)
if err != nil {
return "", fmt.Errorf("error getting system info: %v", err)
}
uptime := time.Duration(info.Uptime) * time.Second
days := int(uptime.Hours() / 24)
hours := int(uptime.Hours()) % 24
minutes := int(uptime.Minutes()) % 60
return fmt.Sprintf("Server uptime: %d days, %d hours, %d minutes", days, hours, minutes), nil
})
h.RegisterCommand("help", func() (string, error) {
var commands []string
for cmd := range h.commands {
commands = append(commands, cmd)
}
return fmt.Sprintf("Available commands: %s", strings.Join(commands, ", ")), nil
})
return h
}
// RegisterCommand adds a new command to the handler
func (h *DefaultCommandHandler) RegisterCommand(name string, handler func() (string, error)) {
h.commands[name] = handler
}
// Execute implements CommandHandler.Execute
func (h *DefaultCommandHandler) Execute(cmd string) (string, uint32) {
cmd = strings.TrimSpace(cmd)
if cmd == "" {
return "", 0
}
if handler, ok := h.commands[cmd]; ok {
output, err := handler()
if err != nil {
return fmt.Sprintf("Error: %v", err), 1
}
return output, 0
}
return fmt.Sprintf("Unknown command: %s\nUse 'help' to see available commands", cmd), 1
}
// GetPrompt implements CommandHandler.GetPrompt
func (h *DefaultCommandHandler) GetPrompt() string {
return "$ "
}
// GetWelcomeMessage implements CommandHandler.GetWelcomeMessage
func (h *DefaultCommandHandler) GetWelcomeMessage() string {
return "Welcome to SSH Server!\nType 'help' to see available commands"
}