Skip to content

Instantly share code, notes, and snippets.

@entomb
Last active December 22, 2015 19:59
Show Gist options
  • Save entomb/6523757 to your computer and use it in GitHub Desktop.
Save entomb/6523757 to your computer and use it in GitHub Desktop.
PHP cron script to parse nix `df` commands and save its outputs into a mysql table. useful for mount usage logs on remote servers. Data can be then read and displayed as you like
<?php
/**
* PHP df command parser
*
* @author Jonathan Tavares
*/
/**
* MySQL Configuration
*/
$Config = array(
'host' => "localhost",
'user' => "YOUR_USERNAME",
'pass' => "YOUR_PASSWORD",
'database' => "YOUR_DATABASE",
'table' => "YOUR_TABLE",
);
/**
* MySQL table creation
CREATE TABLE `disks` (
`df_read_id` int(11) NOT NULL AUTO_INCREMENT,
`date` datetime DEFAULT NULL,
`disk` varchar(50) DEFAULT NULL,
`mount` varchar(50) DEFAULT NULL,
`type` varchar(10) DEFAULT NULL,
`mb_total` int(11) DEFAULT NULL,
`mb_used` int(11) DEFAULT NULL,
`mb_free` int(11) DEFAULT NULL,
`percent` int(3) DEFAULT NULL,
PRIMARY KEY (`df_read_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
*/
$df = array();
echo "reading `df` command \n";
exec("df -T -x tmpfs -x devtmpfs -P -B 1G",$df);
array_shift($df);
$Stats = array();
foreach($df as $disks){
$split = preg_split('/\s+/', $disks);
$Stats[] = array(
'disk' => $split[0],
'mount' => $split[6],
'type' => $split[1],
'mb_total' => $split[2],
'mb_used' => $split[3],
'mb_free' => $split[4],
'percent' => $split[5],
);
}
if($link = mysqli_connect($Config['host'],$Config['user'],$Config['pass'])){
if(mysqli_select_db($link,$Config['database'])){
$_table = mysqli_real_escape_string($link,$Config['table']);
foreach($Stats as $row){
$_disk = mysqli_real_escape_string($link,$row['disk']);
$_mount = mysqli_real_escape_string($link,$row['mount']);
$_type = mysqli_real_escape_string($link,$row['type']);
$_mb_total = (int)$row['mb_total'];
$_mb_used = (int)$row['mb_used'];
$_mb_free = (int)$row['mb_free'];
$_percent = (int)$row['percent'];
$ok = mysqli_query($link,"INSERT INTO `$_table`
VALUES (null, NOW(),
'$_disk',
'$_mount',
'$_type',
'$_mb_total',
'$_mb_used',
'$_mb_free',
'$_percent'
)");
if(!$ok){
echo "could not insert data for $_disk " . mysqli_error($link). "\n";
}else{
echo $_disk . " stats saved \n";
}
}
}else{
die("could not connect to database: " . mysqli_error($link). "\n");
}
}else{
die("could not connect to server \n");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment