Hello nysus,
Have you tried to execute the script with sudo?
Sample:
sudo hosts.pl
For me the following worked just fine:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
sub read_hosts {
my $file = "/etc/hosts";
open (my $fh, "<", $file)
or die "Can't open $file for read: $!";
my @hosts = <$fh>;
close $fh
or die "Cannot close $file: $!";
return @hosts;
}
sub write_hosts {
my $file = "/etc/hosts";
open (my $fh, ">", $file)
or die "Can't open $file for read: $!";
for my $host (@_) {
print $fh $host;
}
# Or print $fh $_ for (@_);
close $fh
or die "Cannot close $file: $!";
return;
}
my @hosts = read_hosts;
print Dumper \@hosts;
$hosts[2] = "Test_host\t127.0.0.4\n";
write_hosts(@hosts);
my @updates = read_hosts();
print Dumper \@updates;
__END__
sudo perl hosts.pl
$VAR1 = [
'127.0.0.1 localhost
',
'127.0.1.1 user
',
'# The following lines are desirable for IPv6 capable hosts
',
'::1 ip6-localhost ip6-loopback
',
'fe00::0 ip6-localnet
',
'ff00::0 ip6-mcastprefix
',
'ff02::1 ip6-allnodes
',
'ff02::2 ip6-allrouters'
];
$VAR1 = [
'127.0.0.1 localhost
',
'127.0.1.1 user
',
'Test_host 127.0.0.4
',
'::1 ip6-localhost ip6-loopback
',
'fe00::0 ip6-localnet
',
'ff00::0 ip6-mcastprefix
',
'ff02::1 ip6-allnodes
',
'ff02::2 ip6-allrouters'
];
Update: Adding print $fh $_ for (@_);
Update2: Or use Sudo module:
Make sure the script "hosts.pl" is executable chmod +x hosts.pl
#!/usr/bin/perl
use strict;
use warnings;
use Sudo;
my $su;
my $name = "root";
my $pass = "password";
$su = Sudo->new( { sudo => '/usr/bin/sudo',
#sudo_args => '...',
username => $name,
password => $pass,
program => '/home/user/hosts.pl',
#program_args => '...'
}
);
my $result = $su->sudo_run();
if (exists($result->{error})) {
printf "STDERR: %s\n",$result->{error};
#&handle_error($result);
}
else {
printf "STDOUT: %s\n",$result->{stdout};
printf "STDERR: %s\n",$result->{stderr};
printf "return: %s\n",$result->{rc};
}
__END__
$ perl sudo.pl
STDOUT: $VAR1 = [
'127.0.0.1 localhost
',
'127.0.1.1 user
',
'
',
'::1 ip6-localhost ip6-loopback
',
'fe00::0 ip6-localnet
',
'ff00::0 ip6-mcastprefix
',
'ff02::1 ip6-allnodes
',
'ff02::2 ip6-allrouters'
];
$VAR1 = [
'127.0.0.1 localhost
',
'127.0.1.1 user
',
'Test_host 127.0.0.4
',
'::1 ip6-localhost ip6-loopback
',
'fe00::0 ip6-localnet
',
'ff00::0 ip6-mcastprefix
',
'ff02::1 ip6-allnodes
',
'ff02::2 ip6-allrouters'
];
STDERR:
return: 1
Hope this helps.
Seeking for Perl wisdom...on the process of learning...not there...yet!
|