0

I want to create bash autocomplete for ssh. I have an a large network, with about 10 level 1 domains, each containts about 20 2 level domains, it can contains level 3 domains or network equipment.

All data stored in my DNS and I can transfer zone with dig, and parse output to ssh_config. For understandong I have records similar to this:

Host ZONE-A/City1-Name/RouterName
        Hostname AAA
Host ZONE-A/City2-Name/RouterName
        Hostname BBB
Host ZONE-B/City3/RouterName
        Hostname CCC
Host ZONE-B/City4/RouterName
        Hostname DDD
Host ZONE-C/City5/RouterName
        Hostname EEE
Host ZONE-C/City6/RouterName
        Hostname FFF
Host ZONE-C/City6/District1/RouterName
        Hostname GGG

I'm tryed to parse this and send to COMPREPLY only substring with this code:

_ssh()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts=$(grep '^Host' /etc/ssh/ssh_config | grep -v '[?*]' | cut -d ' ' -f 2-)
    COMPREPLY=( $(compgen -W "$opts" -- ${cur} \
        | awk -v poscount=$(echo $cur \
        | awk -F\/ '{print NF}') -F\/ '{print $poscount "/"}' | uniq)  )
    return 0
}
complete -F _ssh ssh

but when i trying to

ssh ZONE-A/City1 <TAB>

it changes to

ssh City1-Name

And autocomplete dont working.

If I'm trying to not substitute strings as here, and use

-o filenames

autocomplete shows only end devices names (RouterName)

Is there any way of doing this in bash?

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • Doesn't the completion for `ssh` in the Bash-completion package already do all that? See https://github.com/scop/bash-completion/blob/master/completions/ssh - parses all the conf files for known hosts. – Benjamin W. Jul 09 '18 at 22:49
  • no, it doesn't. Idea in that to create tree structure for access to hosts, because locations have a hard to remember names, and count of hosts is more that 2k. – Ivan Mastrenko Jul 10 '18 at 09:29
  • How do you want it work? `ssh ZONE-A/City1` becomes `ssh ZONE-A/City1-Name/RouterName`? –  Jul 16 '18 at 10:34
  • Yes. and if a multiple variants is avaliable - only this level help is shown: `ssh ZONE-A/City1Name/ ` shows help: `Router1Name Router2Name Router3Name` – Ivan Mastrenko Jul 17 '18 at 16:53

0 Answers0