Scheduled scripts executing with CRON and created web page with parsed data. Part 10 of 11.

Scheduled scripts executing with CRON and created web page with parsed data. Part 10 of 11.

It's almost done to create app that is parsing access.log, inserting parsed data into DB and then showing it in web page.

In this silent video my steps to automate scripts executing with scheduler - CRON. Next - is creating web page, that selecting data from DB and building web page with selected data using php.

To be honest, using php wasn't necessary, as there is no full interaction with user.

This web page get it's appearance and data once a day and remains unmutable till dusk came. It might be done with bash scripts too, but I wanted to try php in action a little.

Also here I recorded how HTTP port was opened in my WiFi router and how I creted virtual host to store more than only one web sites on my server.

Settings in CRON:

00 00 * * * /home/artem/parseAccessLogToDB.sh
00 01 * * * /home/artem/insertAccessToWebAccess.sh
00 02 * * * rm /var/log/apache2/error.log.*.gz
30 02 * * * rm /var/log/apache2/access.log.*.gz        

Every midnight scripts awake and firstly: parse access log and insert it into DB, then select data from main table and insert it into web_access table. After that scripts cleans log files in order to save space. In real project delay between starting every new script is about half an hour.

My php page:

<!DOCTYPE html>
<?php
	$host="localhost";
	$user="user";
	$password="password";
	$dbname="logs";
	$charset="utf8mb4";
	$requestArray=array();
	$sql="SELECT request, quantity FROM web_access";
	$db=new mysqli($host, $user, $password, $dbname);
	$db->set_charset($charset);
	$result=$db->query($sql);
	$lang = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
	if($lang=='ru') {
		echo '
			<html lang="ru">
				<head>
					<meta name="viewport" content="width=device-width, initial-scale=1">
					<title>Реальные кибератаки и вредоносные запросы скан-ботов на веб-сервер</title>
					<meta name="description" content="Представленный перечень - это атаки и вредоносные запросы к серверу этого сайта. Система записывает, фильтрует и вносит их в таблицу. Обновляется ежедневно.">
					<meta name="keywords" content="скан бот, кибератака, безопасность, взлом, анализ данных, защита данных, сетевая безопасность, угрозы кибербезопасности, информационная безопасность">';
	} else {
		echo '
			<html lang="en">
			<head>
					<meta name="viewport" content="width=device-width, initial-scale=1">
					<title>Real cyber attacks and scanbots malicious requests to web server</title>
					<meta name="description" content="Presented data is real cyber attacks and malicious requests to the server of this site. The system records, filters and adds them to the table. Updated daily.">
					<meta name="keywords" content="cyber attack, malicious, server, cyber security, data analysis, information security">';
	}
	echo '
			<style>
				.container {
					width: 100%;
					max-width: 1200px;
					margin: 0 auto;
					-webkit-text-size-adjust:none;
				}
				table {
					border-collapse: collapse;
				}
				th {
					vertical-align: middle;
					text-align: center;
					font-weight: bold;
					border: 1px solid green;
					border-top: 1px solid green;
				}
				th:first-child {
					width: 85%;
				}
				tr:nth-child(even) {
					background-color: rgba(176, 224, 230, 0.3);
				}
				.request {
					vertical-align: middle;
					text-align: left;
					word-break: break-all;
					border: 1px solid green;
				}
				.quantity {
					vertical-align: middle;
					text-align: center;
					border: 1px solid green;
				}
			</style>
		</head>
		<body>
			<div class="container">';
	if($lang=='ru') {
		echo '<h1>Реальные кибератаки и вредоносные запросы скан-ботов на веб-сервер</h1>
					<p>
						Обеспечение безопасности и предотвращение взломов – важные аспекты сетевой 
						и информационной безопасности. Заранее зная об известных угрозах кибербезопасности, 
						мы получаем время и возможность для подготовки к ним. На сайте представлен 
						перечень реальных запросов скан-ботов и кибератак на сервер. 
					</p>
					<p>
						Этот сайт состоит всего из одной страницы и находится на веб-сервере, на котором больше ничего нет. 
						Вебсервер постоянно получает запросы от вредоносных скан-ботов.
						Все запросы в таблице ниже, отличные от <i>/</i>, <i>index</i>, <i>favicon.ico</i>, 
						<i>sitemap.txt</i> и <i>robots.txt</i>, являются атаками на этот сервер, рассчитанные на поиск 
						определенных уязвимостей, попытку вытащить ценную информацию, или нанести вред вроде стирания всех 
						данных. 
					</p>
					<p>
						В операционной системе реализовано приложение, которое собирает и записывает эти запросы, после 
						чего формирует представленную ниже таблицу. Проводя анализ данных, представленных 
						здесь, можно своевременно определить угрозы и обеспечить информационную 
						безопасность своих ресурсов.Также разбор этих запросов может быть полезен для общего понимания 
						известных уязвимостей в системах управления контентом или управления базами данных. 
					</p>
					<p>
						Сайт ежедневно обновляется, новые атаки и запросы добавляются в список. 
					</p>';
	} else {
		echo '<h1>Real cyber attacks and scanbots malicious requests to web server</h1>
			<p>
				Ensuring security and preventing hacking are important aspects of network
				and information security. Knowing in advance about known cybersecurity threats
				gives us time and opportunity to prepare for them. The site contains
				a list of real requests from scan bots and cyber attacks on the server. 
			</p>
			<p>
				This site consists of single page, and located on web server with no more data or apps. 
				Web server constantly requested by malicious scan bots. 
				All queries in the table below other than <i>/</i>, <i>index</i>, <i>favicon.ico</i>, 
				<i>sitemap.txt</i> and <i>robots.txt</i>,	are attacks on this server aimed on  particular 
				vulnerabilities, attempts to get users data or cause damage like erase all from server. 
			</p>
			</p>
				In operating system developed an app which gathered and remembered this requests, forming table below. 
				By analyzing the data presented here, you can analyze threats in a timely manner 
				and ensure the information security of your resources. 
			</p>
			<p>
				The site is updated daily, new attacks and requests are added to the table.
			</p>';
	}
	echo "<table><thead>";
	if($lang=='ru') {
		echo "<tr><th>Запрос</th><th>Количество</th></tr>";
	} else {
		echo "<tr><th>Request</th><th>Quantity</th></tr>";
	}
	echo "</thead><tbody>";
	while($row=$result->fetch_assoc()) {
		echo "<tr><td class=\"request\">";
		echo htmlspecialchars($row['request']);
		echo "</td><td class=\"quantity\">";
		echo $row['quantity'];
		echo "</td></tr>";
	}
	echo "</tbody></table></div></body></html>";
?>        

Interesting thing here might be about "lang" variable. PHP asks server - what language prefers browser that sends request and if it was Russian, then page in Russian language developed and send back, in other cases - it's English.

Maybe this is the moment why php was good idea to use here.

Another interesting thing here is

word-break: break-all;        

in CSS. This option needed in case, when too long one word requests (set of symbols without spaces or other breaks) appears (and they do appears...) because, if they stays unbroken, then web table became less readable and beautiful...

To view or add a comment, sign in

More articles by Artem Dektiarenko

Insights from the community

Others also viewed

Explore topics