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

1 Answer 1

awk -F'[ ,:]' '/^[0-9a-zA-Z]/{sub(/\[/,"",$1); sub(/\]/,"",$1); print $1}' ~/.ssh/known_hosts
  • Used as ssh auto complete in my project bgrc for those who do not wish or cannot install bash-completion. Oct 14, 2015 at 19:26
  • Hmm, fails on IPv6 addresses, returning only the first octet.
    – thrig
    Oct 14, 2015 at 20:41
  • @thrig Can you confirm what it looks like in the known_hosts file and I take a look at it Oct 14, 2015 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, 2015 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. Oct 27, 2015 at 17:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .