1

On my VPN I have a remote server and a remote router (which is running RouterOS with an API and supports ssh connections). What I want is to write a php script and deploy it on the server so it will connect to the remote router using ip address and login credentials and than, run some commands.

I read on the internet that there is a solution for that which is libssh2.php library, but I cannot figure out how to install/use or even test if it work on the server. The Server is running CentOS.

Thank you in advance!!!

2 Answers 2

1

I think you'd be best off with phpseclib, a pure PHP SSH implementation. It has a number of advantages over libssh2:

http://phpseclib.sourceforge.net/ssh/compare.html

Here's an example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
Sign up to request clarification or add additional context in comments.

Comments

0

I did this before and was simply using the SSH command directly. For example:

$sshCmd = "ssh [email protected] \"ls -la ~\"";
exec($sshCmd, $output, $errorCode);
echo "Error code: $errorCode\n";
echo "Output: " . implode("\n", $output);

If you have more complex scripts to run, you can put then in a .sh script and run then via bash:

$sshCmd = "ssh [email protected] 'bash -s' < \"/path/to/script.sh\"";
exec($sshCmd, $output, $errorCode);
echo "Error code: $errorCode\n";
echo "Output: " . implode("\n", $output);

8 Comments

Ehm, ok, but how do I see the output??? I wrote did as you suggested and the server didn't return me an error. But how do I know that the commands were executed??? Is there a way to output what ever the commands return???
@user2462749, exec can optionally return the command output and error code. I've updated my example to show this.
So I wrote exec($sshCmd, $shhOut, $shhErr) or die("Failed to connect"); ___ And it prints "Failed to connect". So my guess is that exec is not working. Any ideas what might be the problem???
No that wouldn't work, you need to send all the commands in one go via SSH. In your case, it would be something like this: ssh [email protected] "/system backup name=phpRemoteBackup". First, you could try this in your shell to double-check that it actually works. Also try without the die() statement. Instead, inspect the output and error code of ssh as in the example code in my answer.
I tried ssh [email protected] /system clock print on my shell and it didn't work. It asked me for the password. How do I put the password with the username???
|

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.