PHP ssh2_exec()未执行iptables命令

时间:2018-09-11 12:37:06

标签: php linux

我想在远程服务器上执行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);

服务器连接和身份验证绝对可以。但是命令输出 为空白,除基本命令外,基本上不执行命令。

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

之所以发生这种情况,是因为对stream_set_blocking()的调用改变了fread()的行为。您可以将代码更改为如下所示:

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

echo "$data\n";

或更简单地说:

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

答案 2 :(得分:0)

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

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

www-data ALL=NOPASSWD: /sbin/iptables

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

相关问题