1

I'm trying to use an SSH connection through PHP to run Bash scripts.

I wrote a script to make backups and restores for a MySQL database and I am still testing to achieve this. I have encountered a problem while trying to run two different simple commands. My code is:

<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");

if(!($con = ssh2_connect("server.hosting.com", 22))){
    echo "fail: unable to establish connection\n";
} else {

    if(!ssh2_auth_password($con, "username", "password")) {
        echo "fail: unable to authenticate\n";
    } else {
        // allright, we're in!
        echo "okay: logged in...\n";




        if (!($stream = ssh2_exec($con, "cd directory " ))) {
            echo "fail: unable to execute command\n";
        } else {
            // collect returning data from command
            stream_set_blocking($stream, true);
            $data = "";
            while ($buf = fread($stream,4096)) {
                $data .= $buf;
            }
            fclose($stream);
        }
if (!($stream = ssh2_exec($con, "mkdir directiry2" ))) {
            echo "fail: unable to execute command\n";
        } else {
            // collect returning data from command
            stream_set_blocking($stream, true);
            $data = "";
            while ($buf = fread($stream,4096)) {
                $data .= $buf;
            }
            fclose($stream);
        }
    }
}
?>

It still creates another directory but not inside the "directory"! Please help!!!

3
  • why not just mkdir -p directory/directiry2? You don't need to cd into a dir to make something inside it. Commented Jul 10, 2015 at 16:20
  • Thanks for that Marc B, now how can i run something like this : mysqldump -u... -p... mydb t1 t2 t3 > mydb_tables.sql Commented Jul 10, 2015 at 16:27
  • [shameless pub] you might want to have a look at github.com/tivie/command It enables you to chain shell commands and set cwd in an OOP way Commented Jul 10, 2015 at 16:33

1 Answer 1

1

The problem is that when you do cd the "state" is lost right after. The phpseclib docs elaborate:

http://phpseclib.sourceforge.net/ssh/examples.html#chdir,

If you want to be able to cd to a directory and then do stuff in that directory you can chain stuff. eg. $ssh->exec('cd directory; mkdir directiry2');

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.