+ install as service

This commit is contained in:
iu 2024-05-10 18:53:36 +00:00
parent 06c39f73fe
commit 929a1ec8ea
1 changed files with 68 additions and 8 deletions

View File

@ -4,6 +4,48 @@ from datetime import datetime, timedelta
import logging import logging
import argparse import argparse
import time import time
import sys
import shutil
import os
DST_FILE_NAME = "/usr/setcamtime"
SERVICE_FILENAME = "/etc/systemd/system/setcamtime.service"
SERVICE_TEMPLATE = """
[Unit]
Description=Webcam time sync service
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=%CMDLINE%
[Install]
WantedBy=multi-user.target
"""
def install_service():
uninstall_service()
# if not os.path.isfile(DST_FILE_NAME):
os.system("systemctl stop setcamtime")
os.system("systemctl disable setcamtime")
shutil.copy(sys.argv[0], DST_FILE_NAME)
service = SERVICE_TEMPLATE.replace(
"%CMDLINE%",
f"{DST_FILE_NAME} -d -a {args.address} -p {args.port} -s {args.hysteresis} -l {args.login} -w {args.password} -i {args.interval}",
)
with open(SERVICE_FILENAME, "w", encoding="UTF-8") as f:
f.write(service)
os.system("systemctl enable setcamtime")
os.system("systemctl start setcamtime")
def uninstall_service():
os.system("systemctl stop setcamtime")
os.system("systemctl disable setcamtime")
if os.path.exists(SERVICE_FILENAME):
os.remove(SERVICE_FILENAME)
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
# logging.basicConfig(filename='app.log', level=logging.INFO) # logging.basicConfig(filename='app.log', level=logging.INFO)
@ -16,18 +58,18 @@ logging.basicConfig(
) )
def setCamTime(cam_addr: str, port: int, hysteresis: int, login:str, password:str): def setCamTime(cam_addr: str, port: int, hysteresis: int, login: str, password: str):
with Telnet(cam_addr, port) as tn: with Telnet(cam_addr, port) as tn:
tn.read_until(b"login: ") tn.read_until(b"login: ")
tn.write((login+"\n").encode("ascii")) tn.write((login + "\n").encode("ascii"))
tn.read_until(b"Password:") tn.read_until(b"Password:")
tn.write((password+"\n").encode("ascii")) tn.write((password + "\n").encode("ascii"))
# tn.read_until(b"[/app]#") # tn.read_until(b"[/app]#")
r = tn.expect([b"\[/app\]\#", b"Login incorrect"]) r = tn.expect([b"\[/app\]\#", b"Login incorrect"])
if r[0] != 0: if r[0] != 0:
log.error('Ошибка аутентификации') log.error("Ошибка аутентификации")
return return
now = datetime.now() + timedelta(hours=3) now = datetime.now()# + timedelta(hours=3)
tn.write("date +%Y%m%d%H%M%S\n".encode("ascii")) tn.write("date +%Y%m%d%H%M%S\n".encode("ascii"))
ds = tn.read_until(b"[/app]#").decode("ascii").split("\n")[1].strip() ds = tn.read_until(b"[/app]#").decode("ascii").split("\n")[1].strip()
d = datetime.strptime(ds, "%Y%m%d%H%M%S") - timedelta(hours=5) d = datetime.strptime(ds, "%Y%m%d%H%M%S") - timedelta(hours=5)
@ -54,8 +96,15 @@ parser.add_argument(
parser.add_argument("-a", "--address", type=str, help="Camera address", required=True) parser.add_argument("-a", "--address", type=str, help="Camera address", required=True)
parser.add_argument("-p", "--port", type=int, help="Camera port", default=23) parser.add_argument("-p", "--port", type=int, help="Camera port", default=23)
parser.add_argument("-d", "--daemon", action="store_true", help="daemon mode") parser.add_argument("-d", "--daemon", action="store_true", help="daemon mode")
parser.add_argument("-l", "--login", type=str, help="login", default='root') parser.add_argument("-l", "--login", type=str, help="login", default="root")
parser.add_argument("-w", "--password", type=str, help="password") parser.add_argument("-w", "--password", type=str, help="password", required=True)
parser.add_argument(
"--install", action="store_true", help="Инсталлировать сервис (systemd)"
)
parser.add_argument(
"--uninstall", action="store_true", help="Деинсталлировать сервис (systemd)"
)
parser.add_argument( parser.add_argument(
"-i", "-i",
"--interval", "--interval",
@ -65,6 +114,15 @@ parser.add_argument(
) )
args = parser.parse_args() args = parser.parse_args()
if args.uninstall:
uninstall_service()
exit(0)
if args.install:
install_service()
exit(0)
if not args.daemon: if not args.daemon:
setCamTime(args.address, args.port, args.hysteresis, args.login, args.password) setCamTime(args.address, args.port, args.hysteresis, args.login, args.password)
else: else:
@ -72,7 +130,9 @@ else:
while True: while True:
log.info(f"Старт синхронизации времени") log.info(f"Старт синхронизации времени")
try: try:
setCamTime(args.address, args.port, args.hysteresis, args.login, args.password) setCamTime(
args.address, args.port, args.hysteresis, args.login, args.password
)
except Exception as e: except Exception as e:
log.error(f"Ошибка синхронизации времени {e}") log.error(f"Ошибка синхронизации времени {e}")
log.info(f"Ожидание {args.interval}сек.") log.info(f"Ожидание {args.interval}сек.")