in reply to Best way to write to a file owned by root?
Hello nysus,
Have you tried to execute the script with sudo?
Sample:
sudo hosts.plFor 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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Best way to write to a file owned by root?
by nysus (Parson) on Mar 13, 2017 at 22:51 UTC | |
by afoken (Chancellor) on Mar 14, 2017 at 07:00 UTC | |
by thanos1983 (Parson) on Mar 14, 2017 at 11:38 UTC | |
by afoken (Chancellor) on Mar 14, 2017 at 21:32 UTC | |
by nysus (Parson) on Mar 14, 2017 at 22:25 UTC | |
by afoken (Chancellor) on Mar 15, 2017 at 06:42 UTC | |
| |
by nysus (Parson) on Mar 14, 2017 at 20:21 UTC | |
by Anonymous Monk on Mar 14, 2017 at 21:37 UTC |