Rick
Rick

Reputation: 17013

Perl, executing linux shell commands that are multi-line, require authentication?

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;

Upvotes: 3

Views: 6712

Answers (3)

Jonas
Jonas

Reputation: 416

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");

Upvotes: 1

eruciform
eruciform

Reputation: 7736

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/
#

Upvotes: 0

Cfreak
Cfreak

Reputation: 19319

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

Upvotes: 3

Related Questions