-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (74 loc) · 2.03 KB
/
Copy pathmain.go
File metadata and controls
87 lines (74 loc) · 2.03 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 main
// A simple program that counts down from 5 and then exits.
import (
"context"
"errors"
"io"
"log"
"log/slog"
"net"
"os"
"os/signal"
"syscall"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/ssh"
"github.com/charmbracelet/wish"
"github.com/charmbracelet/wish/bubbletea"
"github.com/joho/godotenv"
)
const (
host = "0.0.0.0"
port = "6767"
)
func myLoggingMiddleware() wish.Middleware {
return func(next ssh.Handler) ssh.Handler {
return func(s ssh.Session) {
start := time.Now()
slog.Info("connect", "ip", s.RemoteAddr(), "user", s.User())
next(s)
slog.Info("disconnect", "ip", s.RemoteAddr(), "user", s.User(), "duration", time.Since(start))
}
}
}
func main() {
godotenv.Load()
// log to a file
logFile, _ := os.OpenFile("logs/server.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
multi := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(multi)
s, err := wish.NewServer(
wish.WithAddress(net.JoinHostPort(host, port)),
// Auto-generates host key at this path if missing
wish.WithHostKeyPath(".ssh/term_info_ed25519"),
wish.WithMiddleware(
bubbletea.Middleware(teaHandler),
myLoggingMiddleware(),
),
)
if err != nil {
log.Fatalf("could not create server: %v", err)
}
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
log.Printf("Starting SSH server on %s:%s", host, port)
go func() {
if err := s.ListenAndServe(); err != nil && !errors.Is(err, ssh.ErrServerClosed) {
log.Fatalf("server error: %v", err)
}
}()
<-done
log.Println("Shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(ctx); err != nil {
log.Fatalf("shutdown error: %v", err)
}
}
// teaHandler is called once per SSH session — return your model here.
func teaHandler(s ssh.Session) (tea.Model, []tea.ProgramOption) {
//pty, _, _ := s.Pty()
renderer := bubbletea.MakeRenderer(s)
m := NewModel(renderer)
return m, []tea.ProgramOption{tea.WithAltScreen()}
}