├── .gitignore ├── examples ├── Capture1.PNG └── config ├── go.mod ├── tools ├── ssh_windows.go └── ssh_unix.go ├── LICENSE ├── .github └── workflows │ └── build.yml ├── README.md ├── main.go ├── go.sum └── tui └── prompter.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .vscode/ 3 | .ssh/ -------------------------------------------------------------------------------- /examples/Capture1.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/azlux/ssh-prompter/HEAD/examples/Capture1.PNG -------------------------------------------------------------------------------- /examples/config: -------------------------------------------------------------------------------- 1 | Host ServerA1 2 | Hostname 1.2.3.4 3 | Folder FolderA 4 | 5 | Host ServerA1 6 | Hostname 1.2.3.5 7 | Folder FolderA 8 | 9 | Host FolderB/ServerB1 10 | Hostname 1.2.3.6 11 | 12 | Host FolderB/ServerB2 13 | Hostname 1.2.3.6 14 | 15 | Host NotGroupedServer1 16 | Hostname 1.2.3.7 17 | User whynot 18 | 19 | Host NotGroupedServer2 20 | Hostname 1.2.3.8 21 | User whynotv2 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/azlux/ssh-prompter 2 | 3 | go 1.24.0 4 | 5 | require ( 6 | github.com/gdamore/tcell/v2 v2.13.2 7 | github.com/phsym/console-slog v0.3.1 8 | github.com/rivo/tview v0.42.0 9 | github.com/spf13/pflag v1.0.10 10 | golang.org/x/sys v0.39.0 11 | ) 12 | 13 | require ( 14 | github.com/gdamore/encoding v1.0.1 // indirect 15 | github.com/lucasb-eyer/go-colorful v1.3.0 // indirect 16 | github.com/rivo/uniseg v0.4.7 // indirect 17 | golang.org/x/term v0.37.0 // indirect 18 | golang.org/x/text v0.31.0 // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /tools/ssh_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | // +build windows 3 | 4 | package tools 5 | 6 | import ( 7 | "fmt" 8 | "log/slog" 9 | "os" 10 | ) 11 | 12 | func LaunchSSHArgs(args []string, logger *slog.Logger) { 13 | fmt.Println("Run on Windows, execlp unavailable, Do nothing !") 14 | fmt.Println("Command run: ssh", args) 15 | os.Exit(0) 16 | } 17 | 18 | func LaunchSSH(selected_host string, logger *slog.Logger) { 19 | fmt.Println("Run on Windows, execlp unavailable, Do nothing !") 20 | fmt.Println("Selected host is", selected_host) 21 | os.Exit(0) 22 | } 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Azlux 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build Go Binaries 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" # Trigger on version tags 7 | 8 | jobs: 9 | build: 10 | name: Build cross-platform Go program 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v5 16 | 17 | - name: Set up Go 18 | uses: actions/setup-go@v6 19 | with: 20 | go-version: "stable" 21 | 22 | - name: Build binary 23 | run: | 24 | PLATFORMS=(darwin/amd64 darwin/arm64 freebsd/386 freebsd/amd64 freebsd/arm freebsd/arm64 linux/386 linux/amd64 linux/arm linux/arm64) 25 | mkdir -p build 26 | EXT="" 27 | for p in "${PLATFORMS[@]}"; do 28 | export GOOS=$(echo $p | cut -d "/" -f 1) 29 | export GOARCH=$(echo $p | cut -d "/" -f 2) 30 | echo "Building for ${GOOS}/${GOARCH}" 31 | if [ "${GOOS}" = "windows" ]; then EXT=".exe"; fi 32 | go build -o build/ssh-prompter-${GOOS}-${GOARCH}${EXT} 33 | done 34 | ls -alih build/ 35 | 36 | - name: Publish Forgejo Release 37 | uses: actions/forgejo-release@v2.7.3 38 | with: 39 | direction: upload 40 | url: http://forgejo:3000 41 | repo: azlux/ssh-prompter 42 | title: "ssh-prompter ${{ github.ref_name }}" 43 | release-dir: "build" # All files of this folder are added to the release file 44 | release-notes: "Automated release for ${{ github.ref_name }}" 45 | -------------------------------------------------------------------------------- /tools/ssh_unix.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package tools 5 | 6 | import ( 7 | "log/slog" 8 | "os" 9 | "os/exec" 10 | "strconv" 11 | "strings" 12 | 13 | "golang.org/x/sys/unix" 14 | ) 15 | 16 | func changeTMUXName(name string, logger *slog.Logger) int { 17 | // Manage TMUX 18 | _, haveTmux := os.LookupEnv("TMUX") 19 | if haveTmux { 20 | logger.Debug("TMUX detected, trigger the rename") 21 | exec.Command("tmux", "rename-window", name).Run() 22 | res, _ := exec.Command("tmux", "display-message", "-p", "-F", "#{window_index}").Output() 23 | res_string := strings.TrimSpace(string(res)) 24 | res_int, _ := strconv.Atoi(res_string) 25 | logger.Debug("TMUX windows n°" + res_string + " found") 26 | return res_int 27 | } 28 | return -1 29 | } 30 | 31 | func LaunchSSHArgs(args []string, logger *slog.Logger) { 32 | binary, err1 := exec.LookPath("ssh") 33 | if err1 != nil { 34 | logger.Error("Searching SSH executable failed ", "err", err1) 35 | } 36 | 37 | argv := append([]string{"ssh"}, args...) 38 | 39 | err2 := unix.Exec(binary, argv, os.Environ()) 40 | if err2 != nil { 41 | logger.Error("Error during executing ssh command", "err", err2) 42 | os.Exit(1) 43 | } 44 | 45 | } 46 | func LaunchSSH(selected_host string, logger *slog.Logger) { 47 | 48 | TMUXWindow := changeTMUXName(selected_host, logger) 49 | 50 | // args to pass to the ssh executable bin 51 | var args = make([]string, 0) 52 | var binaryToRun string 53 | 54 | if TMUXWindow >= 0 { 55 | 56 | args = []string{"bash", "-c", "trap 'tmux set-option -w -t " + strconv.Itoa(TMUXWindow) + " automatic-rename on' EXIT SIGHUP SIGTERM; ssh -oStrictHostKeyChecking=accept-new " + selected_host} 57 | binary, err := exec.LookPath("bash") 58 | if err != nil { 59 | logger.Error("Error searching 'bash'", "err", err) 60 | return 61 | } 62 | binaryToRun = binary 63 | } else { 64 | args = []string{"ssh", "-oStrictHostKeyChecking=accept-new", selected_host} 65 | binary, err := exec.LookPath("ssh") 66 | if err != nil { 67 | logger.Error("Error searching 'ssh'", "err", err) 68 | return 69 | } 70 | binaryToRun = binary 71 | } 72 | 73 | logger.Debug("Command to run: " + strings.Join(args, " ")) 74 | 75 | env := os.Environ() 76 | err := unix.Exec(binaryToRun, args, env) 77 | if err != nil { 78 | logger.Error("Erreur lors de l'exécution de 'ssh'", "err", err) 79 | os.Exit(0) 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🔐 ssh-prompter 2 | 3 | The source of this project is https://git.azlux.fr/azlux/ssh-prompter, **PR are accepted on the source only**. 4 | 5 | This standalone **TUI** relies entirely on your SSH configuration file, without any database. It's a Go rewrite of my previous Python 3 script. 6 | 7 | ### ✨ Features 8 | 9 | - ✅ Lists all servers from your `~/.ssh/config` 10 | - 🔍 Instant search to quickly find hosts 11 | - 📂 Folder grouping for better organization 12 | - 🔗 Supports `Include` directives in [ssh_config](https://man.openbsd.org/ssh_config#Include) 13 | - ⚡ Fast and lightweight TUI interface (made with Go) 14 | - 🔌 Connect to the selected host 15 | 16 | ### 📸 Screenshot 17 | ![ssh-prompter](examples/Capture1.PNG) 18 | 19 | ## ⚙️ Installation 20 | ### Via APT (recommended) 21 | See [http://packages.azlux.fr](http://packages.azlux.fr) 22 | 23 | ```bash 24 | echo "deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] http://packages.azlux.fr/debian/ trixie main" | sudo tee /etc/apt/sources.list.d/azlux.list 25 | sudo wget -O /usr/share/keyrings/azlux-archive-keyring.gpg https://azlux.fr/repo.gpg 26 | sudo apt update 27 | sudo apt install ssh-prompter 28 | ``` 29 | 30 | ### Manually 31 | You need to install the [Go Language](https://go.dev/doc/install) 32 | 33 | Then you can build the project 34 | ```bash 35 | git clone https://git.azlux.fr/azlux/ssh-prompter.git 36 | cd ssh-prompter 37 | go build 38 | ``` 39 | 40 | ## 🛠 Configuration 41 | ### Alias 42 | Many people don't like the long command `ssh-prompter` so I recommand to put an alias into your `~/.profile` or `~/.bashrc`. 43 | It's safe to replace the `ssh` command since I don't interfere with ssh if additionnals parameters are used. 44 | ```bash 45 | # alias ssh="ssh-prompter" 46 | # or 47 | # alias sshp="ssh-prompter" 48 | ``` 49 | 50 | ### Usage 51 | Simply run : 52 | ```bash 53 | ssh 54 | ``` 55 | .... and enjoy the fast interactive prompt (⚡) then press Enter to connect to the selected host (🚀)! 56 | 57 | ### SSH config configuration 58 | Everything is here : [Official ssh_config manual](https://man.openbsd.org/ssh_config) 59 | I don't have a custom config file, neither a database. 60 | 61 | This program parse the standard ssh config file. See [the example](examples/config) for a basic config for ssh 62 | 63 | ### Folder 64 | SSH-Prompter manage folder. 65 | Host will be group by `Folder` when no search. 66 | 67 | Two methods: 68 | - The Host name can be `FolderName/Name`, 69 | - You can add the ssh config option `Folder FolderName`. 70 | - In this case you need `IgnoreUnknown Folder`on the TOP of your `.ssh/config` file (to avoid error). 71 | 72 | You can use both (but not in the same time for the same Host) ! 73 | 74 | ### Additionnal information 75 | All Host with `*` are ignored. 76 | 77 | I consider we don't want to "select" them since it's a wildcard for other hosts 78 | 79 | ### Why two methods for folder : 80 | I first wanted to have the `/` (slash) method but when you use ProxyJump, ssh don't allow slash into the name. 81 | So the option `Folder` is here to allow having a proxy server into a folder. 82 | 83 | ### TMUX 84 | If you run the script on a tmux. 85 | The window will be renamed with the Host selected. 86 | 87 | It use the command `tmux rename-window xxxxx` 88 | 89 | ## 📜 License 90 | MIT License - see [LICENSE](LICENSE) for details. 91 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "strings" 7 | 8 | "log/slog" 9 | 10 | "github.com/azlux/ssh-prompter/tools" 11 | "github.com/azlux/ssh-prompter/tui" 12 | "github.com/phsym/console-slog" 13 | flag "github.com/spf13/pflag" 14 | ) 15 | 16 | var logger *slog.Logger 17 | 18 | func initLog(level slog.Level) { 19 | logger = slog.New(console.NewHandler(os.Stderr, &console.HandlerOptions{Level: level})) 20 | } 21 | 22 | func LaunchSSHItemHost(hostItem tui.HostItem) { 23 | if hostItem.Folder != "" && hostItem.FolderInName { 24 | tools.LaunchSSH(hostItem.Folder+"/"+hostItem.Host, logger) 25 | } else { 26 | tools.LaunchSSH(hostItem.Host, logger) 27 | } 28 | } 29 | 30 | func main() { 31 | var addr_debug *bool = flag.Bool("debug-prompter", false, "Some debug log for ssh-prompter") 32 | flag.CommandLine.ParseErrorsWhitelist.UnknownFlags = true 33 | flag.Parse() 34 | args := flag.Args() 35 | 36 | // Log 37 | if *addr_debug { 38 | initLog(slog.LevelDebug) 39 | logger.Debug("Debug log enabled") 40 | } else { 41 | initLog(slog.LevelInfo) 42 | } 43 | 44 | // Part to check if use of specific ssh args 45 | // This action will bypass the prompter 46 | 47 | // Build a set of known flags 48 | knownFlags := make(map[string]bool) 49 | flag.CommandLine.VisitAll(func(f *flag.Flag) { 50 | knownFlags["--"+f.Name] = true 51 | }) 52 | 53 | // Parse all args starting with - 54 | // Compare with knowFlags 55 | hasUnknown := false 56 | for _, arg := range os.Args[1:] { 57 | if strings.HasPrefix(arg, "-") { 58 | flagName := arg 59 | if !knownFlags[flagName] { 60 | hasUnknown = true 61 | } 62 | } 63 | } 64 | 65 | var searchText string = "" 66 | var searchResultCounter int = 0 67 | var searchFoundExactHost bool = false 68 | var searchResultHost tui.HostItem 69 | if len(args) == 1 { 70 | searchText = args[0] 71 | } 72 | if len(args) > 1 || hasUnknown { 73 | tools.LaunchSSHArgs(os.Args[1:], logger) 74 | } 75 | 76 | // Starting here 77 | path, _ := os.UserHomeDir() 78 | allItems, ok := tui.ParseSSHConfig(filepath.Join(path, "/.ssh/config"), logger) 79 | if !ok { 80 | logger.Error("No " + path + "/.ssh/config file found") 81 | os.Exit(1) 82 | } 83 | 84 | if searchText != "" { // Searching only if the user have request a host 85 | for i := range allItems { 86 | if strings.Contains(strings.ToLower(allItems[i].Host), strings.ToLower(searchText)) { 87 | searchResultHost = allItems[i] 88 | searchResultCounter += 1 89 | if strings.EqualFold(allItems[i].Host, searchText) { 90 | searchFoundExactHost = true 91 | break 92 | } 93 | } 94 | } 95 | } 96 | 97 | if searchResultCounter == 0 && searchText != "" { 98 | //Launch standard SSH if nothing exist into the config file 99 | logger.Debug("No result during search, back to standars SSH") 100 | tools.LaunchSSH(searchText, logger) 101 | } else if searchFoundExactHost { 102 | logger.Debug("Found direct Host, running SSH without TUI") 103 | LaunchSSHItemHost(searchResultHost) 104 | } else { 105 | // Launch the TUI prompt 106 | selected_host, ok := tui.StartPrompter(searchText, allItems) 107 | if ok { 108 | logger.Debug("SSH requested for " + selected_host.Host) 109 | LaunchSSHItemHost(selected_host) 110 | } else { 111 | logger.Debug("Exiting requested") 112 | } 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= 2 | github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= 3 | github.com/gdamore/tcell/v2 v2.13.2 h1:5j4srfF8ow3HICOv/61/sOhQtA25qxEB2XR3Q/Bhx2g= 4 | github.com/gdamore/tcell/v2 v2.13.2/go.mod h1:+Wfe208WDdB7INEtCsNrAN6O2m+wsTPk1RAovjaILlo= 5 | github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= 6 | github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 7 | github.com/phsym/console-slog v0.3.1 h1:Fuzcrjr40xTc004S9Kni8XfNsk+qrptQmyR+wZw9/7A= 8 | github.com/phsym/console-slog v0.3.1/go.mod h1:oJskjp/X6e6c0mGpfP8ELkfKUsrkDifYRAqJQgmdDS0= 9 | github.com/rivo/tview v0.42.0 h1:b/ftp+RxtDsHSaynXTbJb+/n/BxDEi+W3UfF5jILK6c= 10 | github.com/rivo/tview v0.42.0/go.mod h1:cSfIYfhpSGCjp3r/ECJb+GKS7cGJnqV8vfjQPwoXyfY= 11 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 12 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 13 | github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= 14 | github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 15 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 16 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 17 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 18 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 19 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 20 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 21 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 22 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 23 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 24 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 25 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 26 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 27 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 28 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 29 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 30 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 31 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 32 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 33 | golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= 34 | golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 35 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 36 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 37 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 38 | golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= 39 | golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= 40 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 41 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 42 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 43 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 44 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 45 | golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= 46 | golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= 47 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 48 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 49 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 50 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 51 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 52 | -------------------------------------------------------------------------------- /tui/prompter.go: -------------------------------------------------------------------------------- 1 | // Package tui implement the terminal TUI with tcell and tview 2 | package tui 3 | 4 | import ( 5 | "bufio" 6 | "fmt" 7 | "log/slog" 8 | "os" 9 | "path/filepath" 10 | "strings" 11 | 12 | "github.com/gdamore/tcell/v2" 13 | "github.com/rivo/tview" 14 | ) 15 | 16 | type HostItem struct { 17 | Host string 18 | Hostname string 19 | Folder string 20 | FolderInName bool // set true if use a simple "/" instead of the config option Folder 21 | } 22 | 23 | var prefixFolder string = " 🗁 " 24 | 25 | func emptyHostItem() HostItem { 26 | return HostItem{Host: "", Hostname: "", Folder: "", FolderInName: false} 27 | } 28 | 29 | func ParseSSHConfig(path string, logger *slog.Logger) ([]HostItem, bool) { 30 | file, err := os.Open(path) 31 | if err != nil { 32 | fmt.Println(err) 33 | return nil, false 34 | } 35 | defer file.Close() 36 | 37 | allHost := make([]HostItem, 0) 38 | var tpHost, tpHostname, tpFolder string 39 | var tpFolderInName = false 40 | 41 | scanner := bufio.NewScanner(file) 42 | for scanner.Scan() { 43 | line := strings.TrimSpace(scanner.Text()) 44 | 45 | if line == "" || strings.HasPrefix(line, "#") { 46 | continue 47 | } 48 | 49 | lineFields := strings.Fields(line) 50 | if len(lineFields) < 2 { 51 | continue 52 | } 53 | // loop if include found into config 54 | if strings.ToLower(lineFields[0]) == "include" { 55 | pathsToInclude := lineFields[1:] 56 | 57 | for _, onePath := range pathsToInclude { 58 | if !strings.HasPrefix(onePath, "/") && !strings.HasPrefix(onePath, "~") { 59 | home, _ := os.UserHomeDir() 60 | onePath = filepath.Join(home, ".ssh", onePath) 61 | } else if strings.HasPrefix(onePath, "~") { 62 | home, _ := os.UserHomeDir() 63 | onePath = strings.Replace(onePath, "~", home, 1) 64 | } 65 | if strings.HasSuffix(onePath, "*") { 66 | matches, err := filepath.Glob(onePath) 67 | 68 | if err != nil { 69 | logger.Warn("Erreur glob", "pattern", onePath, "error", err) 70 | continue 71 | } 72 | 73 | for _, match := range matches { 74 | logger.Debug("Including file from dir", "file", match) 75 | newHosts, _ := ParseSSHConfig(match, logger) // récursion 76 | allHost = append(allHost, newHosts...) 77 | } 78 | } else { 79 | logger.Debug("Including file", "file", onePath) 80 | newhosts, _ := ParseSSHConfig(onePath, logger) 81 | allHost = append(allHost, newhosts...) 82 | } 83 | } 84 | } else if strings.ToLower(lineFields[0]) == "host" && !strings.Contains(lineFields[1], "*") { 85 | if tpHost != "" { // If exist, I already found the full config of previous one 86 | allHost = append(allHost, HostItem{Host: tpHost, Hostname: tpHostname, Folder: tpFolder, FolderInName: tpFolderInName}) 87 | // reset for new Host config 88 | tpHost = "" 89 | tpHostname = "" 90 | tpFolder = "" 91 | tpFolderInName = false 92 | } 93 | tpHost = lineFields[1] 94 | if strings.Contains(tpHost, "/") { 95 | tmpSplit := strings.SplitN(tpHost, "/", 2) 96 | tpFolder = tmpSplit[0] 97 | tpHost = tmpSplit[1] 98 | tpFolderInName = true 99 | } 100 | } else if tpHost != "" && strings.ToLower(lineFields[0]) == "hostname" { // Host need to be found first into ssh config 101 | tpHostname = lineFields[1] 102 | } else if tpHost != "" && strings.ToLower(lineFields[0]) == "folder" { // Explicit entry Folder 103 | tpFolder = lineFields[1] 104 | tpFolderInName = false 105 | } 106 | } 107 | 108 | if tpHost != "" { // If exist, I save also the last one 109 | allHost = append(allHost, HostItem{Host: tpHost, Hostname: tpHostname, Folder: tpFolder, FolderInName: tpFolderInName}) 110 | } 111 | 112 | return allHost, true 113 | } 114 | 115 | func StartPrompter(search string, allItems []HostItem) (HostItem, bool) { 116 | app := tview.NewApplication() 117 | ok := true 118 | widthList := 0 119 | 120 | // List to show 121 | list := tview.NewList().ShowSecondaryText(false) 122 | list.SetBorder(true).SetTitle(" Server List ").SetTitleAlign(tview.AlignCenter) 123 | 124 | // Status bar 125 | statusBar := tview.NewTextView().SetTextAlign(tview.AlignCenter).SetDynamicColors(true) 126 | 127 | // Function to update the list according to the filter 128 | updateList := func(filter string) { 129 | list.Clear() 130 | count := 0 131 | _, _, widthList, _ = list.GetInnerRect() 132 | allFolders := make([]string, 0) 133 | 134 | for i := range allItems { 135 | hostToPrint := "" 136 | if allItems[i].Folder != "" { //Manage a list of folder 137 | hostToPrint = allItems[i].Folder + "/" + allItems[i].Host 138 | } else { 139 | hostToPrint = allItems[i].Host 140 | } 141 | if filter == "" { // No Search requested 142 | if allItems[i].Folder != "" { //Manage a list of folder 143 | alreadyExist := false 144 | for j := range allFolders { 145 | if allFolders[j] == allItems[i].Folder { 146 | alreadyExist = true 147 | } 148 | } 149 | if !alreadyExist { // List of uniq folder 150 | allFolders = append(allFolders, allItems[i].Folder) 151 | } 152 | } else { 153 | count++ 154 | nbSpace := max(widthList-len(hostToPrint)-len(allItems[i].Hostname)-2, 2) 155 | list.AddItem(fmt.Sprintf(" %s%s%s ", hostToPrint, strings.Repeat(" ", nbSpace), allItems[i].Hostname), "", 0, nil) 156 | } 157 | 158 | } else { 159 | 160 | if strings.Contains(strings.ToLower(hostToPrint), strings.ToLower(filter)) { // Search is requested 161 | count++ 162 | nbSpace := max(widthList-len(hostToPrint)-len(allItems[i].Hostname)-2, 2) 163 | list.AddItem(fmt.Sprintf(" %s%s%s ", hostToPrint, strings.Repeat(" ", nbSpace), allItems[i].Hostname), "", 0, nil) 164 | } 165 | } 166 | } 167 | for i := len(allFolders) - 1; i >= 0; i-- { // Loop to print all folder on top 168 | count++ 169 | list.InsertItem(0, fmt.Sprintf("%s%s", prefixFolder, allFolders[i]), "", 0, nil) 170 | } 171 | statusBar.SetText(fmt.Sprintf("[gray]%d entries, quit: CTRL+C", count)) 172 | } 173 | 174 | scrollBar := tview.NewTextView() 175 | scrollBar.SetDynamicColors(true). 176 | SetTextAlign(tview.AlignLeft). 177 | SetBorder(false) 178 | 179 | updateScrollBar := func() { 180 | index := list.GetCurrentItem() 181 | total := list.GetItemCount() - 1 182 | 183 | if total == 0 { //Avoid divide by 0 184 | scrollBar.SetText("") 185 | return 186 | } 187 | _, _, _, height := list.GetInnerRect() 188 | height-- // last line doesn't count 189 | 190 | pos := int(float64(index) / float64(total) * float64(height)) 191 | paddingTop := 2 192 | bar := strings.Repeat("\n", paddingTop) 193 | for i := 0; i <= height; i++ { 194 | if i == pos { 195 | bar += "[green]█\n" 196 | } else { 197 | bar += "[gray]│\n" 198 | } 199 | } 200 | scrollBar.SetText(bar) 201 | } 202 | 203 | // Search Input Field 204 | input := tview.NewInputField(). 205 | SetLabel("Search: "). 206 | SetFieldWidth(20). 207 | SetChangedFunc(func(text string) { 208 | updateList(text) 209 | updateScrollBar() 210 | }) 211 | 212 | // Moving into the list refresh the scrollbar 213 | list.SetChangedFunc(func(index int, mainText string, secondaryText string, shortcut rune) { updateScrollBar() }) // fake function to match the expected one 214 | 215 | // Action is something is selected 216 | list.SetSelectedFunc(func(index int, mainText string, secondaryText string, shortcut rune) { 217 | if strings.HasPrefix(mainText, prefixFolder) { 218 | // Get folder name 219 | dir := strings.TrimPrefix(mainText, prefixFolder) 220 | input.SetText(dir + "/") 221 | updateList(dir + "/") 222 | updateScrollBar() 223 | } else { 224 | app.Stop() 225 | } 226 | }) 227 | 228 | // Vertical layout 229 | mainLayout := tview.NewFlex().SetDirection(tview.FlexRow). 230 | AddItem(input, 1, 0, true). 231 | AddItem(list, 0, 1, false). 232 | AddItem(statusBar, 1, 0, false) 233 | 234 | // Horizontal center 235 | root := tview.NewFlex(). 236 | AddItem(nil, 0, 1, false). 237 | AddItem(mainLayout, 0, 3, true). // List is half of the screen 238 | AddItem(scrollBar, 1, 1, false). 239 | AddItem(nil, 0, 1, false) 240 | 241 | app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { 242 | switch event.Key() { 243 | case tcell.KeyUp, tcell.KeyDown, tcell.KeyPgUp, tcell.KeyPgDn: 244 | app.SetFocus(list) 245 | case tcell.KeyEnter: 246 | app.SetFocus(list) 247 | case tcell.KeyCtrlC: 248 | ok = false 249 | app.Stop() 250 | default: 251 | app.SetFocus(input) 252 | } 253 | return event 254 | }) 255 | 256 | app.SetBeforeDrawFunc(func(screen tcell.Screen) bool { 257 | newWidth, _ := screen.Size() 258 | if newWidth != widthList { 259 | widthList = newWidth 260 | if newWidth < 100 { 261 | // If the screen is too small 262 | // Removing the empty items to have the list fullscreen 263 | root.RemoveItem(nil) 264 | } 265 | } 266 | // If need of full screen background color override 267 | // screen.Clear() 268 | // screen.Fill(' ', tcell.StyleDefault.Background(tcell.ColorBlack)) 269 | 270 | return false 271 | }) 272 | 273 | app.SetAfterDrawFunc(func(screen tcell.Screen) { // Get size AFTER the first rendering to get the good width. 274 | updateList("") // Update the list 275 | input.SetText(search) 276 | updateScrollBar() 277 | app.SetAfterDrawFunc(nil) // Delete the hook after first run 278 | }) 279 | 280 | if err := app.SetRoot(root, true).EnableMouse(false).Run(); err != nil { 281 | panic(err) 282 | } 283 | if !ok { 284 | return emptyHostItem(), ok 285 | } 286 | 287 | currentLine, _ := list.GetItemText(list.GetCurrentItem()) // Get the brut selected line text 288 | currentLineHost := strings.Split(strings.TrimLeft(currentLine, " "), " ")[0] // remove the spaces and the hostname/IP at the end 289 | 290 | // Get the real HostItem behind the selection 291 | for i := range allItems { 292 | hostWithFolder := "" 293 | if allItems[i].Folder != "" { //Manage a list of folder 294 | hostWithFolder = allItems[i].Folder + "/" + allItems[i].Host 295 | } else { 296 | hostWithFolder = allItems[i].Host 297 | } 298 | if hostWithFolder == currentLineHost { 299 | // Return the Host 300 | return allItems[i], ok 301 | } 302 | } 303 | return emptyHostItem(), false 304 | } 305 | --------------------------------------------------------------------------------