linux 以超级用户的身份从Laravel代码中运行命令

drnojrws  于 5个月前  发布在  Linux
关注(0)|答案(1)|浏览(78)

所以我试图让一个进程作为一个超级用户从一个php代码中运行,使用ssh2函数:

$commande='sudo systemctl restart kannel.service';
        $con=ssh2_connect($host,$port);
        $con2=ssh2_auth_password($con,$user,$password);
        if(ssh2_exec($con,$commande)) session()->flash('success','Success!!');
        else session()->flash('success','ERROR');

字符串
所以我的问题基本上是,如果我想运行systemctl restart kannel.service作为超级用户,提示用户输入超级用户密码时,我应该怎么做?我没有打算在脚本中存储密码。

$commande='sudo systemctl restart kannel.service';
        $con=ssh2_connect($host,$port);
        $con2=ssh2_auth_password($con,$user,$password);
        if(ssh2_exec($con,$commande)) session()->flash('success','Success!!');
        else session()->flash('success','ERROR');


我试着这么做,但没有成功。

sr4lhrrt

sr4lhrrt1#

您可以将流设置为阻塞模式,以确保PHP脚本等待命令完成,这样您就可以正确捕获任何输出/错误。

$command = 'sudo systemctl restart kannel.service';
$connection = ssh2_connect($host, $port);

if (ssh2_auth_password($connection, $user, $password)) {
    $stream = ssh2_exec($connection, $command);
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream, true);

    $output = stream_get_contents($stream);
    $errorOutput = stream_get_contents($errorStream);

    fclose($errorStream);
    fclose($stream);

    if ($output) {
        session()->flash('success', 'Success: ' . $output);
    } else {
        session()->flash('error', 'Error: ' . $errorOutput);
    }
} else {
    session()->flash('error', 'SSH Authentication Failed');
}

字符串

相关问题