Ubuntu – How to create new “gksu” command based on pkexec

command linegeditgksudonautiluspolicykit

When I google “gksu gedit” one of the top entries (How to run gedit and nautilus as root) advises that gksu usage is frowned upon:

gksu hasn't been updated since 2009 and is not recommendedany more. In
fact, Ubuntu no longer ships with gksu by default (though it may be
installed for many of you, because some apps still depend on it) and
it may even be completely removed at some point.

A link to AskUbuntu (Why is gksu no longer installed by default?) suggests pkexec should be used instead but doesn't provide clear and concise steps to do this.

How can I use pkexec within a new wrapper shell script called gsu that supports both gedit and nautilus?

I feel a wrapper script called gsu is most appropriate because my "muscle memory" is to type gksu all the time and I don't want to have to type pkexec instead.

Additionally I would like those pesky gtk warning messages to disappear. Also I would like the terminal prompt back right away instead of waiting for editor or file manager to end.

AU Duplicates: I've searched many Q&A but none are asking (or offering how to) give a complete solution for gsu wrapper script to call pkexec AND install all necessary policy kits AND get rid of pesky gtk warnings AND get terminal prompt back right away… All in one answer.

Best Answer

Before you can use pkexec with gedit and nautilus you need to copy the polkit rules to support them. This will automatically be done in Ubuntu 17.04 but in the mean time you need to wget them.

Nautilus Policy Kit

wget https://raw.githubusercontent.com/hotice/webupd8/master/org.gnome.nautilus.policy -O /tmp/org.gnome.nautilus.policy
sudo cp /tmp/org.gnome.nautilus.policy /usr/share/polkit-1/actions/

Gedit Policy Kit

wget https://raw.githubusercontent.com/hotice/webupd8/master/org.gnome.gedit.policy -O /tmp/org.gnome.gedit.policy
sudo cp /tmp/org.gnome.gedit.policy /usr/share/polkit-1/actions/

"gsu" bash script to replace "gksu"

Creating a bash script is one of two ways to call pxexec using the somewhat familiar term of gsu. Create this file in one of your paths:

#!/bin/bash

# Usage: gsu gedit file1 file2...
#  -OR-  gsu natuilus /dirname

# & is used to spawn process and get prompt back ASAP
# > /dev/null is used to send gtk warnings into dumpster

COMMAND=$1 # extract gedit or nautilus

pkexec "$COMMAND" "${@:2}" &> /dev/null&

Save the file and mark it as executable with chmod +x gsu

Now instead of typing gksu to edit grub configuration you can use:

gsu gedit /etc/default/grub

"gsu" as an alias of "pkexec" to replace "gksu"

Creating an alias is the second option to call pxexec using the somewhat familiar term of gsu. Open the file ~/.bashrc and search for alias. You will see this:

# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

After the last line add this:

alias gsu='pkexec'

Save the file and exit.