0

I am attempting to write my first ever PHP script, and I am struggling quite a bit, the main issue is the connection/exec part is not working and instead throwing the "Could not connect to server" message...

tried changing the code if statements.

<?php
  include('Net/SSH2.php');
  //Coded by Aaron Akhtar
  //May not be the best code, this is my first ever php script ;P

  //edit the information below to match your ssh details or this will not work!
  $address = "104.xxx.xx.xx";
  $user = "root"; //do not change unless you are using another user from root
  $password = "xxxxx";

  $command = $_GET["command"];

  if(empty($command)){
    echo "Please specify a command to send to the server...";
    die();
  }

    function execute(){
    $connection = ssh2_connect($address, 22);
    if(ssh2_auth_password($connection, $user, $password)){
      echo ssh2_exec($connection, $command);
    }else {
      die("Could not connect to server...");
    }

  }

  execute();

 ?>

I am trying to get it to send a command to my remote server.

  • Since you define those login information as global variables, you have to define inside your function which global variables you are going to use using `global` keyword https://stackoverflow.com/questions/15687363/php-access-global-variable-in-function – catcon Jul 10 '19 at 10:34
  • It's best practice to pass those login information to function as parameter, rather than using global variables – catcon Jul 10 '19 at 10:36

1 Answers1

0

Try these changes:

function execute($address,$user, $password, $command){
    $connection = ssh2_connect($address, 22);
    if(ssh2_auth_password($connection, $user, $password)){
        echo ssh2_exec($connection, $command);
    }else {
        die("Could not connect to server...");
    }
}

execute($address,$user, $password, $command);

The variables that you were referencing inside the function weren't actually available, they need to either be passed in as parameters when calling the function as I've done in the snippet above or by declaring them globally inside the function.

John.M
  • 335
  • 1
  • 10
  • Why should the OP "try these changes"? A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Jul 10 '19 at 17:45
  • Thanks, I've updated the answer and will keep that in mind in the future. Cheers. – John.M Jul 10 '19 at 22:41