Is it possible for root to execute a command as non-root?

Short answer: "Yes, this is possible".

if you like to execute a non-X application then just use the following command:

sudo -u abc command

If you like to run some X application as another user but with your own desktop first you need to create a helper script, that will make your life simpler

  • create a bin folder under your home directory:

mkdir -p ~/bin

and using your favorite text editor create a file ~/bin/xsudo as follows:

#!/bin/bash
# (C) serge 2012
# The script is licensed to all users of StackExchange family free of charge
# Fixes/Enhancements to the script are greatly appreciated. 
# 
# SUDO_ASKPASS has to be set to the path of ssh-askpass
# fix the following two lines if your distribution does not match this autodetection
. /etc/profile.d/gnome-ssh-askpass.sh
export SUDO_ASKPASS="${SSH_ASKPASS}"

SUDOUSERNAME="$1"
shift
xauth nlist "${DISPLAY}"|sudo -HA -u $SUDOUSERNAME env --unset=XAUTHORITY \
bash -c "xauth nmerge - ; $*"

then make it executable:

chmod +x ~/bin/xsudo

and use it the same way as sudo but without any switches:

xsudo user application

Enjoy.

P.S. Starting xsession from the root account is strongly discouraged!


A portable solution would be:

su abc -c google-chrome

However, as google-chrome is requiring X11 access, this will likely fail unless you unsecured it, which would be a very bad idea, especially while running as root.

If X11 tunelling/forwarding is allowed, a better way would be

ssh -X abc@localhost google-chrome

or

ssh -Y abc@localhost google-chrome

Tags:

Linux

Su

User