in reply to Find and replace MD5 hash from file
First, you need to convert the text into a regex pattern. Then you need to convert the Perl program into a sh string literal.
sub text_to_shell_lit(_) { return $_[0] if $_[0] =~ /^[a-zA-Z0-9_\-]+\z/; my $s = $_[0]; $s =~ s/'/'\\''/g; return "'$s'"; } my $pat = quotemeta($hash2); my $repl = quotemeta($hash1); my $perl_code = 's/^'.$pat.'$/'.$repl.'/'; my $remote_cmd = join ' ', map text_to_shell_lit, '/usr/bin/perl' => ( '-i', '-p', '-e' => $perl_code, 'hashfile', ); my $ssh_cmd = join ' ', map text_to_shell_lit, 'ssh' => ( '-o' => 'StrictHostKeyChecking=no', 'root@localhost', '--', $remote_cmd, ); system($ssh_cmd);
That can be shortened to
sub text_to_shell_lit(_) { return $_[0] if $_[0] =~ /^[a-zA-Z0-9_\-]+\z/; my $s = $_[0]; $s =~ s/'/'\\''/g; return "'$s'"; } system(q{ssh -o StrictHostKeyChecking=no root@localhost }.text_to_shel +l_lit(q{/usr/bin/perl -i -pe}.text_to_shell_lit("s/^\Q$pat\E\$/\Q$rep +l\E/").q{ hashfile}));
But I wanted to present the safe but wordy version. If you do it in steps, you're more likely to get it right then if you start with this short but far more complex version.
Alternatively, you could use the multiple argument form of system instead of forming a shell command since don't need the shell.
my $pat = quotemeta($hash2); my $repl = quotemeta($hash1); my $perl_code = 's/^'.$pat.'$/'.$repl.'/'; my $remote_cmd = join ' ', map text_to_shell_lit, '/usr/bin/perl' => ( '-i', '-p', '-e' => $perl_code, 'hashfile', ); system( 'ssh' => ( '-o' => 'StrictHostKeyChecking=no', 'root@localhost', '--', $remote_cmd, ), );
By the way, I suspect sudo is a more common way of escalating to root privileges.
By the way,
is the same ass/.../.../ee
s/.../eval "..."/e
which is very very very wrong. $hash1 does not contain Perl code to execute, so the /e is wrong, and if it was Perl code to execute, it doesn't return Perl code to execute, so the eval is wrong too.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Find and replace MD5 hash from file
by adroc (Initiate) on Jun 29, 2011 at 20:18 UTC | |
by ikegami (Patriarch) on Jun 29, 2011 at 20:28 UTC | |
by adroc (Initiate) on Jun 29, 2011 at 22:35 UTC |