#!/bin/sh # # Execute a command as another user, with access to the X display # # Copyright (C) 2013 Antonio Ospite # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # This is the equivalent of sux[1] but simpler and using sudo. # [1] http://fgouget.free.fr/sux/ set -e usage() { echo "usage: $(basename $0) [OPTION]... " echo "Execute a command as another user, with access to the X display" echo echo "List of OPTIONs:" echo echo " -u user Execute the program as the specified user (default is root)" echo " -d display Set the X display" echo " -h|--help Show this help text" echo sudo -h | grep -v "^[ ]\+-u user" } USERNAME=root while true; do case "$1" in -u) [ "x$2" != "x" ] || { usage 1>&2; exit 1; } USERNAME="$2" shift 2 ;; -d) [ "x$2" != "x" ] || { usage 1>&2; exit 1; } DISPLAY="$2" shift 2 ;; -h | --help) usage exit 0 ;; *) break ;; esac done id $USERNAME > /dev/null || { echo "Invalid user." 1>&2; exit 1; } [ -n "$DISPLAY" ] || { echo "Cannot get the DISPLAY env variable." 1>&2; exit 1; } [ "x$@" != "x" ] || { usage 1>&2; exit 1; } # Get the authorization cookie from the current user. COOKIE="$(xauth nextract - $DISPLAY)" # XAUTHORITY needs to be unset now, so that the default $HOME/.Xauthority will # be used for the target user and not some locked auth file from the current # user. unset XAUTHORITY # Authorize the user. # Use "sudo -H" to cover the case when env_keep+="HOME" is set in /etc/sudoers echo "$COOKIE" | sudo -H -u "$USERNAME" xauth nmerge - # Execute the command. # NOTE: -i or -s can be passed in order to open a shell sudo DISPLAY="$DISPLAY" -u "$USERNAME" "$@"