Acorbe
Acorbe

Reputation: 8391

Bash - checking if user is logged via ssh

I am in the process of writing a bash script which has to do with recursive modifications of UIDs and GIDs of a given target user T. It has to be run on a remote machine and as root.

In order to work properly, the script requires that such user T is not the one which made the ssh connection. Otherwise, commands as usermod won't work as there are processes alive owing to T (ssh).

In other words, to operate on T, I must be logged as root after having connected as S.

Is there a way I can ensure that the user logged is not the target of the script? i.e. that S!=T?

Upvotes: 1

Views: 579

Answers (1)

kojiro
kojiro

Reputation: 77137

If you can modify the part of the script that runs before privilege escalation, keep in mind ssh normally sets the USER environment variable. You can export that to another name to keep around within the escalated environment.

OLD_USER=$USER su -m # the `-m` flag says to keep the current environment

(Then again, if you can modify the part of the script that runs before privilege escalation, why not just check if S=T then?)

Also, if you become root using sudo, that command sets SUDO_USER and SUDO_UID for you.

Upvotes: 1

Related Questions