webcron/Scripts/update-database.py

52 lines
1.3 KiB
Python
Raw Normal View History

#!/usr/bin/python
import sqlite3
from pathlib import Path
dirs = (
'/etc/cron.d/',
'/etc/cron.hourly',
'/etc/cron.daily',
'/etc/cron.monthly',
'/var/spool/cron/crontabs'
)
fs_files = dict()
db_files = dict()
# Get crontabs from each crontab directory (if it exists)
for dir in [ Path(dir) for dir in dirs ]:
if dir.exists():
for fs_file in dir.iterdir():
if fs_file.is_file():
with fs_file.open('r') as file:
fs_files.update({str(fs_file.absolute()):file.read()})
conn = sqlite3.connect('../webcron.db')
cur = conn.cursor()
# Get the path and data of each of the crontabs in the db
cur.execute("SELECT crontab_path, crontab_data FROM crontabs")
for path, data in cur.fetchall():
db_files.update({path:data})
# Put files into db if they do not exist there already
for file_path, file_data in fs_files.items():
if file_path not in db_files:
cur.execute("INSERT INTO crontabs (crontab_path, crontab_data) VALUES (?,?)",(file_path, file_data,))
else:
if file_data != db_files[file_path]:
cur.execute("UPDATE crontabs SET crontab_data = ? WHERE crontab_path = ?",(file_data, file_path,))
# Commit changes from memory into db-file
conn.commit()