views:

60

answers:

3

I've been looking around but can't figure this out.. I figured out how to do a perl execution of a shell script, such as:

#!/usr/bin/perl
$cmd = "nautilus";
system $cmd;

However, I want to do a shell script execution from perl that would do something like this on the command line:

su
$password
nautilus

So it would become root, then open the nautilus browser.. when I tried this by just doing each command on separately, like below, it doesn't work.. I would appreciate any advice as to the proper way to accomplish this.. thanks

$cmd = "su";
system $cmd;
$cmd = $password;
system $cmd;
$cmd = "nautilus";
system $cmd;
+3  A: 

Check out the Expect module. It will do what you want. (It should be included already in the last several Perl versions)

Cfreak
This is not a problem for which expect is a good solution if you can avoid it. Using sudo is better because it doesn't require you to leave a password lying around in cleartext. Also sudo logs all uses, whereas nothing will notify you if someone has read your root password where you wrote it in cleartext.
Gilles
A: 

If you wanted to do it by hand, this is one way of doing it. However, as in Cfreak's post, I recommend Expect as well:

# cat foo.pl
  #!/usr/bin/perl
  if( open SHELL, "| /bin/bash" )
  {
    print SHELL <<'COMMANDS';
  echo hello
  pwd
  # do whatever
  COMMANDS
    close SHELL;
  }
  else
  {
    die "horrible error: $!";
  }
# ./foo.pl
  hello
  /mypath/whatever/
#
eruciform
+1  A: 

It's a horrible idea to hard-code a password in the code, especially the password of your root account. A much better and more secure way would be to use the sudo command which is most likely preinstalled in pretty much every linux distribution. You can even allow a user to execute a predefined command with root permissions without asking a password at all - which is still more secure because an attacker that could read your variant of the script has access to the root password and thus can do anything he wants, while using the sudo variant only allows him to execute the predefined command as root. In addition, the code does not break once you're fancy changing your root password.

In /etc/sudoers:

myuser ALL=NOPASSWD: /usr/bin/nautilus

In your perl script:

system("sudo /usr/bin/nautilus");

Jonas
And if you need to run more than one command as root, the simplest solution is to put the commands to run as root inside a script.
Gilles