0

I try to write variable in end of file, but write it into STDOUT in local server some code:

$num = <STDIN>
my $cmd = "echo $dep_keys{$num} >> /root/1";
#$ssh->system({stdin_data =>$dep_keys{$num} },"echo >> /root/1");
#$ssh->error die "Couldn't establish SSH connection: ". $ssh->error;
#$ssh->system("echo $dep_keys{$num} >> /root/1");
$ssh->system($cmd);

I expect that the file will contain new line in the end of file.

3
  • 3
    The first problem here is that you're not using strict and warnings. The second problem is that $num will usually contain a trailing newline after reading from STDIN, so you should use chomp on it. Commented Sep 27, 2019 at 16:48
  • 3
    The variable is interpolated locally into that string, so it is not a variable anymore on the remote system, and by enabling warnings you will be informed that it is probably just undefined because you didn't chomp $num. Commented Sep 27, 2019 at 16:50
  • 3
    The third problem is that you aren't sanitizing the variable for use in a shell command, which you can use String::ShellQuote to do. Commented Sep 27, 2019 at 16:51

1 Answer 1

1
use String::ShellQuote qw( shell_quote );

defined( my $num = <STDIN> )
   or die("Invalid input");

chomp($num);

defined($dep_keys{$num})
   or die("Invalid input");

my $cmd = shell_quote('printf', '%s\n', $dep_keys{$num}) . ' >>/root/1';
$ssh->system($cmd);

Fixes:

  • Checks for EOF and other invalid inputs.
  • Removes trailing line feed from $num (if any).
  • Properly convert the text from the hash element into a shell literal.
  • Avoids echo because echo makes impossible to output some strings.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.