sshtunnel/cmd/list.go
2025-05-23 15:08:44 +02:00

56 lines
1.1 KiB
Go

package cmd
import (
"fmt"
"os"
"strings"
"syscall"
"github.com/spf13/cobra"
)
var listCmd = &cobra.Command{
Use: "list",
Short: "List all active SSH tunnels",
Long: `Display all currently active SSH tunnels managed by this tool.`,
Run: func(cmd *cobra.Command, args []string) {
listTunnels()
},
}
func init() {
rootCmd.AddCommand(listCmd)
}
func listTunnels() {
tunnels, err := getTunnels()
if err != nil {
fmt.Printf("Error listing tunnels: %v\n", err)
os.Exit(1)
}
if len(tunnels) == 0 {
fmt.Println("No active SSH tunnels found.")
return
}
fmt.Println("Active SSH tunnels:")
fmt.Printf("%-5s %-15s %-20s %-10s\n", "ID", "LOCAL", "REMOTE", "PID")
fmt.Println(strings.Repeat("-", 60))
for _, t := range tunnels {
// Check if the process is still running
process, err := os.FindProcess(t.PID)
if err != nil || process.Signal(syscall.Signal(0)) != nil {
// Process does not exist anymore, clean up the tunnel file
removeFile(t.ID)
continue
}
fmt.Printf("%-5d %-15s %-20s %-10d\n",
t.ID,
fmt.Sprintf("localhost:%d", t.LocalPort),
fmt.Sprintf("%s:%d", t.RemoteHost, t.RemotePort),
t.PID)
}
}