Initial commit

This commit is contained in:
torsten committed 2026-08-13 18:33:10 +02:00
commit b7d90b9afe
16245 files changed
+3396666

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
{
"tds": "EXCTDS01",
"ws": "localhost",
"dbs": "localhost",
"avs": "EXCAVS01",
"avs_user": "ctc",
"avs_pass": "ctc11de"
}
+73
View File
@@ -0,0 +1,73 @@
FROM opensuse/leap:15.1
RUN rm /etc/zypp/repos.d/*
COPY ./*.repo /etc/zypp/repos.d/
RUN zypper ref
#RUN zypper --non-interactive dup
RUN zypper install -y python3 python3-pip
RUN zypper in -y python3-devel
COPY req.txt /
ENV http_proxy="http://mike-lennart.wille%40rheinmetall.com:1ZwQG147@213.61.254.67:8080/"
ENV https_proxy="http://mike-lennart.wille%40rheinmetall.com:1ZwQG147@213.61.254.67:8080/"
#ENV no_proxy="192.168.133.0/24, 10.0.0.0/8"
ENV no_proxy="10.198.80.75"
RUN zypper in -y wget
RUN wget https://sh.rustup.rs -O rustup.sh && chmod u+x rustup.sh && ./rustup.sh -y
RUN ln /root/.cargo/bin/* /usr/local/bin/ -s
#RUN pip3 install -r req.txt
RUN pip3 install --upgrade pip
RUN pip3 install altgraph==0.17.4
RUN zypper in -y gcc
RUN pip3 install bcrypt==4.0.1
RUN pip3 install cffi==1.15.1
RUN pip3 install colorama==0.4.5
RUN zypper in -y pkg-config
RUN zypper in -y openssl-devel
RUN zypper in -y openssl
ENV PKG_CONFIG_PATH=/usr/lib/pkgconfig
RUN pip3 install cryptography
RUN pip3 install evdev
RUN pip3 install importlib-metadata==4.8.3
RUN pip3 install MouseInfo==0.1.3
RUN pip3 install Nuitka==1.3
RUN pip3 install paramiko==3.3.1
RUN pip3 install Pillow==8.4.0
RUN pip3 install psutil==5.9.6
RUN pip3 install pycparser==2.21
RUN pip3 install PyGetWindow==0.0.9
RUN pip3 install pyinstaller-hooks-contrib==2022.0
RUN pip3 install PyMouse==1.0
RUN pip3 install PyMsgBox==1.0.7
RUN pip3 install PyNaCl==1.5.0
RUN pip3 install pynput==1.7.6
RUN pip3 install pyperclip==1.8.2
RUN pip3 install PyRect==0.2.0
RUN pip3 install PyScreeze==0.1.26
RUN pip3 install python-xlib==0.33
RUN pip3 install python3-xlib==0.15
RUN pip3 install pytweening==1.0.7
RUN pip3 install six==1.16.0
RUN pip3 install typing_extensions==4.1.1
RUN pip3 install zipp==3.6.0
RUN pip3 install pyinstaller==4.10
RUN pip3 install prompt_toolkit
RUN pip3 install rich
RUN mkdir app
COPY ExconHelper app
RUN rm -rf main
RUN pyinstaller -F -w -y app/main.py
RUN ls /dist
RUN mkdir output
RUN cp /dist/main /output/main
RUN ls /output
CMD ["echo", "Build complete"]
+21
View File
@@ -0,0 +1,21 @@
HAllo,
Dieses kleine Tool stellt einige Funktionen bereit um mit der Excon zu arbeiten.
Damit das Tool auf den openSuse 15.1 Rechnern funktioniert muss es auch auf einem 15.1 System gebaut werden.
Das funktioniert wie folgt: Ich habe einen docker container erstellt (die Dockerfile liegt hier im Verzeichnis).
In diesem Container wird mithilfe vom pyinstaller dieses Projekt zusammen mit der Python installation an sich in ein executable gepackt.
Mit der build_and_copy.sh konnte ich das Projekt bei mir lokal bauen und das ganze Docker Ding starten.
Das executable kann dann auf einer Anlage mit dem Befehl "./main --init" gestartet und installiert werden.
Beim Installieren müssen einige fragen über das darunter liegende System beantwortet werden, das Programm installiert sich und eine .settings.json Datei dann im System und ist nach der installation systemweit mit dem Befehl excon erreichbar (ohne ./ davor)
mit "excon --help" lässt sich die hilfe anzeigen
führt man excon ohne weitere Parameter aus werden einem grundlegende Möglichkeiten gezeigt den LogView aus der WS zu starten oder die Services neu zu starten.
mit "excon -ac" lässt sich ein autocheck durchführen, Dort wird überprüft ob Services laufen und Rechner erreichbar sind, ob die Domain ID die gleiche ist und die Datenbank überall korrekt eingetragen wurde.
Ich konnte die Entwicklung leider nicht abschließen aber vielleicht bringt es euch ja was
Liebe Grüße Niklas
+223
View File
@@ -0,0 +1,223 @@
import shutil
from smtpd import usage
import psutil
import network
import local as localI
import settings
from network import is_reachable, check_proc_running, check_proc_args
from colorama import Style, Fore
CHECKMARK = Fore.GREEN + "[\u2713]" + Style.RESET_ALL
CROSS = Fore.RED + "[\u2717]" + Style.RESET_ALL
WARN = Fore.YELLOW + "[!]" + Style.RESET_ALL
opdom = None
svcdom = None
local = False # Set to true if the TDS is not reachable
tds = settings.get_setting("tds")
tds_user = settings.get_setting("tds_user")
tds_pass = settings.get_setting("tds_pass")
dbs = settings.get_setting("dbs")
dbs_user = settings.get_setting("dbs_user")
dbs_pass = settings.get_setting("dbs_pass")
avs = settings.get_setting("avs")
avs_user = settings.get_setting("avs_user")
avs_pass = settings.get_setting("avs_pass")
def autocheck(verbose):
global local
checkLocalDiskSpace()
if tds == "localhost":
local = True
if is_running("OperatorApplication"):
print(CHECKMARK + "OperatorApplication is running")
for element in get_args("OperatorApplication"):
if "-d" in element:
opdom = element.split("-d")[1]
else:
print(CROSS + "OperatorApplication is not running")
if is_running("AVS_Workstation"):
print(CHECKMARK + "AVS_Workstation is running")
else:
print(CROSS + "AVS_Workstation is not running")
if is_running("AVS_Export"):
print(CHECKMARK + "AVS_Export is running")
else:
print(CROSS + "AVS_Export is not running")
if not local:
if is_reachable(tds, verbose):
print(CHECKMARK + "TDS is reachable")
checkDiskUsage(network.checkDiskSpace(tds, tds_user, tds_pass), 80)
if "localhost" == network.checkLtsccConf(tds, tds_user, tds_pass, "ServerHostname"):
print(CROSS + "TDS is reachable but lts-cc.conf got localhost")
checkServicesRemote(verbose)
else:
print(CROSS + Style.RESET_ALL + "TDS is not reachable")
local = True
if is_running("svcServiceManagement"):
print(CHECKMARK + "ServiceManagement is running local")
if "localhost" != localI.checkLocalConfig("ServerHostname"):
print(CROSS + "ServiceManagement running locally but ServerHostname in lts-cc.conf is not set to localhost")
#checkServicesLocal(verbose)
else:
print(CROSS + "ServiceManagement is not running local")
if dbs != "localhost":
if is_reachable(dbs, verbose):
print(CHECKMARK + "DBS is reachable")
if check_proc_running(dbs, dbs_user, dbs_pass, "postgres", verbose):
print(" " + CHECKMARK + " Postgres is running")
if local:
if localI.checkLocalConfig("DatabaseName") not in network.checkDatabases(dbs, dbs_user, dbs_pass):
print(" " + CROSS + " The DatabaseName in lts-cc.conf is not in psql")
else:
if network.checkLtsccConf(tds, tds_user, tds_pass, "DatabaseName").strip() not in network.checkDatabases(
dbs, dbs_user, dbs_pass):
print(" " + CROSS + " The DatabaseName in lts-cc.conf is not in psql")
else:
print(" " + CROSS + " Postgres is not running")
else:
print(CROSS + "DBS is not reachable")
if is_reachable(avs, verbose):
print(CHECKMARK + "EXCAVS01 is reachable")
else:
print(CROSS + "EXCAVS01 is not reachable")
if is_reachable("EXCTDS05", verbose):
print(CHECKMARK + "EXCTDS05 is reachable")
else:
print(CROSS + "EXCTDS05 is not reachable")
def is_running(proc):
for process in psutil.process_iter():
if proc in process.name() :
return True
return False
def get_args(proc):
for process in psutil.process_iter(["pid", "name", "cmdline"]):
if proc in process.name():
return process.cmdline()[1:]
return None
def checkServicesRemote( verbose):
if check_proc_running(tds, tds_user, tds_pass, "svcServiceManagement", verbose):
print(" " + CHECKMARK + "svcServiceManagement is running")
proc_args= check_proc_args(tds, tds_user, tds_pass, "svcServiceManagement", verbose)
if proc_args is not None:
for element in proc_args:
if "-d" in element:
svcdom = element.split("-d")[1]
if svcdom is not opdom:
print(" " + CROSS + "svcServiceManagement has different Domain Id than OperatorApplication")
else:
print(" " + CROSS + "svcServiceManagement is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcAreaEffectSimulation", verbose):
print(" " + CHECKMARK + "svcAreaEffectSimulation is running")
else:
print(" " + CROSS + "svcAreaEffectSimulation is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcCentralEffectSimulation", verbose):
print(" " + CHECKMARK + "svcCentralEffectSimulation is running")
else:
print(" " + CROSS + "svcCentralEffectSimulation is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcExerciseEventManagement", verbose):
print(" " + CHECKMARK + "svcExerciseEventManagement is running")
else:
print(" " + CROSS + "svcExerciseEventManagement is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcExerciseManagement", verbose):
print(" " + CHECKMARK + "svcExerciseManagement is running")
else:
print(" " + CROSS + "svcExerciseManagement is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcParticipantManagement", verbose):
print(" " + CHECKMARK + "svcParticipantManagement is running")
else:
print(" " + CROSS + "svcParticipantManagement is not running")
if check_proc_running(tds, tds_user, tds_pass, "svcProjectDataManagement", verbose):
print(" " + CHECKMARK + "svcProjectDataManagement is running")
else:
print(" " + CROSS + "svcProjectDataManagement is not running")
def checkServicesLocal(verbose):
svcdom2 = None
if is_running("svcServiceManagement"):
print(" " + CHECKMARK + "svcServiceManagement is running")
for element in get_args("svcServiceManagement"):
if "-d" in element:
svcdom2 = element.split("-d")[1]
if svcdom2 is not opdom:
print(" " + CROSS + "svcServiceManagement has different Domain Id than OperatorApplication")
else:
print(" " + CROSS + "svcServiceManagement is not running")
if is_running("svcAreaEffectSimulation"):
print(" " + CHECKMARK + "svcAreaEffectSimulation is running")
else:
print(" " + CROSS + "svcAreaEffectSimulation is not running")
if is_running("svcCentralEffectSimulation"):
print(" " + CHECKMARK + "svcCentralEffectSimulation is running")
else:
print(" " + CROSS + "svcCentralEffectSimulation is not running")
if is_running("svcExerciseEventManagement"):
print(" " + CHECKMARK + "svcExerciseEventManagement is running")
else:
print(" " + CROSS + "svcExerciseEventManagement is not running")
if is_running("svcExerciseManagement"):
print(" " + CHECKMARK + "svcExerciseManagement is running")
else:
print(" " + CROSS + "svcExerciseManagement is not running")
if is_running("svcParticipantManagement"):
print(" " + CHECKMARK + "svcParticipantManagement is running")
else:
print(" " + CROSS + "svcParticipantManagement is not running")
if is_running("svcProjectDataManagement"):
print(" " + CHECKMARK + "svcProjectDataManagement is running")
else:
print(" " + CROSS + "svcProjectDataManagement is not running")
def checkDiskUsage(disk_usage, threshold):
for disk in disk_usage:
percent_used = disk['percent_used']
if percent_used > threshold:
print(WARN + f"Disk {disk['mountpoint']} is {percent_used}% full!")
def checkLocalDiskSpace():
partitions = psutil.disk_partitions()
for partition in partitions:
try:
usage = shutil.disk_usage(partition.mountpoint)
total = usage.total
used = usage.used
percent_used = (used / total) * 100
if percent_used > 80:
print(WARN + f"Disk {partition.mountpoint} is {percent_used}% full!")
except Exception as e:
print("Fehler bei der Festplattenüberprüfung")
+104
View File
@@ -0,0 +1,104 @@
from prompt_toolkit import prompt
import concurrent.futures
import network
import settings
import local
from rich.table import Table
from rich.console import Console
def switch_branch(verbose):
tds = settings.get_setting("tds")
tds_user = settings.get_setting("tds_user")
tds_pass = settings.get_setting("tds_pass")
branches_list = network.list_branches(tds, tds_user, tds_pass)
table = Table(title="Branches")
table.add_column("Branches")
for branch in branches_list:
table.add_row(branch)
branch_name = prompt('Branch name:')
if branch_name not in branches_list:
print("choose branch from the list!")
switch_branch(verbose)
def add_branch(verbose):
localhost = False
tds = settings.get_setting("tds")
if tds == "localhost":
localhost = True
tds_user = settings.get_setting("tds_user")
tds_pass = settings.get_setting("tds_pass")
dbs = settings.get_setting("dbs")
dbs_user = settings.get_setting("dbs_user")
dbs_pass = settings.get_setting("dbs_pass")
branch_url = prompt('SVN URL:')
project_name_p= prompt("Project Name(y/n)(Standard is guez):")
project_name = "guez"
guez_mode= True
build_ws= True
build_sv= True
build_hla= False
if prompt("GÜZ Mode(y/n)(Standard is ON):") == "n":
guez_mode = False
if prompt("Build WS(y/n)(Standard is ON):") == "n":
build_ws = False
if prompt("Build SV(y/n)(Standard is ON):") == "n":
build_sv = False
if prompt("Build HLA(y/n)(Standard is OFF):") == "y":
build_hla=True
if project_name_p != "":
project_name=project_name_p
console = Console()
with console.status("[bold green]Adding branch..."):
with concurrent.futures.ProcessPoolExecutor() as executor:
if not localhost:
branch_name = network.add_branch(tds, tds_user, tds_pass, branch_url)
console.log("Adding Folders on Server and SVN Checkout complete.")
executor.submit(build_remote(tds, tds_user, tds_pass, branch_name, project_name, guez_mode, build_ws, build_sv, build_hla))
console.log("Building on Server complete.(SRC and Test-DB)")
branch_name = local.add_branch(branch_url)
if branch_name:
console.log("Adding Folders on local machine and SVN Checkout complete.")
else:
return
if executor.submit(build_local(project_name, guez_mode, build_ws, build_sv, build_hla, branch_name)):
console.log("Building on local machine complete.")
else:
return
if not localhost:
db_name = network.checkLtsccConf(tds, tds_user, tds_pass, "DatabaseName")
network.save_db(dbs, dbs_user, dbs_pass, db_name, verbose)
console.log("Saving old db complete.")
network.editLtsccConf(tds, tds_user, tds_pass, "DatabaseName", f'{branch_name}_db')
console.log("Editing new DB to lts-cc.conf complete.")
console.log("Build Test DB complete.")
settings.set_setting("current_branch", branch_name)
def build_remote(tds, tds_user, tds_pass, branch_name, project_name, guez_mode, build_ws, build_sv, build_hla):
network.build_branch(tds, tds_user, tds_pass, branch_name, project_name, guez_mode, build_ws, build_sv, build_hla)
network.build_test_db(tds,tds_user,tds_pass, branch_name)
def build_local(project_name, guez_mode, build_ws, build_sv, build_hla, branch_name):
local.build_branch(branch_name, project_name, guez_mode, build_ws, build_sv, build_hla)
+9
View File
@@ -0,0 +1,9 @@
LOCAL_OUTPUT="/shd/CTC/TOOLS/dockertest/output"
IMAGE_NAME="excon_helper"
rm -rf ExconHelper
cp -r /shd/CTC/TOOLS/PycharmProjects/ExconHelper .
mkdir -p "$LOCAL_OUTPUT"
docker build -t "$IMAGE_NAME" .
conatiner_id=$(docker run -d "$IMAGE_NAME")
docker cp "$conatiner_id:/output/main" "$LOCAL_OUTPUT/main"
docker rm -f "$conatiner_id"
+176
View File
@@ -0,0 +1,176 @@
import os.path
import shutil
import subprocess
import sys
import stat
from prompt_toolkit import prompt
import settings
from local import check_rpm_package_installed
from network import is_reachable, check_ssh_credentials
def initiate():
root_pass = prompt("Local root password:")
install_self(root_pass)
if autoinit(root_pass):
return
settings_dict = dict()
tds = prompt("Address of TDS (Standard is EXCTDS01):")
if tds == "":
tds = "EXCTDS01"
settings_dict["tds"] = tds
if tds != "localhost":
tds_user = prompt("TDS Username (Standard is ctc):")
if tds_user == "":
tds_user = "ctc"
settings_dict["tds_user"] = tds_user
tds_pass = prompt("TDS Password (Standard is ctc11de):")
if tds_pass == "":
tds_pass = "ctc11de"
settings_dict["tds_pass"] = tds_pass
ws = prompt("Address of WS (Standard is localhost):")
if ws == "":
ws = "localhost"
settings_dict["ws"] = ws
if ws != "localhost":
ws_user = prompt("WS Username (Standard is ctc):")
if ws_user == "":
ws_user = "ctc"
settings_dict["ws_user"] = ws_user
ws_pass = prompt("WS Password (Standard is ctc11de):")
if ws_pass == "":
ws_pass = "ctc11de"
settings_dict["ws_pass"] = ws_pass
dbs = prompt("Address of DBS (Standard is EXCDBS01):")
if dbs == "":
dbs = "EXCDBS01"
settings_dict["dbs"] = dbs
if dbs != "localhost":
dbs_user = prompt("DBS Username (Standard is postgres):")
if dbs_user == "":
dbs_user = "postgres"
settings_dict["dbs_user"] = dbs_user
dbs_pass = prompt("DBS Password (Standard is postgres):")
if dbs_pass == "":
dbs_pass = "postgres"
settings_dict["dbs_pass"] = dbs_pass
avs = prompt("Address of AVS (Standard is EXCDAVS01):")
if avs == "":
avs = "EXCAVS01"
settings_dict["avs"] = avs
if avs != "localhost":
avs_user = prompt("AVS Username (Standard is ctc):")
if avs_user == "":
avs_user = "ctc"
settings_dict["avs_user"] = avs_user
avs_pass = prompt("AVS Password (Standard is ctc11de):")
if avs_pass == "":
avs_pass = "ctc11de"
settings_dict["avs_pass"] = avs_pass
build = prompt("Is the software installed over rpm? (y/n):")
if build == "y":
aws = prompt("Admin Workstation Address (Standard is CCSAWS01):")
if aws == "":
aws = "CCSAWS01"
settings_dict["aws"] = aws
settings_dict["rpm"] = True
else:
settings_dict["rpm"] = False
settings.save_settings(settings_dict, root_pass)
print("Erfolgreich gespeichert!")
def autoinit(root_pass):
settings_dict = dict()
if is_reachable("EXCTDS01", False):
tds = "EXCTDS01"
if check_ssh_credentials(tds, "ctc", "ctc11de"):
tds_user = "ctc"
tds_pass = "ctc11de"
settings_dict["tds_user"] = tds_user
settings_dict["tds_pass"] = tds_pass
else:
print("Auto Init failed. Please enter the credentials manually.")
return False
else:
tds = "localhost"
settings_dict["tds"] = tds
if is_reachable("EXCDBS01", False):
dbs = "EXCDBS01"
if check_ssh_credentials(dbs, "postgres", "postgres"):
settings_dict["dbs_user"] = "postgres"
settings_dict["dbs_pass"] = "postgres"
else:
print("Auto Init failed. Please enter the credentials manually.")
return False
else:
dbs = "localhost"
settings_dict["dbs"] = dbs
settings_dict["ws"] = "localhost"
settings_dict["ws_user"] = "ctc"
settings_dict["ws_pass"] = "ctc11de"
if is_reachable("EXCAVS01", False):
settings_dict["avs"] = "EXCAVS01"
if check_ssh_credentials("EXCAVS01", "ctc", "ctc11de"):
settings_dict["avs_user"] = "ctc"
settings_dict["avs_pass"] = "ctc11de"
else:
print("Auto Init failed. Please enter the credentials manually.")
return False
if check_rpm_package_installed('guez_ws'):
if is_reachable("CCSAWS01", False):
aws = "CCSAWS01"
if check_ssh_credentials(aws, "root", "!Moutde"):
settings_dict["aws"] = aws
settings_dict["aws_user"] = "root"
settings_dict["aws_pass"] = "!Moutde"
settings_dict["rpm"] = True
else:
print("Auto Init failed. Please enter the credentials manually.")
return False
else:
print("Auto Init failed. Please enter the credentials manually.")
return False
else:
settings_dict["rpm"] = False
settings.save_settings(settings_dict, root_pass)
def install_self(root_pass):
target_bin_path = f"/usr/local/bin/excon"
try:
# Kopiere die Datei nach /usr/local/bin mit sudo
subprocess.run(f"echo {root_pass} | sudo -S cp {sys.executable} {target_bin_path}", shell=True, check=True)
# Setze die Ausführberechtigung für die Datei
subprocess.run(f"echo {root_pass} | sudo -S chmod +x {target_bin_path}", shell=True, check=True)
except subprocess.CalledProcessError as e:
print(f"Fehler beim Kopieren der Datei nach '/usr/local/bin': {e}")
except Exception as e:
print(f"Unbekannter Fehler: {e}")
+141
View File
@@ -0,0 +1,141 @@
import subprocess
from sys import stderr
from utils import console, get_error_console
def getConfigParam(lines, config_id):
value = None
for line in lines:
line = line.strip()
if not line or line.startswith('#') or line.startswith(';'):
continue
if '=' in line:
key, val = line.split('=', 1)
key = key.strip()
if key == config_id:
value = val
break
return value
def checkLocalConfig(config_id):
try:
with open('/etc/lts-cc.conf', 'r', encoding="utf-8") as file:
return getConfigParam(file.readlines(), config_id)
except FileNotFoundError:
print("Can not find lts-cc.conf")
def extractDatabases(output):
lines = output.splitlines()
databases = []
capture = False
for line in lines:
line = line.strip()
if line.startswith("Name"):
capture = True
continue
if capture:
if line.startswith("----"):
continue
if line.strip() == "":
continue
name = line.split('|')[0].strip()
if name != "":
databases.append(name)
return databases
def parseDiskUsage(output):
lines = output.split("\n")
disk_usage = []
for line in lines[1:]:
parts = line.split()
if len(parts) < 6:
continue
percent_used = int(parts[4].replace("%", ""))
mountpoint = parts[5]
disk_usage.append({
'percent_used': percent_used, 'mountpoint': mountpoint
})
return disk_usage
def add_branch( svn_url):
branch_name = svn_url.rstrip('/').split('/')[-1]
stderr_source = subprocess.run(['mkdir', f'/shd/CTC/TOOLS/TDS/source-{branch_name}'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr_source.returncode:
get_error_console().log(f"Cant create source folder: {stderr_source}")
return False
stderr_build = subprocess.run(['mkdir', f'/shd/CTC/TOOLS/TDS/build-{branch_name}'],stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr_build.returncode:
get_error_console().log(f"Cant create build folder: {stderr_build}")
return False
stderr_co = subprocess.run(['svn', 'co', f'{svn_url}', f'/shd/CTC/TOOLS/TDS/source-{branch_name}'], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr_co.returncode:
get_error_console().log(f"Cant checkout branch: {stderr_co}")
return False
return branch_name
def build_branch(branch_name, project_name, guez_mode, build_ws, build_sv, build_hla):
command = ['cmake', '-G', 'Ninja', f'/shd/CTC/TOOLS/TDS/source-{branch_name}']
if guez_mode:
command.append( "-DGUEZ_MODE=ON")
else:
command.append( "-DGUEZ_MODE=OFF")
command.append("-DBUILD_TOOLSSV=ON")
command.append("-DBUILD_WLS=ON")
if build_ws:
command.append("-DBUILD_WS=ON")
else:
command.append("-DBUILD_WS=OFF")
command.append("-DBUILD_AAR=OFF")
if build_hla:
command.append("-DBUILD_SVC_HLA=ON")
else:
command.append("-DBUILD_SVC_HLA=OFF")
if build_sv:
command.append("-DBUILD_SV=ON")
else:
command.append("-DBUILD_SV=OFF")
command.append( f'-D_pname={project_name}')
command.append( "-DCMAKE_BUILD_TYPE=RelWithDebInfo")
command.append("-B")
command.append(f"/shd/CTC/TOOLS/TDS/build-{branch_name}")
stderr_configure = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr_configure.returncode:
get_error_console().log(f"Cant configure branch: {stderr_configure.stderr}")
return False
stderr_build = subprocess.run(['ninja'], cwd=f'/shd/CTC/TOOLS/TDS/build-{branch_name}', stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr_build.returncode:
get_error_console().log(f"Cant build branch: {stderr_build}")
return False
return True
def build_test_db(branch_name):
stderr = subprocess.run(['ninja', 'test-db'], cwd=f'/shd/CTC/TOOLS/TDS/build-{branch_name}', stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if stderr.returncode:
get_error_console().log(f"Cant build test-db: {stderr}")
def check_rpm_package_installed(package_prefix):
try:
result = subprocess.run(['rpm', '-qa', package_prefix], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode:
get_error_console().log(f"Package {package_prefix} not installed: {stderr}")
return False
installed_packages = result.stdout.splitlines()
matching_packages = [package for package in installed_packages if package.startswith(package_prefix)]
if matching_packages:
return True
else:
return False
except Exception as e:
return False
+114
View File
@@ -0,0 +1,114 @@
import argparse
import sys
import paramiko
from prompt_toolkit import prompt
import network
import settings
from initiate import initiate
import subprocess
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Niklas Excon Helfer")
parser.add_argument('-db', '--updatedb', action='store_true', help="Datenbank updaten")
parser.add_argument('-c', '--autocheck', action='store_true',
help="Checkt alle Maschinen und Prozesse in einem Produktivsystem und lokalem System")
# parser.add_argument('-i', '--install' , action='store_true', help="Installiert die komplette Software, pogchamp")
parser.add_argument("-b", "--branch", action='store_true', help='Returns the current used branch')
parser.add_argument('-s', '--switch', action='store_true', help='Switches the branch to another')
parser.add_argument('-a', '--add', action='store_true', help='Adds a new branch on server and client')
parser.add_argument('-v', '--verbose', action='store_true', help="More print outs")
parser.add_argument('-in', '--init', action='store_true', help="Init this tool to set TDS and DBS...")
parser.add_argument('-n', '--niklas', action='store_true', help="Kleine Info")
parser.add_argument("-r", "--revisions", action='store_true', help="Show all revisions/versions installed on several machines")
verbose = False
args = parser.parse_args()
if args.niklas:
print("Hallo liebe Freunde, dieses Tool wurde mit Liebe und Herzblut von mir gebaut, ich hoffe es sind nicht zu viele Fehler drin, in Liebe Niklas <3")
sys.exit()
if args.init:
initiate()
sys.exit()
if settings.get_setting("tds") is None:
print("Die Settings wurden nicht korrekt gesetzt, bitte führe --init aus")
sys.exit()
if args.branch:
if settings.get_setting("rpm") is True:
print("Only possible in dev mode. (This machine is in production mode, --init to change)")
sys.exit()
branch = settings.get_setting("current_branch")
if branch is not None:
print(f"Current installed branch: {branch}")
sys.exit()
if args.revisions:
if settings.get_setting("rpm") is False:
print("Only possible in production mode. (This machine is in dev mode, --init to change)")
sys.exit()
if args.verbose:
verbose = True
if args.autocheck:
from autocheck import autocheck
autocheck(verbose)
sys.exit()
if args.updatedb:
from updatedb import updatedb
updatedb(verbose)
sys.exit()
if args.switch:
if settings.get_setting("rpm") is True:
print("Only possible in dev mode. (This machine is in production mode, --init to change)")
sys.exit()
from branch_helper import switch_branch
switch_branch(verbose)
sys.exit()
if args.add:
if settings.get_setting("rpm") is True:
print("Only possible in dev mode. (This machine is in production mode, --init to change)")
sys.exit()
from branch_helper import add_branch
add_branch(verbose)
sys.exit()
tds = settings.get_setting("tds")
if tds == "localhost":
sys.exit()
print("What do you want to do?")
print("[1] Open LogView")
print("[2] Open SqlBrowser")
print("[3] Open DDSView")
print("[4] Restart Server")
print("[5] Restart Tetra")
print("[6] Update Software")
option = prompt()
tds_user = settings.get_setting("tds_user")
tds_pass = settings.get_setting("tds_pass")
if option == "1":
subprocess.run(f"sshpass -p '{tds_pass}' ssh -X {tds_user}@{tds} /shd/CTC/SV/bin/LogView", shell=True)
if option == "2":
subprocess.run(f"sshpass -p '{tds_pass}' ssh -X {tds_user}@{tds} /shd/CTC/SV/bin/sqlbrowser", shell=True)
if option == "3":
subprocess.run(f"sshpass -p '{tds_pass}' ssh -X {tds_user}@{tds} /shd/CTC/SV/bin/ddsview", shell=True)
if option == "4":
subprocess.run(f"sshpass -p '!Mout11de' ssh -X root@{tds} systemctl restart lts_sv", shell=True)
if option == "5":
network.execSshCommand("ccstsw01", "root", "accessnet", "systemctl restart guez2")
if option == "6":
print("ServiceManagement will be stopped!")
network.execSshCommand(tds, "root", "!Mout11de", "systemctl stop lts_sv && zypper ref && zypper up")
network.execSshCommand(tds, "root", "!Mout11de", "systemctl start lts_sv")
+40
View File
@@ -0,0 +1,40 @@
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['main.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None )
+272
View File
@@ -0,0 +1,272 @@
import subprocess
import local
import paramiko
import datetime
def check_ssh_credentials(hostname, username, password):
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname, username=username, password=password)
return True
except paramiko.AuthenticationException:
print("Authentication failed when connecting to %s" % hostname)
return False
except paramiko.SSHException as e:
return False
except Exception as e:
return False
def execSshCommand(hostname, username, password, command, verbose=False):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
client.connect(hostname, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)
if verbose:
print(stdout.read().decode('utf-8'))
except Exception as e:
print(e)
finally:
client.close()
def execScpCommand(local_path, hostname, username, password, remote_path):
try:
transport = paramiko.Transport((hostname, 22))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_path, remote_path)
transport.close()
except Exception as e:
print(e)
def is_reachable(hostname, verbose=False):
try:
if verbose:
subprocess.check_output(["ping", "-c", "1", hostname])
else:
subprocess.check_output(["ping", "-c", "1", hostname], stderr=subprocess.DEVNULL)
return True
except subprocess.CalledProcessError:
return False
def editLtsccConf(hostname, username, password, id, new_content):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname, username=username, password=password)
_, stdout, _ = client.exec_command(f"cat /etc/lts-cc.conf")
content = stdout.read().decode('utf-8')
new_content = content.replace(id + '=', f'{id}={new_content};')
with client.open_sftp().file("/etc/lts-cc.conf", 'w') as remote_file:
remote_file.write(new_content)
except Exception as e:
print(e)
finally:
client.close()
def checkLtsccConf(hostname, username, password, config_id):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname, username=username, password=password)
_, stdout, _ = client.exec_command(f"cat /etc/lts-cc.conf")
content = stdout.read().decode('utf-8')
lines = content.splitlines()
return local.getConfigParam(lines, config_id)
except Exception as e:
print(e)
finally:
client.close()
def check_proc_running(hostname, username, password, process_name, verbose=False):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(f"ps aux | grep {process_name} | grep -v grep")
output = stdout.read().decode('utf-8')
ssh.close()
return process_name in output
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
return False
def checkDatabases(hostname, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command('psql -l')
stdout_str = stdout.read().decode('utf-8')
stderr_str = stderr.read().decode('utf-8')
ssh.close()
return local.extractDatabases(output=stdout_str)
except Exception as e:
print(e)
def check_proc_args(hostname, username, password, process_name, verbose=False):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(f"ps aux | grep {process_name} | grep -v grep")
output = stdout.read().decode('utf-8')
ssh.close()
lines = output.split("-")[1:]
if lines:
return lines
else:
return None
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
return None
def checkDiskSpace(hostname, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command("df -h")
output = stdout.read().decode().strip()
ssh.close()
disk_usage = local.parseDiskUsage(output)
return disk_usage
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def list_branches(hostname, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command(f'ls -d /shd/CTC/TOOLS/TDS/*')
output = stdout.read().decode('utf-8').splitlines()
directories = [dire.strip('/') for dire in output]
ssh.close()
return directories
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def add_branch(hostname, username, password, svn_url):
try:
branch_name = svn_url.rstrip('/').split('/')[-1]
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
ssh.exec_command(f'mkdir /shd/CTC/TOOLS/TDS/source-{branch_name}')
ssh.exec_command(f'mkdir /shd/CTC/TOOLS/TDS/build-{branch_name}')
ssh.exec_command(f'svn co {svn_url} /shd/CTC/TOOLS/TDS/source-{branch_name}')
ssh.close()
return branch_name
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def build_branch(hostname, username, password, branch_name, project_name, guez_mode, build_ws, build_sv, build_hla):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname, username=username, password=password)
command = f'cmake -G Ninja /shd/CTC/TOOLS/TDS/source-{branch_name} -DGUEZ_MODE='
if guez_mode:
command+= "ON"
else:
command+= "OFF"
command+= " -DBUILD_TOOLSSV=ON -DBUILD_WLS=ON -DBUILD_TOOLSWS=ON -DBUILD_TESTING=ON -DBUILD_WS="
if build_ws:
command+= "ON"
else:
command+= "OFF"
command+= " -DBUILD_AAR=OFF -DBUILD_SVC_HLA="
if build_hla:
command += "ON"
else:
command += "OFF"
command+= " -DBUILD_SV="
if build_sv:
command += "ON"
else:
command += "OFF"
command+= " -D_pname="
command+= project_name
command += " -DCMAKE_BUILD_TYPE=RelWithDebInfo"
command += f" -B /shd/CTC/TOOLS/TDS/build-{branch_name}"
stderr = ssh.exec_command(command)
stderr = ssh.exec_command(f'cd /shd/CTC/TOOLS/TDS/build-{branch_name}/ && ninja')
ssh.close()
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def build_test_db(hostname, username, password, branch_name):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=hostname, username=username, password=password)
ssh.exec_command(f'cd /shd/CTC/TOOLS/TDS/build-{branch_name}/ && ninja test-db')
ssh.close()
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def save_db(dbs,db_user, db_pass, db_name, verbose):
command = f"pg_dump {db_name} > {db_name}_save" + str(datetime.date)
execSshCommand(dbs, db_user, db_pass, command, verbose)
def execExternalApp(host, user, password, path, params):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=host, username=user, password=password)
transport = ssh.get_transport()
session = transport.open_session()
session.request_x11()
command = path + " " + params
session.exec_command(command)
session.recv_exit_status()
ssh.close()
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
def restart_server(hostname, username, password):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=hostname, username="root", password="!Mout11de")
transport = ssh.get_transport()
session =transport.open_session()
session.request_x11()
ssh.exec_command(f'systemctl restart lts_sv')
session.recv_exit_status()
ssh.close()
except (paramiko.AuthenticationException, paramiko.SSHException) as e:
print("Fehler bei Verbindung zum Server")
+70
View File
@@ -0,0 +1,70 @@
import json
import os.path
import subprocess
def save_settings(settings, root_pass):
settings_dir = "/etc/excon_helper"
settings_file = os.path.join(settings_dir, ".settings.json")
temp_file = "/tmp/.settings.json" # Temporäre Datei
# Temporäre Datei lokal schreiben
with open(temp_file, "w") as temp:
json.dump(settings, temp, indent=4)
# Befehle zum Erstellen des Zielverzeichnisses und Kopieren der Datei
commands = [
f"mkdir -p {settings_dir}",
f"cp {temp_file} {settings_file}",
f"chmod 777 {settings_file}",
f"rm {temp_file}" # Temporäre Datei entfernen
]
for command in commands:
try:
# Übergebe das Passwort an `sudo` und führe den Befehl aus
process = subprocess.run(
f"echo {root_pass} | sudo -S {command}",
shell=True
)
if process.returncode != 0:
print(f"Cant save settings file")
return False
except Exception as e:
print(f"Error: {e}")
return False
return True
def load_settings():
settings_file = "/etc/excon_helper/.settings.json"
# Überprüfen, ob die Datei existiert
if not os.path.exists(settings_file):
print(f"Error: Settings file doesnt exist")
return {}
# Lesen der JSON-Datei
try:
with open(settings_file, "r") as file:
settings = json.load(file)
return settings
except json.JSONDecodeError:
print("Error: Corrupted json file")
except PermissionError:
print("Error: no permission to read the file")
except Exception as e:
print(f"Unknown error: {e}")
return {}
def get_setting(key):
settings = load_settings()
if settings is not None:
return settings.get(key)
return None
def set_setting(key, value):
settings = load_settings()
settings.set(key, value)
save_settings(settings)
+45
View File
@@ -0,0 +1,45 @@
from network import *
import os
import datetime
import settings
def updatedb(verbose):
dbserver = settings.get_setting("dbs")
dbpass = settings.get_setting("dbs_pass")
dbuser = settings.get_setting("dbs_user")
dbname = "lts_ets_pro"
tds = settings.get_setting("tds")
tds_user = settings.get_setting("tds_user")
tds_pass = settings.get_setting("tds_pass")
dump = input("DB Dump Pfad:")
dbserver_in = input("DB Server (Default: " + dbserver + "):")
dbpass_in = input("DB Password (Default: " + dbpass + "):")
dbuser_in = input("DB User (Default: " + dbuser + "):")
dbname_in = input("DB Name (Default: " + dbname + "):")
if dbserver_in is not "":
dbserver = dbserver_in
if dbpass_in is not "":
dbpass = dbpass_in
if dbname_in is not "":
dbname = dbname_in
if dbuser_in is not "":
dbuser = dbuser_in
print("Dump wird auf DB Server kopiert")
execScpCommand(dump, dbserver, dbuser, dbpass, "/opt/postgres")
print("Alte Datenbank wird gesichert")
db_name = checkLtsccConf(tds, tds_user, tds_pass, "DatabaseName")
save_db(dbserver, dbuser, dbpass,db_name, verbose)
print("Neue DB wird eingespielt")
execSshCommand(dbserver, dbuser, dbpass, "dropdb lts_ets_pro", verbose)
execSshCommand(dbserver, dbuser, dbpass, "createdb lts_ets_pro", verbose)
execSshCommand(dbserver, dbuser, dbpass, "createdb lts_ets_pro", verbose)
onlyName = os.path.basename(dump)
execSshCommand(dbserver, dbuser, dbpass, "psql " + dbname + " -f " + onlyName, verbose)
execSshCommand(dbserver, dbuser, dbpass,
"psql + " + dbname + " -U " + dbuser + "-c \'GRANT CREATE ON DATABASE " + dbname + " TO ets_admin\'", verbose)
print("Passe lts-cc.conf an")
editLtsccConf(dbserver, dbuser, dbpass, "DatabaseName", onlyName)
+10
View File
@@ -0,0 +1,10 @@
from rich.console import Console
console = Console()
error_console = Console(stderr=True, style="bold red")
def get_console():
return console
def get_error_console():
return error_console