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 given port is open, works well.
I use this script for an SSH connection, then open a tunnel and can "talk" to the database on another server.
Tunnel stays active until I finish the corresponding SSH pid.
But even with the tunnel active, if a time passes I can no longer connect the database, I have to finish the tunnel and redo it, then I can access the base normally.
The detail is that the creation of the tunnel takes time because the networks that need to talk are slow, I would like to keep the tunnel active and be able to access the base by it.
The complete 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’ve researched about persistent connection, but I didn’t see it as a solution since the script will run once and has no subprocesses.