template-python/script.py

108 lines
2.9 KiB
Python
Raw Normal View History

2023-01-08 16:19:45 +03:00
#!/usr/bin/env python3
2023-03-15 14:58:27 +03:00
import logging
2023-01-08 16:19:45 +03:00
from datetime import datetime
2023-03-15 14:58:27 +03:00
from getpass import getuser
from os import path, sep, chdir, devnull
from sys import platform
2023-01-08 16:19:45 +03:00
def execquite(code: int) -> None:
2023-03-15 14:58:27 +03:00
"""Exit procedure.
Args:
code (int): exitcode
2023-01-08 16:19:45 +03:00
"""
if args['show'] != 'qn':
2023-03-15 14:58:27 +03:00
input("Press [ENTER] to continue...")
global time_start
time_execute = datetime.now() - time_start
logging.info(msg='execution time is ' + str(time_execute) + '. Exit.')
2023-01-08 16:19:45 +03:00
exit(code)
def getconfig(config: str) -> dict:
2023-03-15 14:58:27 +03:00
"""Simple config reader.
Args:
config (str): custom configuration file path
Returns:
dict: dictionary as "key":"value"
2023-01-08 16:19:45 +03:00
"""
dictionary = {}
2023-03-15 14:58:27 +03:00
dictionary['log_root'] = None
2023-01-08 16:19:45 +03:00
if path.exists(config):
with open(config) as file:
raw = file.read()
for line in raw.splitlines():
2023-03-15 14:58:27 +03:00
if not line.lstrip().startswith('#') and "=" in line:
if "log_root=" in line:
dictionary['log_root'] = line.split('=')[1].strip()
2023-01-08 16:19:45 +03:00
return dictionary
2023-03-15 14:58:27 +03:00
2023-01-08 16:19:45 +03:00
def checkroot() -> bool:
2023-03-15 14:58:27 +03:00
"""Crossplatform privileged rights checker.
Returns:
bool: True - if privileged rights, False - if not privileged rights
2023-01-08 16:19:45 +03:00
"""
if platform.startswith('linux') or platform.startswith('darwin'):
from os import geteuid
if geteuid() != 0:
return False
else:
return True
elif platform.startswith('win32'):
import ctypes
return ctypes.windll.shell32.IsUserAnAdmin()
if __name__ == "__main__":
from argparse import ArgumentParser
2023-03-15 14:58:27 +03:00
global time_start
time_start = datetime.now()
2023-01-08 16:19:45 +03:00
args = ArgumentParser(
prog='script',
description='Checking privileged rights',
epilog='Dependencies: '
2023-03-15 14:58:27 +03:00
'- Python 3 (tested version 3.9.5)'
2023-01-08 16:19:45 +03:00
)
args.add_argument('-s', '--show', type=str, default=None, required=False,
help='qn - execution without pauses')
args.add_argument('-c', '--conf', type=str, default=None, required=False,
help='path to configuration file')
args = vars(args.parse_args())
2023-03-15 14:58:27 +03:00
conf = path.abspath(__file__).replace('.py', '.conf')
if args['conf']:
2023-01-08 16:19:45 +03:00
conf = args['conf']
conf = getconfig(conf)
2023-03-15 14:58:27 +03:00
log_path = devnull
if conf['log_root']:
log_path = conf['log_root'] + sep + path.splitext(path.basename(__file__))[0] + '.log'
logging.basicConfig(
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d_%H.%M.%S',
handlers=[
logging.FileHandler(
filename=log_path,
mode='a'
),
logging.StreamHandler()
],
level='INFO'
)
2023-01-08 16:19:45 +03:00
chdir(path.split(path.abspath(__file__))[0])
if checkroot():
print('Running as', getuser())
execquite(0)
else:
2023-03-15 14:58:27 +03:00
logging.warning(msg='Restart this as root!')
execquite(1)