thanos1983 has asked for the wisdom of the Perl Monks concerning the following question:
Dear Monks,
It looks like a familiar question, that has been answered differently such as Executing unix command from script. My question is not similar to this one and I am looking for a different approach than the proposed ones in the question.
My problem is that I want to able to execute sudo commands from my script without the use of any module(s) such as Expect.pm or Sudo.
I have all ready created an operating script using Expect.pm that is able to connect and execute sudo commands.
Sample of operating code is provided under:
#!/usr/bin/perl use Expect; use strict; use warnings; use Data::Dumper; sub loop { my $command = shift; my $debug = 0; my $timeout = 2; my $username = "username"; my $password = "password"; # create an Expect object by spawning another process my $exp = Expect->spawn($command) or die "Cannot spawn $command: $!\n"; my $login = Expect->init($exp); $login->raw_pty(1); $debug and $login->log_user(1); $debug and print "waiting for password prompt\n"; $login->expect($timeout, ':') or die "expect failed\n"; $debug and print "prompt seen\n"; $login->send("$password\n"); $debug and print "password sent\n"; $login->expect($timeout, "\n") or die "bad password\n"; $debug and print "password ok\n"; my $send; while(<$login>) { # removing trailing characters such as \n chomp $_; # removing blank space before and after the string $_ =~ s/^\s+|\s+$//g; print "\$_: ".$_."\n"; $send = $_; } # if no longer needed, do a soft_close to nicely shut down the com +mand $login->soft_close(); return $send; } my @commands = ( "sudo -k; sudo service ntp stop" , "sudo -k; sudo ntpd -gq" , "sudo -k; sudo service ntp start" ); my @final = (); foreach my $input (@commands) { my @output = loop($input); push(@final,@output); } print Dumper(\@final); __END__ $_: * Stopping NTP server ntpd + [ OK ] $_: ntpd: time slew +0.106441s $_: * Starting NTP server ntpd + [ OK ] $VAR1 = [ '* Stopping NTP server ntpd + [ OK ]', 'ntpd: time slew +0.106441s', '* Starting NTP server ntpd + [ OK ]' ];
I am looking to find a way to provide the username and password and be able to execute sudo commands. I do not want to change the access permissions of the script nor to disable root password.
At this point I do not know if what I want is possible, maybe it is not. But before I give up I would like to ask the experts if anyone has an idea on how to do that with a script.
Thank you in advance for your time and effort reading and replying to my question.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to execute sudo command(s) without the use of module(s)
by salva (Canon) on Sep 25, 2014 at 06:33 UTC | |
by thanos1983 (Parson) on Sep 25, 2014 at 23:03 UTC |