Как запустить Скрипт PHP
-
Новичек !
Дело в том что в англоязычным форуме этого сайта нашел один скрипт, которая переключает опенВПН на резервную связь когда отпадает основной связь. А когда оно поднимается, переключает обратно на основную. Да вот не как не могу разобраться как запустить. Пожалуйста помогите.
сам скрипт
#!/usr/local/bin/php -f
require_once('config.inc');
include('openvpn.inc');if ($argc != 2)
{
echo "Usage: " . basename($argv[0]) . " <full or="" partial="" vpn="" client="" name="">\n";
exit;
}
$name = $argv[1];$msg = "Checking whether the $name VPN client needs a restart.";
echo $msg."\n";
exec("logger '$msg'");// Read in all of the OpenVPN client configs.
global $config;
if (!is_array($config['openvpn']['openvpn-client']))
{
return;
}// Find client config for given name
$found_config = false;
foreach ($config['openvpn']['openvpn-client'] as & $settings)
{
if (stripos($settings['description'], $name) !== false)
{
$found_config = true;
break;
}
}// If client config not found, exit.
if (!$found_config)
{
echo "Did not find client VPN config for "$name".\n";
exit;
}// Print the client config.
echo "\n–--Client configuration----\n";
echo "vpnid: {$settings['vpnid']}\n";
echo "description: {$settings['description']}\n";
echo "server_addr: {$settings['server_addr']}\n";
echo "custom_options: {$settings['custom_options']}\n\n";// Resolve the configured host name to an IP address.
// This is the VPN server's primary IP.
if (is_ipaddr($settings['server_addr']))
{
$ip_primary = $settings['server_addr'];
}
else
{
$ip_primary = gethostbyname($settings['server_addr']);
if ($ip_primary == $settings['server_addr'])
{
echo "DNS lookup failed for VPN server primary hostname ({$settings['server_addr']}). Exiting.\n";
exit;
}
}
echo "VPN server primary IP: $ip_primary\n";// Tokenize the custom_options to get the VPN
// server's secondary IP.
$tok = strtok($settings['custom_options'], " \n\t;");
while ($tok !== false)
{
if (strcasecmp($tok, 'remote') == 0)
{
$tok = strtok(" \n\t;");
if ($tok !== false)
{
if (is_ipaddr($tok))
{
$ip_secondary = $tok;
}
else
{
$ip_secondary = gethostbyname($tok);
if ($ip_secondary == $tok)
{
echo "DNS lookup failed for VPN server secondary hostname ($tok). Exiting.\n";
exit;
}
}
echo "VPN server secondary IP: $ip_secondary\n";
}
}
$tok = strtok(" \n\t;");
}// Find the status for the VPN client.
$found_status = false;
$clients = openvpn_get_active_clients();
foreach ($clients as $client)
{
if (stripos($client['name'], $name) !== false)
{
$found_status = true;
break;
}
}// If client status not found, exit.
if (!$found_config)
{
echo "Did not find VPN client status for "$name".\n";
exit;
}// Print the client status
echo "\n----Client status----\n";
echo "name: {$client['name']}\n";
echo "mgmt: {$client['mgmt']}\n";
echo "status: {$client['status']}\n";
echo "remote_host: {$client['remote_host']}\n";// See if the client is connected to a secondary IP.
// Note: $client['remote_host'] has trailing white space that
// we must trim before comparing to $ip_primary
$remote_host = rtrim($client['remote_host']);
if ($client['status'] == 'up' && $remote_host == $ip_primary)
{
$msg = "The $name VPN client is connected to $remote_host (VPN server primary IP). Not restarting client.";
echo $msg."\n";
exec("logger '$msg'");
exit;
}
else if ($client['status'] == 'up')
{
$msg = "The $name VPN client is connected to $remote_host (VPN server secondary IP).";
echo $msg."\n";
exec("logger '$msg'");
}
else
{
$msg = "The $name VPN client is not connected. Current status is {$client['status']}.";
echo $msg."\n";
exec("logger '$msg'");
exit;
}// If we got this far, we will want to restart the VPN client
// so it connects to primary IP instead of secondary IP.// Before trying to connect to primary IP, we have to make sure
// we can ping it. If we can't ping it, there's no sense in
// trying to connect to it. Furthermore, that is probably
// the reason why the client is currently connected to the
// secondary IP.
exec("ping -t 10 -o $ip_primary", $output, $return_var);
echo "ping return_var: $return_var\n";// A return value of 0 means at least one ping was replied to.
// In other words, the IP address is up and we should be
// able to restart to VPN to connect to it.
if ($return_var == 0)
{
$msg = "VPN server primary IP is up. Restarting $name VPN client.";
echo $msg."\n";
exec("logger '$msg'");// Restart the VPN client by mimicking the technique used in
// the file /usr/local/www/status_services.php
//openvpn_restart('client', $settings);
$configfile = "{$g['varetc_path']}/openvpn/client{$settings['vpnid']}.conf";
$pidfile = "{$g['varrun_path']}/openvpn_client{$settings['vpnid']}.pid";
if (file_exists($configfile))
{
$msg = "Terminating openvpn using pidfile: $pidfile";
echo $msg."\n";
exec("logger '$msg'");
killbypid($pidfile);
// wait for process to terminate
sleep(1);
$msg = "Starting new openvpn process using config file: $configfile";
echo $msg."\n";
exec("logger '$msg'");
mwexec_bg("/usr/local/sbin/openvpn --config {$configfile}");
}$msg = "Finished restarting $name VPN client.";
echo $msg."\n";
exec("logger '$msg'");
}
else
{
$msg = "VPN server primary IP is down. Not restarting $name VPN client.";
echo $msg."\n";
exec("logger '$msg'");
}
?></full> -
Скрипт PHP, это нормальна?
-
Доброе.
Судя из листинга скрипта он предназначен для клиентской части Openvpn. Т.е. впн-клиент переключается на 2-ой впн сервер при недоступности 1-го сервера. И не факт, что скрипт предназначен для pf. Вам это надо? Так это все и без скрипта (с нюансами) работает. Достаточно неск. директив remote и remote-random в конф. впн-клиента:Пример части конф. впн-клиента:
... remote 1.1.1.1 1194 udp remote 2.2.2.2 1194 udp remote-random ...
P.s. Обычно такие скрипты как ваш добавляются в планировщик Cron c проверкой в неск. минут.
-
remote-random для failover, наверное, лишний.
Не знаю, умеет ли cron выполнять PHP. Если да - можно поступить так:
1. Как написано по ссылке oleg1969 - создаем script.php c нужным содержимым и помещаем его НЕ в /usr/local/etc/rc.d.
chmod 755 для PHP думаю, не обязателен.
2. Устанавливаем пакет cron
3. В cron задаем выполнять script.php и периодичность его выполнения.Хотя согласен с werter,
remote 1.1.1.1 1194 udp
remote 2.2.2.2 1194 udpдолжны делать все то же самое.
-
Так как основной связь 100мбпс, а резервный 10мбпс.
Смысал в том что как только восстановливается основной, нужно переключится на него. -
@oleg1969:
Можеть быть здесь
Diagnostics / Command Prompt
Execute PHP Commands
Да не как.
выдает ошибку на 6 строке. не могу понять в чем проблема -
@oleg1969:
А если так
http://www.thin.kiev.ua/router-os/50-pfsense/600-scriptsh.html
да не пойму?
./restart-vpn-client.phpUsage: restart-vpn-client.php <full or="" partial="" vpn="" client="" name="">теперь запушен? как проверить?</full>