SQL会计到SQL数据库

时间:2017-08-17 07:10:11

标签: php mysql networking mikrotik

我需要帮助编译一个php脚本,该脚本将从我的MikroTik路由器获取IP记帐数据并将其存储到sql数据库中,

在MikroTik上,IP会计显示在cgi的Web端口上,例如。 http://routerip:webport/accounting/ip.cgi

每次请求ip.cgi后,路由器都会自动清除所有数据。

在ip.cgi上显示数据:

196.10.52.57 192.168.1.60 456 6 * *
157.240.1.32 192.168.2.16 612 6 * *
192.168.1.23 38.90.226.38 2124 15 * *
23.21.244.249 192.168.1.23 6219 13 * *
157.240.1.18 192.168.1.23 9881 27 * *
192.168.1.23 23.21.244.249 1987 20 * *

第一个ip是src地址,第二个ip是dst地址,下一个数字是传输的字节数,最后一个数字是传输的数据包。不需要星星,我甚至都不知道它们的用途。

到目前为止,我已将此代码连接到数据库,但无法弄清楚如何从ip.cgi页面提取信息并将其存储到数据库中

<?php

$SQLserver = "localhost";
$SQLusername = "root";
$SQLpassword = "sqlpassword";
$SQLdatabase = "sqldatabase";



$RouterIP = "192.168.1.1";
$WebPort = "81";
$AccountingLocation = "accounting/ip.cgi";

$routerconnect = "http://$RouterIP:$WebPort/$AccountingLocation";

$orig = file_get_contents($routerconnect);
$a = htmlentities($orig);

$conn = mysqli_connect($SQLserver, $SQLusername, $SQLpassword, 
$SQLdatabase);
if (!$conn) {
    die("Could not connect: " . mysqli_connect_error());
}
$sql = "INSERT INTO accounting (src_address, dst_address, bytes, packets)
VALUES ('1.1.1.1', '2.2.2.2', '3', '4')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);

?>  

我将这个php脚本添加到一个cron作业,每5分钟运行一次,以存储我的OSPF网络的记帐数据,所有记帐都在我的核心mikrotik路由器上完成。

1 个答案:

答案 0 :(得分:1)

Once you've pulled the data with file_get_contents() into your $orig variable, you'll need to parse it out:

foreach ( explode( "\n", $orig ) as $line ) {
    if ( trim( $line )) {
        list( $src, $dst, $bytes, $packets ) = explode( ' ', trim( strip_tags( $line )));

        // Now $src, $dst, $bytes, and $packets contain your data
        $sql = "INSERT INTO accounting (src_address, dst_address, bytes, packets) VALUES ('$src', '$dst', '$bytes', '$packets')";

        // Then the rest of your code to execute the query goes here
    }
}

This will break the result into individual lines, then break the lines into pieces (assuming that the pieces are separated by spaces as it appears they are in your question). From there, you can handle the SQL part that you've already written.

Check into the documentation for list,了解有关该处发生的更多信息。