from jinja2 import Environment, FileSystemLoader import platform import subprocess import psutil import time from datetime import datetime def get_pkg_count(): result = subprocess.run(["pkg", "stats", "-ql"], stdout=subprocess.PIPE) for r in result.stdout.decode("utf-8").strip("\n").split("\n\t"): if r.startswith("Installed packages: "): return r.split(": ")[1] def get_uptime(): result = subprocess.run(["sysctl", "-a"], stdout=subprocess.PIPE) for r in result.stdout.decode("utf-8").strip("\n").split("\n"): if r.startswith("kern.boottime"): boot = datetime.fromtimestamp(int(r.split(" ")[4].strip(","))) now = datetime.fromtimestamp(time.time()) delta = now - boot days = delta.days hour = delta.seconds // 3600 seconds = (delta.seconds % 3600) // 60 return days, hour, seconds def get_mem_total(): mem = dict(psutil.virtual_memory()._asdict()) return int(mem["total"] / 1024.0 / 1024.0) def get_mem_used(): mem = dict(psutil.virtual_memory()._asdict()) return int(mem["used"] / 1024.0 / 1024.0) def parse_template(): environment = Environment(loader=FileSystemLoader("/var/www/cgit.jinwei.me/template/")) template = environment.get_template("index.jinja2") content = template.render( UP_DAYS = get_uptime()[0], UP_HOUR = get_uptime()[1], UP_MINS = get_uptime()[2], NB_PACKAGES = get_pkg_count(), MEM_IN_USE = get_mem_used(), MEM_IN_TOTAL = get_mem_total(), OS=platform.system(), VERSION=platform.release(), ARCH = platform.machine() ) with open("/var/www/cgit.jinwei.me/index.html", mode="w", encoding="utf-8") as f: f.write(content) f.close() if __name__ == "__main__": parse_template()