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.

5
  • I've tried both ways using path and simply command. Commented Sep 11, 2018 at 12:57
  • I'm accessing the server using root user... some basic commands are working fine ... for example ls, pwd etc. Commented Sep 11, 2018 at 13:06
  • Got nothing .... same issue Commented Sep 11, 2018 at 13:42
  • iptables needs to run as root or via sudo. Commented Sep 11, 2018 at 14:32
  • accessing server by root user Commented Sep 12, 2018 at 4:52

3 Answers 3

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";
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

accessing server by root user
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.