Bash extract user for a particular host from ssh c

2019-06-28 04:09发布

I'm writing a bash script where I need to obtain a particular user from an ssh config file. The ssh config file looks a little something like this:

HOST blag
    HostName blag.net.au
    Port 2683
    User blaguser
Host bloo
  User ABCDEF
  IdentityFile ~/.ssh/id_rsa
HOST biff
    HostName biff.net.au
    Port 2683
    User biffuser

I want to obtain the string 'ABCDEF' and put it in a variable, by searching for Host bloo.

I was able to use the answer at https://superuser.com/questions/791374/get-variable-values-from-config-file/791387#791387?newreg=6626dd5535194d0180a91b6ace31e16f to read the config file but it assigns the array with the last host entry in the file.

I'm able to delete the host entry with this answer How can I remove a Host entry from an ssh config file?. The sed command here could be edited to extract the correct User but I'm not sure precisely how

I'm having a lot of trouble with it. Can anyone assist? An answer which uses sed would be preferable.

标签: bash ssh sed
2条回答
你好瞎i
2楼-- · 2019-06-28 04:34

As per 123's comment above:

var=$(awk '/^Host bloo$/{x=1}x&&/User/{print $2;exit}' ssh.conf)

That will assign value ABCDEF to var.

查看更多
一夜七次
3楼-- · 2019-06-28 04:46

You can use ssh configuration test mode to parse the configuration file and return you the expected value:

ssh -G hostname | grep "user "

This should work since openssh-6.8.

查看更多
登录 后发表回答