Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get SSH login name in bash script

Tags:

bash

ssh

I have a Bash script on server A that finds the logged in SSH user via the logname command, even if it's run as root with sudo. If I SSH into server A from my desktop and run the script, it works fine.

However, I've set up a post-commit hook on SVN server S which SSH's into A and runs the script there, which causes logname to fail, with error "logname: no login name".

If I SSH into S from my desktop, then SSH into A from there, it works correctly, so the error must be in the fact that the SVN hook ultimately does not run from a virtual terminal.

What alternative to logname can I use here?

like image 445
Bart van Heukelom Avatar asked Jan 17 '23 09:01

Bart van Heukelom


2 Answers

You could use the id command:

  $ ssh 192.168.0.227 logname
  logname: no login name

However

  $ ssh 192.168.0.227 id
  uid=502(username) gid=100(users) groups=100(users)

In a bash script you can cut the username out of the id output with something like

  $ id | cut -d "(" -f 2 | cut -d ")" -f1
  username

To have a script that works both in a sudo environment and without a terminal you could always execute different commands conditionally.

if logname &> /dev/null ; then 
    NAME=$( logname )
else 
    NAME=$( id | cut -d "(" -f 2 | cut -d ")" -f1 )
fi
echo $NAME
like image 161
Dmitri Chubarov Avatar answered Jan 18 '23 23:01

Dmitri Chubarov


This is what I ended up with.

if logname &> /dev/null; then
    human_user=$(logname)
else
    if [ -n "$SUDO_USER" ]; then
        human_user=$SUDO_USER
    else
        human_user=$(whoami)
    fi
fi
like image 35
Bart van Heukelom Avatar answered Jan 19 '23 00:01

Bart van Heukelom