Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ssh2_exec() wont change directory with "cd"

Tags:

php

centos

plesk

I have a problem with ssh_exec() refusing to execute the "cd" command.

If I log into the server directly and execute the command, it works fine, so I don't think the problem is with my command.

My code is as follows:

$str = ssh2_exec($sshStream, 'cp /var/www/compressed.tar.gz /var/www/vhosts/demo-domain1.com/httpdocs/');
$errstr = ssh2_fetch_stream($str, SSH2_STREAM_STDERR);
stream_set_blocking($str, true);
stream_set_blocking($errstr, true);
echo "Output: " . stream_get_contents($str);
echo "Error: " . stream_get_contents($errstr);

$str = ssh2_exec($sshStream, 'cd /var/www/vhosts/demo-domain1.com/httpdocs/');
$errstr = ssh2_fetch_stream($str, SSH2_STREAM_STDERR);
stream_set_blocking($str, true);
stream_set_blocking($errstr, true);
echo "Output: " . stream_get_contents($str);
echo "Error: " . stream_get_contents($errstr);

$str = ssh2_exec($sshStream, 'tar xzf c-class.tar.gz');
$errstr = ssh2_fetch_stream($str, SSH2_STREAM_STDERR);
stream_set_blocking($str, true);
stream_set_blocking($errstr, true);
echo "Output: " . stream_get_contents($str);
echo "Error: " . stream_get_contents($errstr);

I am logged in as root.

The first command runs correctly and copies the file to the location. The second command doesn't execute, but outputs no errors. The third command displays an error (obviously as the previous cd command doesn't work).

I know it hasn't changed dirs, as when I execute the "pwd", it returns saying it is in the root dir still.

As mentioned before, if I run the commands from shell, they execute fine, so I'm 99.9% sure my syntax is correct.

This is a dedicated server provided by 1&1, running CentOS and Plesk 9.

like image 852
David Cooke Avatar asked Jan 07 '11 16:01

David Cooke


1 Answers

To execute ssh2_exec() PHP starts a process that will perform a ssh executed on the remote server.

The shell process created remotely has its own environment, including the current working directory.
The cd command will change the working directory of the shell that was started by your second command.

When that second command ends, the shell dies with it. Along with the working dir information.

In other terms, the shell environment of the command N will not be remembered during the execution of command N+1.

If you want the shell commands to be working while depending on each other in terms of environment, you should put several commands in a unique ssh2_exec like

 $str = ssh2_exec($sshStream, 'cd /var/www/vhosts/demo-domain1.com/httpdocs/;'
                            . 'tar xzf c-class.tar.gz');

 $errstr = ssh2_fetch_stream($str, SSH2_STREAM_STDERR);
 stream_set_blocking($str, true);
 stream_set_blocking($errstr, true);
 echo "Output: " . stream_get_contents($str);
 echo "Error: " . stream_get_contents($errstr);
like image 153
Déjà vu Avatar answered Nov 13 '22 06:11

Déjà vu