Ssh2_exec () does not change directory with "cd"

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 team.

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 registered as root.

The first command runs correctly and copies the file to the specified location. The second command is not executed, but does not display errors. The third command displays an error (obviously, since the previous cd command does not work).

I know that he did not change dirs, because when I execute "pwd" he returns, saying that he is in the root directory.

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

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

+6
php centos plesk
source share
1 answer

To execute ssh2_exec() PHP starts a process that runs ssh running on a remote server.

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

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

In other words, the command-line shell environment will not be remembered during the execution of the n + 1 command.

If you want shell commands to work, depending on each other in terms of the environment, you must put several commands in a unique ssh2_exec as

  $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); 
+14
source share

All Articles