【问题标题】:PHP ssh2_exec() not executing iptables commandPHP ssh2_exec() 不执行 iptables 命令
【发布时间】:2019-02-15 23:17:15
【问题描述】:

我想在远程服务器上执行 iptables 命令并使用 php 打印所有 iptables 命令输出:

$connection = ssh2_connect($server_ip, $server_port);

//authenticating username and password
if(ssh2_auth_password($connection, $server_user, $server_pwd)){
    $conn_error=0;
}else{
    $conn_error=1;
}

$stream = ssh2_exec($connection, "iptables -L -n --line-number");
stream_set_blocking( $stream, true );
$data = "";
while( $buf = fread($stream,4096) ){
   $data .= $buf."<br>";
}
fclose($stream);

服务器连接和身份验证绝对没问题。但命令输出 是空白的,基本上它不执行除了基本命令之外的命令。

【问题讨论】:

  • 我已经尝试过使用路径和简单命令两种方式。
  • 我正在使用 root 用户访问服务器...一些基本命令运行良好...例如 ls、pwd 等。
  • 什么都没有......同样的问题
  • iptables 需要以 root 身份或通过sudo 运行。
  • root用户访问服务器

标签: php linux


【解决方案1】:

这是因为调用stream_set_blocking() 改变了fread() 的行为。您可以将代码更改为如下所示:

$data = '';
while (!feof($stream)) {
    $data .= fread($stream, 4096);
}

echo "$data\n";

或者,更简单地说:

$data = stream_get_contents($stream);
echo "$data\n";

【讨论】:

    【解决方案2】:

    尝试将 sudo 添加到您的命令中,因为 iptables 需要 sudo 权限。

    $stream = ssh2_exec($connection, "sudo iptables -L -n --line-number");
    

    【讨论】:

    • root用户访问服务器
    【解决方案3】:

    我发现了这背后的问题。 我们必须允许 iptables 命令用于 apache。

    1. 运行命令sudo visudo。实际上我们想编辑etc/sudoers中的文件。为此,通过在终端中使用sudo visudo,它复制(临时)sudoers文件进行编辑。
    2. 在文件的末尾,添加以下ex:-如果我们想使用命令重新启动smokeping并使用mount命令进行其他操作,

    www-data ALL=NOPASSWD: /sbin/iptables

    https://stackoverflow.com/a/22953232/5979349

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2013-04-02
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 2019-10-26
      • 2013-09-07
      相关资源
      最近更新 更多