普通网友 2013-07-30 10:20
浏览 132

使用ssh2_exec远程执行sh脚本时,PHP无法正常工作

I have a shell script makedir.sh as given below.

sudo -H sh -c '
    mkdir /usr/local/testdir;
    if [ $? -eq 0 ];then
        echo "Successfull";
    else
        echo "Unsuccessfull";
    fi
'

I have given privileges to a user testuser to execute shell script with sudo, but without asking password.For this I add the below line in /etc/sudoers file,

testuser ALL=(ALL) NOPASSWD: ALL

And it works fine that, I could run commands with sudo, but without asking password. The above shell script also working fine without asking password, creating directory testdir inside /usr/local. My problem starts here. I want to run this shell script from a php file. In the current scenario the shell script is residing in a remote machine with ip address 10.3.2.0. The following is my php code but, while running this php code, it is not creating any directory(testdir) inside /usr/local/ . Please advise as I am very beginner in PHP.

PHP Code

<?php
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
if(!($con = ssh2_connect("10.3.2.0", "22")))
{
    echo "fail: unable to establish connection";
}
else
{
    if(!ssh2_auth_password($con, "testuser", "abcdef"))
    {
        echo "fail: unable to authenticate ";
    }
    else
    {
        $stream = ssh2_exec($con, "./makedir.sh");
            stream_set_blocking($stream, true);
        $item = "";
        while ($input = fread($stream,4096)) {
               $item .= $input;
        }
        echo $item;
    }
}

?>

SHELL SCRIPT - makedir.sh (residing at 10.3.2.0 - the same above shell script)

#!/bin/sh
sudo -H sh -c '
    mkdir /usr/local/testdir;
    if [ $? -eq 0 ];then
        echo "Successfull";
    else
        echo "Unsuccessfull";
    fi
'

Thanks.

  • 写回答

2条回答 默认 最新

  • douqiang6448 2013-08-22 11:03
    关注

    From what i know, sudo commands do not work from ssh2 module of php. you will need to connect as the user who has permissions to the directory.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝