Skip to content

Instantly share code, notes, and snippets.

@angely-dev
Last active October 10, 2022 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angely-dev/15a040dec4c6360c420e355efa362c80 to your computer and use it in GitHub Desktop.
Save angely-dev/15a040dec4c6360c420e355efa362c80 to your computer and use it in GitHub Desktop.
Autocomplete SSH, SCP, ping, ..., based on known hosts.
#!/usr/bin/env bash
get_ssh_known_hosts() {
known_hosts=$(cat ~/.ssh/known_hosts | cut -d' ' -f1)
starts_with=$2
COMPREPLY=( $(compgen -W "$known_hosts" -- "$starts_with") )
return 0
}
complete -F get_ssh_known_hosts ssh scp ping nslookup my-custom-command
@angely-dev
Copy link
Author

angely-dev commented Sep 28, 2022

How To

  1. Create the script in a specific location, e.g., ~/.local/bin
  2. Source it at the end of your ~/.bashrc file (or source it manually):
source ~/.local/bin/ssh-autocomplete
  1. Open a new terminal and check:
$ complete 
complete -F get_ssh_known_hosts ssh
complete -F get_ssh_known_hosts nslookup
complete -F get_ssh_known_hosts scp
complete -F get_ssh_known_hosts my-custom-command
complete -F get_ssh_known_hosts ping
  1. That's it! Enjoy the autocompletion.

Demo

I used a Docker container just to be in a minimal isolated environment but Docker is not needed for this to work!

demo

Dockerfile I used if needed:

FROM alpine

# We need both Bash and an SSH client
RUN apk add --no-cache \
    bash openssh-client

# Initial directories
RUN mkdir -p ~/.local/bin
RUN mkdir ~/.ssh

# Initial empty files
RUN touch ~/.local/bin/ssh-autocomplete
RUN touch ~/.ssh/known_hosts

To build it and run it:

$ docker build -t just-bash-ssh .
$ docker run -it --rm just-bash-ssh bash

Note

This is based on ~/.ssh/known_hosts file. This requires known hosts hashing to be disabled in ~/.ssh/config file (by default in most cases):

# Disable known hosts hashing,
# so that we can read them for autocompletion
Host *
  HashKnownHosts=no

See: https://security.stackexchange.com/questions/56268/ssh-benefits-of-using-hashed-known-hosts

@angely-dev
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment