2

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
        Hostname 192.168.89.102
        user root
        IdentityFile /root/.ssh/keys/id_rsa_passwordless


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

Host centosvm-test
        Hostname 192.168.56.233
        user test

2 Answers 2

2

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
1
  • 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? Mar 24, 2017 at 12:21
0

Grep specific string inside a file. For grep:

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

If this is exactly what you want..

1
  • 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. Mar 24, 2017 at 11:45

You must log in to answer this question.

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