How to check if a connection is "sleeping" in php?

1

I have the following script:

$fp = @fsockopen($IPAddress, $newport, $errno, $errstr, (float) 0.5);

if ($fp) {
    echo("Conectado\n");
} else {
    echo("Desconectado\n");
}

This script checks if a particular port is open, works fine.

I use this script for a connection via SSH, so I open a tunnel and I can "talk" to the database on another server.

The tunnel stays active while I do not end the corresponding SSH pid.

But even with the tunnel active, if I spend some time I can not connect the database anymore, having to finish the tunnel and refine it, then I access the base normally.

The detail is that the creation of the tunnel takes because the networks that need to talk are slow, I would like to keep the tunel active and to be able to access the base through it.

The full script below:

    <?php

// debug temporario
ini_set('display_errors', 1);
ini_set('display_startup_erros', 1);
error_reporting(E_ALL);

try {

    $host = 'IP_EXTERNO';
    $sshuser = 'user';
    $sshpass = 'senha';
    $dbuser = 'postgres';
    $dbpass = 'dbpass';
    $dbname = 'basename';
    $intranet = "IP_INTERNO";
    $newport = "NOVA_PORTA";
    $oldport = "PORTA_PADRAO";

    $IPAddress = "localhost";

    $fp = @fsockopen($IPAddress, $newport, $errno, $errstr, (float) 0.5);

    if ($fp) {
        echo("Conectado\n");
    } else {
        echo("Desconectado\n");
    }

    if (!$fp) {

        $command = "expect -c 'spawn ssh -f " . $sshuser . "@" . $host . " -L " . $newport . ":" . $intranet . ":" . $oldport . " -N; expect " . '"assword:"' . "; send " . '"' . $sshpass . '\r"' . "; expect send " . '"exit\r"' . "'";
        $res = shell_exec($command);
    } else {

        $res = true;

        fclose($fp);
    }

    if ($res) {
        $dbh = new PDO('pgsql:host=localhost;port=' . $newport . ';dbname=' . $dbname . '', $dbuser, $dbpass);

        // SQL Teste
        $sth = $dbh->prepare("select * from clientes codid desc limit 1");

        $sth->execute();

        $result = $sth->fetchAll();

        print_r($result);

        $dbh = null;

        function fProcessos($sshuser, $host) {

            $output = shell_exec('ps -x');
            $array = explode("\n", $output);

            for ($i = 1; $i < count($array); $i++) {
                $pos = strpos($array[$i], "ssh -f $sshuser@$host");
                if ($pos !== false) {
                    $id = substr($array[$i], 0, strpos($array[$i], ' ?'));
                    shell_exec('kill -9 ' . $id);
                }
            }
        }

        fProcessos($sshuser, $host);
    } else {
        echo("não passou\n");
    }
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "\n";
    die();
}

This script will run every 1 / 2h via cron, not via browser.

I have already researched a persistent connection, but I have not seen it as a solution since the script will run only once and has no subprocesses.

    
asked by anonymous 06.09.2018 / 20:04

1 answer

1

Actually this tunnel has nothing to do with PHP, PHP only runs the SSH daemon to create the tunnel, you must add some parameters to the command inside your shell_exec to keep the tunnel active.

  

ServerAliveCountMax Sets the number of active server messages (see below) that can be sent without any ssh receiving any   message back from the server. If this limit is reached while the   messages are being sent, ssh will be   disconnected from the server by logging off. It is important to observe   that the use of active server messages is very different from the   TCPKeepAlive (below). Messages from the active server are sent   encrypted channel and therefore can not be falsified. THE   TCP keepalive option enabled by TCPKeepAlive is spoofable. The mechanism   of the active server is valuable when the client or server depends on   know when a connection has become inactive.

     

The default value is 3. If, for example, ServerAliveInterval (see below)   is set to 15 and ServerAliveCountMax is left in the default,   if the server does not respond, ssh will be disconnected after   approximately 45 seconds. This option applies only to the   protocol 2.

     

ServerAliveInterval Defines a timeout interval in seconds, after which, if no data has been received from the server,   ssh (1) will send a message over the encrypted channel to request   response from the server. The default is 0, indicating that these messages   will not be sent to the server. This option only applies to the   protocol version 2.

     

-N Does not execute a remote command. This is useful only for forwarding ports (protocol version 2 only).

     

-T Disables pseudo-tty allocation.

     

-R [bind_address:] port: host: hostport   Specifies that the port provided on the remote host (server) should be forwarded to the host and port provided on the local side. This works by assigning a socket to listen to the port on the remote side, and whenever a connection is made to this port, the connection is routed through the secure channel, and a connection is made to host hostport port of the local machine. / p>      

Port forwarding can also be specified in the configuration file. Privileged ports can only be forwarded when logging in as root on the remote machine. IPv6 addresses can be specified by placing the address in brackets or using an alternate syntax: [bind_address /] host / port / hostport.

     

By default, the listening socket on the server will be bound only to the loopback interface. This can be overridden by specifying a bind_address. An empty bind_address, or the address '*', indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the GatewayPorts server option is enabled (see sshd_config (5) ). / p>

If the port argument is '0', the listening port will be dynamically allocated on the server and reported to the client at runtime.

Example:

sshpass -p senha ssh -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -N -T -R porta:127.0.0.1:22 user@host

There are other ways you can execute commands on the remote machine, you can open the port on your PGSQL server and manage the connections via the user, where you will perform better in your PHP code, shell_exec function in addition to using a lot of machine resources, it is slow to execute shell commands.

Another simpler and more effective way is to create a block with the commands you want to run on the remote machine in a text file, copy that file with scp and via ssh run it on remote machine.

    
04.10.2018 / 21:25