Get ssh username in bash script

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

However, I set the binding after committing to the SVN S server, which SSH is in A and runs the script there, which causes the log name to fail, with the error "logname: no login name".

If I find SSH in S from my desktop, then SSH in A , it works correctly, so the error should be that the SVN hook ultimately does not start from the virtual terminal.

What alternative can logname be used here?

+4
source share
3 answers

You can 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 strip the username from the id output with something like

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

To have a script that works both in sudo and without a terminal, you can 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 
+3
source

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 
+2
source

Use id -nu . There are no stupid forks and cuts to get a username.

+2
source

All Articles