开发者

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 c开发者_开发技巧ommand 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;


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜