If you have a sudo configuration that allows it (as most desktop linux distributions do for normal users), you can start your perl script with this line:
#!/usr/bin/env -S -i MYVAR=foo sudo --preserve-env perl -w -T
Then in your script before you use system()
or backticks explicitly set your $ENV{PATH} (to de-taint it):
$ENV{PATH} = '/usr/bin';
Other environment variable that your script explicitly mentions or that get implicitly used by perl itself will have to be similarly de-tainted (see man perlsec
).
This will probably (again depending on your exact sudo configuration) get you to the point where you only have to type in your root password once (per terminal) to run the script.
To avoid having to type your password at all you can add a line like this to the bottom of /etc/sudoers
:
myusername ALL=(ALL) NOPASSWD:ALL
Of course you'd want to be careful with this on a multi-user system.
The -S
options to env splits the string into separate arguments (making it possible to use options and combinations of programs like sudo/perl with the shebang mechanism). You can use -vS
instead to see what it's doing.
The -i
option to env
clears the environment entirely.
MYVAR=foo
introduces an environment variable definition.
The --preserve-env
option to sudo will preserve MYVAR
and others.
sudo
sets up a minimal environment for you when it finds e.g. PATH
to be missing.
The -i
option to env
and --preserve-env
option to sudo
may both be omitted and you'll probably end up with a slightly more extensive list of variables from your original environment including some X-related ones (presumably the ones the sudo configuration considers safe). --preserve-env
without -i
will end up passing along your entire unsanitized environment.
The -w
and -T
options to perl are generally advisable for scripts running as root.