无法使用 phpseclib 库更改目录

Can't change directory using phpseclib library

我想用 phpseclib 库更改 PHP 中的目录,但它不起作用。

$ssh = new Net_SSH2('localhost');
if (!$ssh->login('root', 'pass')) {
    exit('Failed to connect!');
}
$ssh->exec('cd /home/');
echo $ssh->exec('ls');

为什么这总是只输出根目录files/folders...并且不将目录更改为主目录?

如果您 read the documentation,它表示:

If done on an interactive shell, the output you'd receive for the first pwd would (depending on how your system is setup) be different than the output of the second pwd. The above code snippet, however, will yield two identical lines.

The reason for this is that any "state changes" you make to the one-time shell are gone once the exec() has been ran and the channel has been deleted.

You can workaround this on Linux by doing $ssh->exec('cd /; pwd')

因此您需要将两个命令放在同一个 exec 中:

$ssh->exec('cd /home/; ls');