Reputation: 1287
I am new to Perl. I'm building a plugin for Cpanel to install SSL certificates when the user clicks an option.
I have to execute a command as root inside the Perl code. How can I do this?
Upvotes: 0
Views: 331
Reputation: 222622
So basically you need to run a system command as root
user from within a Perl script.
You can use the system built-in function with a sudo
inside it. This will fork a new process where the command will be executed while the parent process waits, and then return the exit status of that command.
For example, this basic command switches to root
and prints the current user :
perl -e 'system("sudo su -c whoami")'
Obiously, it outputs this on the standard output :
root
Notes :
for this to work, you need you application user to be able to switch to root
(without the need of typing a password) ; some could consider that a security breach (some attacker that would have taken over your application would be able to cause fatal damage to your system)
the actual command to switch to the root
user might vary depending on your OS ; the one I used in the example you is for RedHat
I searched the CPAN for modules that provide the "switch to root" functionality and the only one I found is Sudo ; I didn't try it, but it that was not updated since 2013 and has few issues pendings since 3 to 9 years
Upvotes: 2