1

I'm trying to retrieve the contents of a file on a remote server via SSH and display the results in a browser. The remote server's name and address is configured on my local server with the name "router", such that from the command line I can execute the following to successfully retrieve the results:

ssh router "cat /var/log/messages"

I'm having trouble getting this to execute in PHP - I can't get the quotes escaped properly. Here's my PHP script

<pre>
$command = 'ssh router \"cat /var/log/messages\"';
<?php system($command); ?>
</pre>

But this outputs the command string to the webpage instead of executing the command and returning the results.

1 Answer 1

2

Use escapeshellarg() to escape command argument. Please try like this

$host       =  escapeshellarg("user@router");
$commandArg =  escapeshellarg("/var/log/messages");
$result     = shell_exec('ssh ' . $host . ' cat ' . $commandArg);
echo $result, PHP_EOL;
Sign up to request clarification or add additional context in comments.

1 Comment

It's important to be extremely careful when executing arbitrary shell commands. It's great that you're using escapeshellarg, as this is really not optional.

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.