2

I am developing a simple wrapper script for SSH to do some preprocessing before actually executing SSH (to be exact: load the per-host key with keychain/ssh-agent).

In order to do so, I need to extract the host name from the command line arguments. The wrapper shall support all options accepted by SSH — so my first, simple approch using the last command line parameter does not work if the user intends to run a command non-interactively on the remote side.

Does anybody see a simple shell-only way to get the hostname reliably?

Thanks in advance!

4
  • As a first pass, I would use getopt to loop through the ssh arguments. The first non-option parameter should be either hostname or user@hostname (where hostname is a name, an IP address, or an alias from the ssh configuration file[s]). Commented Jul 9, 2017 at 12:45
  • $(hostname) ? Commented Jul 9, 2017 at 12:46
  • 1
    @user4556274: I thought about this too, but wouldn't I then need to skip arguments to the options (such as for -o)? This would actually mean to name all SSH option in the script, right? Commented Jul 9, 2017 at 16:31
  • @DavidPostill: I'm looking for specifierd remote hostname, not the local one... Commented Jul 9, 2017 at 16:31

1 Answer 1

2

Just use ssh -G:

ssh -G -nNT -L10000:localhost:10000 admin@yo|awk '/^hostname/ {print $2}' 

Will print yo. It will fully resolve to the real hostname if you have a match in your .ssh/config.

Edit: awk improvement suggested by Grant McLean

2
  • Thank you for this - it was exactly what I needed. Incidentally, awk already has built-in grep-like functionality. Your command can be simplified to: ssh -G -nNT -L10000:localhost:10000 admin@yo | awk '/^hostname/ {print $2}' Commented Oct 16, 2024 at 0:58
  • Correct I will fix the answer. Commented Oct 16, 2024 at 20:23

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.