Thursday, September 24, 2009

Run GUI applications as another user in Linux

Supposed user1 wants to run a gnome-terminal as user2. He needs to do these:

1. Login as root (or ask root to help) to setup the sudoers. Run visudo and add these:
user1 ALL = (user2) NOPASSWD:ALL
Note: This grants user1 to do any good or harm to user2's account. You may want to limit the commands user1 can run.

2. Create a shell script with these lines:
xhost +SI:localuser:user2
sudo -u user2 -H gnome-terminal
xhost -SI:localuser:user2

3. Run the script and you will get a gnome-terminal popped up, which is owned by user2.

Some notes:
  • The manpage of xhost implies that you can add a user name by typing "xhost +user2". That is not true. You must use ServerInterpreted to add a user. Otherwise you will get an error of "xhost: bad hostname user2".
  • If you are getting "cannot open display" error, it may be that your environmental variables are reset by sudo. If that is the case, you need to add this to the sudoers:
Defaults env_keep="DISPLAY XAUTHORITY"

No comments:

Get This <