Skip to content

Instantly share code, notes, and snippets.

@JonTheNiceGuy
Last active December 5, 2017 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonTheNiceGuy/bc7408d36a7849541b7574ddd4fda18f to your computer and use it in GitHub Desktop.
Save JonTheNiceGuy/bc7408d36a7849541b7574ddd4fda18f to your computer and use it in GitHub Desktop.
Run GUI commands as other users, without having to SSH to that user account.

runas for Unix-like Systems

Download these two files, and place them in /usr/local/bin. Chmod them to 755, and chown them to root:root.

Then, perform the following command:

runas -u someuser command

or

runas -v command

or

runas -v -u anotheruser command

This is useful for starting scripts as other users, with a full GUI.

By amending line 68 of the "runas" script, you could make this be your "standard" way to run virtual machines (runas -u virtualbox virtualbox)

die_with_message() {
echo $1
exit 1
}
usage() {
echo "This script allows you to become another user to perform a GUI command"
echo "Usage:"
echo "$0 [-v] [-u NAME] [command]"
echo ""
echo "Options are:"
echo " -v | --verbose = Enable verbose mode"
echo " -u NAME | --user NAME = Specify the username (default root)"
echo " -h | --help = This help"
}
RunAsUser=""
Verbose=""
# Heavily based on
# http://wiki.bash-hackers.org/scripting/posparams#production_examples
while :
do
case "$1" in
-h | --help)
usage
exit 0
;;
-u | --user)
if [ -z "$2" ] || [ "${2:0:1}" == "-" ]; then
echo "Must supply a user for the -u/--user option." >&2
usage
exit 2
fi
if [ -n "$RunAsUser" ]; then
echo "The -u/--user option can only be passed once." >&2
usage
exit 2
fi
RunAsUser="$2"
if [ $(id -u $RunAsUser 2>/dev/null || echo -1) -eq -1 ]; then
echo "No such user as $RunAsUser." >&2
usage
exit 2
fi
shift 2
;;
-v | --verbose)
Verbose="verbose"
shift
;;
--)
shift
break;
;;
-*)
echo "Error: Unknown option: $1" >&2
exit 1
;;
*)
break
;;
esac
done
if [ -z "$RunAsUser" ]; then
RunAsUser="$(id -un 0)"
fi
if [ -n "$DISPLAY" ] && [ -n "$1" ]; then
CURRENTDISPLAY="$(echo $DISPLAY | cut -d ':' -f 2 | cut -d '.' -f 1 | sed -e s/^/:/)"
MYXAUTH=$(xauth list || die_with_message "Unable to obtain XAuthority to run this command...")
DPYNAME="$(echo $MYXAUTH | grep "$CURRENTDISPLAY" | cut -d ' ' -f 1)"
PROTONAME="$(echo $MYXAUTH | grep "$CURRENTDISPLAY" | cut -d ' ' -f 3)"
HEXKEY="$(echo $MYXAUTH | grep "$CURRENTDISPLAY" | cut -d ' ' -f 5)"
fi
if [ -z "$1" ]; then
if [ -n "$Verbose" ]; then
echo "CMD: sudo -u $RunAsUser -i"
fi
sudo -u "$RunAsUser" -i
else
if [ -n "$Verbose" ]; then
echo "CMD: sudo -u $RunAsUser -i -- xauth_exec $DISPLAY $DPYNAME $PROTONAME $HEXKEY $@"
fi
sudo -u "$RunAsUser" -i -- xauth_exec "$DISPLAY" "$DPYNAME" "$PROTONAME" "$HEXKEY" "$@"
fi
#! /bin/bash
export DISPLAY=$1
shift
xauth add $1 $2 $3
shift 3
"$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment