Skip to content

Instantly share code, notes, and snippets.

@yolabingo
Last active November 4, 2022 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yolabingo/7bc825d8ecfb455a56a2773ade5e8858 to your computer and use it in GitHub Desktop.
Save yolabingo/7bc825d8ecfb455a56a2773ade5e8858 to your computer and use it in GitHub Desktop.
strongDM bash completion of hostnames for "sdm ssh [hostname]"
#/usr/bin/env bash
# fetch server hostnames from `sdm status` to use as completions for `sdm ssh [hostname]`
# save the sdm status to a local file from a cron job to speed this up a lot:
# sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' | sort -u > /var/tmp/sdm-status
# h/t https://iridakos.com/programming/2018/03/01/bash-programmable-completion-tutorial
update_frequency=4h
compwords_file=/var/tmp/sdm-status
_sdm_ssh_completions()
{
if [ "${#COMP_WORDS[@]}" != "3" ]; then
return
fi
# is this "sdm ssh" ?
if [ "${3}" != "ssh" ]; then
return
fi
# keep the suggestions in a local variable
# local suggestions=($(compgen -W "$(sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}')" -- "${COMP_WORDS[2]}"))
# occasionally save "sdm status" output to a file for much faster completions
if [ ! -s "$compwords_file" ]; then
sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' > $compwords_file
elif ! test "$( find $compwords_file -ctime -${update_frequency} 2>/dev/null )"; then
# echo "Updating compwords"
sdm status --filter 'TYPE:ssh*' | tail -n +2 | awk '{print $1}' > $compwords_file
fi
local suggestions=($(compgen -W "$(cat /var/tmp/sdm-status)" -- "${COMP_WORDS[2]}"))
if [ "${#suggestions[@]}" == "1" ]; then
# if there's only one match, we remove the command literal
# to proceed with the automatic completion of the number
local number=$(echo ${suggestions[0]/%\ */})
COMPREPLY=("$number")
else
# more than one suggestions resolved,
# respond with the suggestions intact
for i in "${!suggestions[@]}"; do
suggestions[$i]="$(printf '%*s' "-$COLUMNS" "${suggestions[$i]}")"
done
COMPREPLY=("${suggestions[@]}")
fi
}
complete -F _sdm_ssh_completions sdm
@yolabingo
Copy link
Author

use "sdm status" not "sdm admin list"

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