簡體   English   中英

使用ssh2_exec遠程執行sh腳本時,PHP無法正常工作

[英]PHP is not working while executing sh script remotely using ssh2_exec

我有一個shell腳本makedir.sh ,如下所示。

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

我已授予用戶testuser特權以sudo執行shell腳本,但無需詢問密碼。為此,我在/etc/sudoers文件中添加以下行,

testuser ALL=(ALL) NOPASSWD: ALL

它可以很好地工作,我可以使用sudo運行命令,而無需詢問密碼。 上面的shell腳本在不詢問密碼的情況下也可以正常工作,在/usr/local創建目錄testdir 我的問題從這里開始。 我想從php文件運行此shell腳本。 在當前情況下,shell腳本位於IP地址為10.3.2.0的遠程計算機中。 以下是我的php代碼,但是在運行此php代碼時,它沒有在/usr/local/創建任何目錄(testdir)。 請指教,因為我是PHP初學者。

PHP代碼

<?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;
    }
}

?>

外殼腳本makedir.sh (位於10.3.2.0-與上面的Shell腳本相同)

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

謝謝。

據我所知,sudo命令不適用於php的ssh2模塊。 您將需要以具有目錄權限的用戶身份連接。

好吧...問題是一年前的xD,但我仍然可能會中止使用sudo和ssh2_exec,您需要一點技巧。 這是不安全的,不建議使用,但是如果您沒有其他選擇,請使用

ssh2_exec($connection, "echo sudopw | yourscript.sh" . PHP_EOL);

並且您的腳本必須使用-S參數調用sudo

"sudo -S mkdir folder"

應該管用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM