added portfolio evidence
This commit is contained in:
80
Case study 1/scripting/monitoring/collect-to-db.py
Normal file
80
Case study 1/scripting/monitoring/collect-to-db.py
Normal file
@@ -0,0 +1,80 @@
|
||||
from flask import Flask, request, jsonify
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
DB_PATH = "metrics.db"
|
||||
|
||||
# Creates the database table if it doesn't exist
|
||||
def init_db():
|
||||
with sqlite3.connect(DB_PATH) as conn:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS metrics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
hostname TEXT,
|
||||
os TEXT,
|
||||
cpu_percent REAL,
|
||||
memory_percent REAL,
|
||||
disk_usage REAL,
|
||||
timestamp TEXT
|
||||
)
|
||||
""")
|
||||
print("Database initialized")
|
||||
|
||||
# route for sending metrics
|
||||
@app.route('/collect', methods=['POST'])
|
||||
def collect():
|
||||
data = request.get_json()
|
||||
|
||||
if not data or "hostname" not in data:
|
||||
return jsonify({"error": "Invalid data"}), 400
|
||||
|
||||
timestamp = datetime.now().isoformat()
|
||||
|
||||
with sqlite3.connect(DB_PATH) as conn:
|
||||
conn.execute("""
|
||||
INSERT INTO metrics (hostname, os, cpu_percent, memory_percent, disk_usage, timestamp)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
""", (
|
||||
data.get("hostname"),
|
||||
data.get("os"),
|
||||
data.get("cpu_percent"),
|
||||
data.get("memory_percent"),
|
||||
data.get("disk_usage"),
|
||||
timestamp
|
||||
))
|
||||
conn.commit()
|
||||
|
||||
print(f"[{timestamp}] Data received from {data.get('hostname')}")
|
||||
return jsonify({"status": "stored"}), 200
|
||||
|
||||
# for posting metrics which you can view in the browser
|
||||
@app.route('/metrics', methods=['GET'])
|
||||
def list_metrics():
|
||||
with sqlite3.connect(DB_PATH) as conn:
|
||||
cursor = conn.execute("""
|
||||
SELECT hostname, os, cpu_percent, memory_percent, disk_usage, timestamp
|
||||
FROM metrics
|
||||
ORDER BY id DESC
|
||||
LIMIT 10
|
||||
""")
|
||||
rows = cursor.fetchall()
|
||||
|
||||
results = [
|
||||
{
|
||||
"hostname": row[0],
|
||||
"os": row[1],
|
||||
"cpu_percent": row[2],
|
||||
"memory_percent": row[3],
|
||||
"disk_usage": row[4],
|
||||
"timestamp": row[5],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
return jsonify(results)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not os.path.exists(DB_PATH):
|
||||
init_db()
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
19
Case study 1/scripting/monitoring/collect-to-log.py
Normal file
19
Case study 1/scripting/monitoring/collect-to-log.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from flask import Flask, request, jsonify
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/collect', methods=['POST'])
|
||||
def collect():
|
||||
data = request.get_json()
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
with open("collected_data.log", "a") as f:
|
||||
f.write(f"{timestamp} - {json.dumps(data)}\n")
|
||||
|
||||
print(f"[{timestamp}] Data received from {data.get('hostname', 'unknown')}")
|
||||
return jsonify({"status": "success"}), 200
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=5000)
|
||||
1
Case study 1/scripting/monitoring/collected_data.log
Normal file
1
Case study 1/scripting/monitoring/collected_data.log
Normal file
@@ -0,0 +1 @@
|
||||
2025-10-28 14:55:03 - {"hostname": "hp-arch", "os": "Linux", "cpu_percent": 1.9, "memory_percent": 30.8, "disk_usage": 85.2, "time": "2025-10-28T14:55:03.021372"}
|
||||
BIN
Case study 1/scripting/monitoring/metrics.db
Normal file
BIN
Case study 1/scripting/monitoring/metrics.db
Normal file
Binary file not shown.
3
Case study 1/scripting/monitoring/prereq.txt
Normal file
3
Case study 1/scripting/monitoring/prereq.txt
Normal file
@@ -0,0 +1,3 @@
|
||||
flask
|
||||
requests
|
||||
psutil
|
||||
32
Case study 1/scripting/monitoring/send_metrics.py
Normal file
32
Case study 1/scripting/monitoring/send_metrics.py
Normal file
@@ -0,0 +1,32 @@
|
||||
import psutil
|
||||
import platform
|
||||
import requests
|
||||
import socket
|
||||
from datetime import datetime
|
||||
|
||||
SERVER_URL = "http://localhost:5000/collect"
|
||||
|
||||
def collect_metrics():
|
||||
data = {
|
||||
"hostname": socket.gethostname(),
|
||||
"os": platform.system(),
|
||||
"cpu_percent": psutil.cpu_percent(interval=1),
|
||||
"memory_percent": psutil.virtual_memory().percent,
|
||||
"disk_usage": psutil.disk_usage('/').percent,
|
||||
"time": datetime.now().isoformat()
|
||||
}
|
||||
return data
|
||||
|
||||
def send_data(data):
|
||||
try:
|
||||
response = requests.post(SERVER_URL, json=data, timeout=5)
|
||||
if response.status_code == 200:
|
||||
print("Data sent successfully")
|
||||
else:
|
||||
print("Server returned:", response.status_code)
|
||||
except Exception as e:
|
||||
print("Error sending data:", e)
|
||||
|
||||
if __name__ == "__main__":
|
||||
metrics = collect_metrics()
|
||||
send_data(metrics)
|
||||
Reference in New Issue
Block a user