http://www.perlmonks.org?node_id=1029184

cspctec has asked for the wisdom of the Perl Monks concerning the following question:

Okay, I'm trying to write a script that will attempt to log in as su on my unix box, but I do not know how to send my password from the script when the system requests a password...
my $root = system("su"); my $password = "password"; print "$password"; print "\n";

Am I on the right path? The terminal just prompts for the root password and sits there waiting for a response, and I'm wanting the script to send the password.

Replies are listed 'Best First'.
Re: Responding to terminal I/O
by CountOrlok (Friar) on Apr 17, 2013 at 18:01 UTC
    This isn't the right way to approach this. When you do system("su"), your program will sit and wait for the su command to finish or timeout before going on the next line of code.

    The larger question would be why do you want to do "su"? Are you then going to run certain commands as root? You should instead look into using something like the Expect module.
      I am trying to write a script that will simulate a superuser log in attempt failure, but I'm not sure how to send a password to the terminal when the terminal requests a password.
        this should get you started:
        use strict; use warnings; use Expect; my $timeout = 5; my $password = "password"; my $shell_prompt = ']$ '; my $exp = new Expect; $exp->raw_pty(1); $exp= Expect->spawn("su") or die "Error calling su: $!\n"; unless ($exp->expect(5,"Password: ")) { die; # add error handling }; $exp->send("$password\n"); unless ($exp->expect(5, $shell_prompt)) { die; # add error handling }; print "Login successful\n";
Re: Responding to terminal I/O
by 2teez (Vicar) on Apr 17, 2013 at 18:35 UTC

    '.. I'm trying to write a script that will attempt to log in as su on my unix box..'
    see Unix::Login - Customizable Unix login prompt and validation module, it might be what you what

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me