Bu basit Python betiği, herhangi bir SystemD servis dosyasındaki TimeoutStartSec değerini otomatik olarak değiştirir.
Şu şekilde çağırın:
ensure_timeout_start_usage.sh
python ensure_timeout_start.py /etc/systemd/system/mynodejs.serviceTam kaynak kodu
ensure_timeout_start.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ensure_timeout_start.py
This work is dedicated to the public domain under the Creative Commons "CC0 1.0 Universal" (CC0 1.0) public domain dedication.
Author: Uli Köhler
SPDX-License-Identifier: CC0-1.0
systemd birim dosyalarının [Service] bölümünde TimeoutStartSec=600 olmasını sağlar.
- [Service] eksikse eklenir.
- TimeoutStartSec varsa (herhangi bir değer), 600 olarak ayarlanır.
- TimeoutStartSec eksikse [Service]'e eklenir.
Kullanım:
python ensure_timeout_start.py my1.service my2.service
python ensure_timeout_start.py /etc/systemd/system/*.service --dry-run
"""
import argparse
import os
import shutil
import sys
from configupdater import ConfigUpdater
def ensure_timeout_start(filepath: str, value: str = "600", dry_run: bool = False, backup_ext: str = ".bak") -> bool:
"""
Değişiklik gerekiyorsa (dry-run'da yapıldıysa veya yapılacaksa) True, zaten uygunsa False döndürür.
"""
updater = ConfigUpdater()
try:
updater.read(filepath, encoding="utf-8")
except FileNotFoundError:
print(f"ERROR: File not found: {filepath}", file=sys.stderr)
return False
changed = False
# [Service] bölümünün var olduğundan emin ol
if not updater.has_section("Service"):
updater.add_section("Service")
changed = True
service = updater["Service"]
if service.has_option("TimeoutStartSec"):
current_val = service.get("TimeoutStartSec").value.strip()
if current_val != value:
service["TimeoutStartSec"].value = value
changed = True
else:
service["TimeoutStartSec"] = value
changed = True
if dry_run:
return changed
if changed:
# Üzerine yazmadan önce yedek oluştur
if backup_ext:
backup_path = filepath + backup_ext
shutil.copy2(filepath, backup_path)
tmp_path = filepath + ".tmp"
with open(tmp_path, "w", encoding="utf-8", newline="") as f:
updater.write(f)
try:
st = os.stat(filepath)
os.chmod(tmp_path, st.st_mode)
try:
os.chown(tmp_path, st.st_uid, st.st_gid) # root gerektirebilir
except PermissionError:
pass
except FileNotFoundError:
pass
os.replace(tmp_path, filepath)
return changed
def main():
parser = argparse.ArgumentParser(
description="Bir veya daha fazla systemd birim dosyasının [Service] bölümünde TimeoutStartSec=600 olmasını sağlar."
)
parser.add_argument("unit_files", nargs="+", help="Birim dosyası yol(lar)ı")
parser.add_argument("--dry-run", action="store_true", help="Yazmadan değişiklik yapılıp yapılmayacağını göster")
parser.add_argument("--no-backup", action="store_true", help="Yedek dosyası oluşturma")
parser.add_argument("--value", default="600", help="TimeoutStartSec için ayarlanacak değer (varsayılan: 600)")
args = parser.parse_args()
backup_ext = "" if args.no_backup else ".bak"
exit_code = 0
for path in args.unit_files:
changed = ensure_timeout_start(path, value=args.value, dry_run=args.dry_run, backup_ext=backup_ext)
if args.dry_run:
print(f"{path}: {'CHANGE NEEDED' if changed else 'NO CHANGE NEEDED'}")
else:
print(f"{path}: {'UPDATED' if changed else 'ALREADY OK'}")
if not os.path.exists(path):
exit_code = 2
sys.exit(exit_code)
if __name__ == "__main__":
main()If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow