i am trying to make bash script who read .ssh/config file and connect to hosts who only uses IdentityFile or ssh key, and run commands on remote servers. So problem is that config file contain hosts who don't use IdentityFile and connect via passwords. How to grep explicitly Host and IdentityFile blocks in file and discard others? I've make already script that connect to all hosts in file with for loop, but that is not what i want 100 %. Thank you. My .ssh/config file looks like this:

Host centos7-mp1
        user root
        IdentityFile /root/.ssh/keys/id_rsa_passwordless

Host centos6-mp2
        user root
        IdentityFile /root/.ssh/keys/id_rsa_passwordless

Host centosvm-test
        user test

awk in paragraph mode is useful for this case - where you have multiline records that are separated by one or more blank lines e.g. to print the value of the Host key (second field) of records matching IdentityFile you can do

awk '/IdentityFile/ {print $2}' RS= .ssh/config

If you need to match IdentityFile case-insensitively, you can modify that to

awk 'toupper($0) ~ /IDENTITYFILE/ {print $2}' RS= .ssh/config

or (with GNU awk)

gawk '/IdentityFile/ {print $2}' RS= IGNORECASE=1 .ssh/config
  • Thank you man!! That is about everything i need from here, but i got other questions. When config file got no empty lines between two blocks of host files, script exits, how to bypass this? – Igor Mijatovic Mar 24 '17 at 12:21

Grep specific string inside a file. For grep:

$ grep -i 'string' ~/path/to/config/file/

If this is exactly what you want..

  • Thank you for response. I want output to contain only this, in this particularly file it would be Host centos7-mp1 IdentityFile /root/.ssh/keys/id_rsa_passwordless and Host centos6-mp2 IdentityFile /root/.ssh/keys/id_rsa_passwordless, without Host centosvm-test and strings below that, because that file don't contain IdentityFile. – Igor Mijatovic Mar 24 '17 at 11:45

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.