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.