0

I wanna execute iptables command on a remote server and print all the iptables command output using php:

$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);

server connection and authentication is absolutely fine. but command output is blank, basically its not executing commands except basic commands.

Sean Bright
  • 118,630
  • 17
  • 138
  • 146

3 Answers3

0

try adding sudo to your command as iptables require sudo permissions.

$stream = ssh2_exec($connection, "sudo iptables -L -n --line-number");
Amjad Hussain Syed
  • 994
  • 2
  • 11
  • 23
0

This is happening because of the call to stream_set_blocking() which changes the behavior of fread(). You can change your code to look something like this:

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

echo "$data\n";

Or, more simply:

$data = stream_get_contents($stream);
echo "$data\n";
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
0

I found the issue behind this. we've to allow iptables command for apache.

  1. Run the command sudo visudo. Actually we want to edit the file in etc/sudoers.To do that, by using sudo visudo in terminal ,it duplicate(temp) sudoers file to edit.
  2. At the end of the file, add the following ex:-if we want to use command for restart smokeping and mount command for another action,

www-data ALL=NOPASSWD: /sbin/iptables

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