9

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.

Community
  • 1
  • 1
James Jones
  • 3,850
  • 5
  • 25
  • 44
  • 2
    `var=$(awk '/^Host bloo$/{x=1}x&&/User/{print $2;exit}' ssh.conf)` – 123 Jul 11 '16 at 10:12
  • @123 Noice. Works perfect, if you add this as an answer I'll accept it. – James Jones Jul 11 '16 at 10:37
  • Note that `openssh` config is not case sensitive, which might get you fooled. Using `ssh` itself will shield you from these details. Check my answer below. – Jakuje Jul 11 '16 at 11:01

3 Answers3

10

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.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Jakuje
  • 24,773
  • 12
  • 69
  • 75
  • I have version 6.6.1 sadly. – James Jones Jul 11 '16 at 11:44
  • 1
    2 years later, found my own question again but this time running OpenSSH 7.4 so this answer is better. Just be careful about checking for a hostname that doesn't exist in the config. It'll return whatever user you run the command as. That's pretty easy to check for but you might be expecting nothing. – James Jones Nov 08 '18 at 14:45
  • If you have a `Host *` with a `User` set it will always be that one no matter what. – Nate-Wilkins Dec 20 '22 at 02:03
4

Adding to @Jakuje's correct answer. This one will return only the username

$ ssh -G hostname | grep -m1 -oP "(?<=user ).*"
ubuntu

where grep parameters mean

-m1 - stop reading after first matches

-o - print only the matching part of the line

-P - use Perl compatible positive look behind regex

Levon
  • 10,408
  • 4
  • 47
  • 42
  • 2
    Not really of concern here, but I guess this regex will be quite slow. You can make it a lot easier with cut: `ssh -G hostname | grep "^user " | head -1 | cut -d " " -f2-` – xeruf Dec 10 '21 at 21:39
3

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.

James Jones
  • 3,850
  • 5
  • 25
  • 44