Monitoring Samba from a web page using smbstatus

A long time ago, I found that I needed something to be able to see which users are logged in using samba and kick users as necessary. The usual way is to check the currently logged in users using smbstatus and kicking users by killing the smb process belonging to a user. To make this a bit easier, I made a small webpage in *cough*PHP*cough*. Hey, it was 2 years ago! :) Anyway, I still find it very useful, so maybe it’s useful to you, too.

<?
error_reporting(0);

if(isset($_GET['kill'])){
	echo shell_exec("sudo /scripts/smbkill ".$_GET['kill']." 2>&1");
	}

exec("smbstatus -S",$log);
exec("smbstatus -L",$lock);

$pid_us = array();
for($i=3;$i<sizeof($log);$i++)
	if(!trim($log[$i])=="") {
		$users[] = split("[ ]+",$log[$i],4);
		$pid_us[$users[sizeof($users)-1][1]] = $users[sizeof($users)-1][2];
		}
for($i=3;$i<sizeof($lock);$i++)
	if(!trim($lock[$i])=="") {
			$line = split("[ ]+",$lock[$i],7);
			$usr = $pid_us[$line[0]];
			if(trim($usr)=="") $usr = $line[0];
			$locks[$line[0]][] = array($line[0],$usr,substr_replace($line[6],"",-25));	//Remove date (25 chars from the right
		}

//die("");

echo "<br />";
echo "<font style=\"font-family: Verdana;\">Connected users:</font>\n";
echo "<br /><br />";
echo "<table>\n";
foreach($users as $user){
	list($service,$pid,$mach,$date) = $user;
	echo "<tr\n>";
	echo "<td><a onclick=\"return confirm('Kick this user?');\" href=\"".$PHP_SELF."?kill=".$pid."\"><img border=\"0\" src=\"remove.gif\" /></a></td>\n";
	echo "<td class=\"user\">".$mach."</td>\n";
	echo "<td class=\"pid\">".$pid."</td>\n";
	echo "<td>".$service."</td>\n";
	echo "<td>".$date."</td>\n";
	echo "</tr>\n";
}
echo "</table>\n\n";

echo "<br /><br />";
echo "<font style=\"font-family: Verdana;\">Locked files:</font>\n";
echo "<br /><br />";
echo "<table>\n";

$cuser = "";
$first = true;
foreach($locks as $l){
	foreach($l as $lck){
		list($pid, $user,$file) = $lck;
		if($user != $cuser){
			if(!$first){
				echo "<tr>\n";
				echo "<td>&nbsp;</td>\n";
				echo "<td>&nbsp;</td>\n";
				echo "<td>&nbsp;</td>\n";
				echo "</tr>\n";
				}
			echo "<tr>\n";
			echo "<td class=\"pid\"><a onclick=\"return confirm('Kick this user?');\" href=\"".$PHP_SELF."?kill=".$pid."\"><img border=\"0\" src=\"remove.gif\" /></a> ".$pid."</td>\n";
			echo "<td class=\"user\">".$user."</td>\n";
			echo "<td>".$file."</td>\n";
			echo "</tr>\n";
			$cuser = $user;
			}
		else {
			echo "<tr>\n";
			echo "<td>&nbsp;</td>\n";
			echo "<td>&nbsp;</td>\n";
			echo "<td>".$file."</td>\n";
			echo "</tr>\n";
			}
		$first = false;
		}
}
echo "</table>\n";
?>

Note that you should of course make sure that only you are able to access the page and execute the kill command, so you’ll need to get creative with sudo and htaccess ;)

Image used: remove

~ by moiristo on December 14, 2008.

Leave a Reply