dtdb99743 2016-08-12 17:07
浏览 83
已采纳

SSH无法通过PHP exec正常工作

Hey I'm attempting to utilise the PHP SSH2 functions of which I've used a class from over a GitHub: Here but doesn't seem to be working as expected.

I'm trying to cd into a directory and then list files, but seems to ignore the cd and when I use the ls command it just displays the root dir.

Here's when I perform a normal ls on my root directory:

drwx------  6 root root 4096 Aug 12 18:23 .
drwxr-xr-x 22 root root 4096 Aug 11 08:28 ..
-rw-------  1 root root 2963 Aug 12 18:33 .bash_history
-rw-r--r--  1 root root 3106 Oct 22  2015 .bashrc
drwx------  3 root root 4096 Aug 11 21:05 .cache
drwxr-xr-x  3 root root 4096 Aug 12 18:21 .local
drwxr-xr-x  2 root root 4096 Aug 12 18:22 .nano
drwxr-xr-x 18 root root 4096 Aug 11 21:07 myOtherDirectory
-rw-r--r--  1 root root  148 Aug 17  2015 .profile
-rw-------  1 root root 1024 Aug 12 18:27 .rnd
-rw-r--r--  1 root root  252 Aug 12 18:28 .wget-hsts

And here's then I try to access the myOtherDirectory using SSH via PHP

$ssh = new ssh("ip", "root", "pass");
$ssh("cd myOtherDirectory");
$result = $ssh("ls -la");
print_r($result);
  • 写回答

1条回答 默认 最新

  • doupingzhi9674 2016-08-12 18:54
    关注

    The SSH protocol permits you to make one SSH connection (called a session) to a remote host and then run multiple channels through the single connection. A single channel can represent an interactive session, a single SFTP transfer, and so on. Each channel is independent of the others.

    $ssh = new ssh("ip", "root", "pass");
    $ssh("cd myOtherDirectory");
    $result = $ssh("ls -la");
    

    What you're doing here is creating a single SSH session to the remote host, then creating two channels. The first channel runs cd and then exits. The second channel runs ls and then exits. The two channels are independent of each other, so the cd invocation has no effect on the working directory of the ls invocation.

    You want to run both commands in a single session. Assuming the remote system is using bash or a similar shell to run commands, this ought to work:

    $ssh = new ssh("ip", "root", "pass");
    $result = $ssh("cd myOtherDirectory && ls -la");
    

    Alternately, you could specify the correct remote directory in the ls command:

    $ssh = new ssh("ip", "root", "pass");
    $result = $ssh("ls -la myOtherDirectory");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 qc代码,修改和添加东西
  • ¥50 Unity的粒子系统使用shadergraph(内置管线)制作的一个顶点偏移shader,但是粒子模型移动时,顶点也会偏移
  • ¥15 如何用python处理excel的数据(极值标准化)
  • ¥15 三向应力状态求剪应力
  • ¥15 jupyter notebook如何添加libGL.so.1库
  • ¥20 easyPoi能否实现下拉多选或者复选框
  • ¥15 网桥在转发帧时,会变帧的源地址和目的地址吗?
  • ¥15 用Multisim设计汽车尾灯控制电路
  • ¥100 求用matlab求解上述微分方程的程序代码
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码