How to run several commands with SSH.Net?

How to run 2 SSH commands separately using PHP?

  • 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!!!

  • Answer:

    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');

Luarb Balla at Stack Overflow Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.