I would like to extract hostnames/ips from .ssh/known_hosts file in all (known) format conditions:

  • Hostname only hostname pubkey
  • Hostname with ip: hostname, pubkey
  • Hostname with ip that is not reverse and custom port: [hostname]:1234,[]:1234 pubkey
  • Safely ignore hashed hosts, if any
awk -F'[ ,:]' '/^[0-9a-zA-Z]/{sub(/\[/,"",$1); sub(/\]/,"",$1); print $1}' ~/.ssh/known_hosts
| improve this answer | |
  • Used as ssh auto complete in my project bgrc for those who do not wish or cannot install bash-completion. – Benjamin Goodacre Oct 14 '15 at 19:26
  • Hmm, fails on IPv6 addresses, returning only the first octet. – thrig Oct 14 '15 at 20:41
  • @thrig Can you confirm what it looks like in the known_hosts file and I take a look at it – Benjamin Goodacre Oct 14 '15 at 21:58
  • 2001:db8::1 ssh-rsa ... or with ports [2001:db8::1]:1234, possibly as CSV with hostnames or IPv4 equiv. – thrig Oct 14 '15 at 22:41
  • If only complete ipv6 addresses are matched this is relatively easy, the regex in the Net::IPv6Addr perl module can be used. To match incomplete ipv6 everything between the (square) brackets can be captured: [[ $i =~ ^[\[]([^,]+)[\]]. I will work to incorporate the logic into the above awk and then remove the colon from the field delimiters. – Benjamin Goodacre Oct 27 '15 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.