Compare commits
No commits in common. "main" and "latest" have entirely different histories.
7
.env
7
.env
|
|
@ -1,7 +0,0 @@
|
|||
## Ticketsystem
|
||||
ZAMMAD_URL = "https://ticket.stines.de/api/v1"
|
||||
ZAMMAD_API_TOKEN ="1v4XGY7cZpBXSfb4s_tIBbywQjcaDV6q65IXQyVXrrBDqVtmAtLxM5tOqIAp0VXZ"
|
||||
|
||||
## API-Server
|
||||
API_SERVER = "http://api.stines.de:8001"
|
||||
API_TOKEN = "^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8"
|
||||
|
|
@ -1,3 +0,0 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.11" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/Agents.iml" filepath="$PROJECT_DIR$/.idea/Agents.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -1,98 +0,0 @@
|
|||
import requests
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
|
||||
# Lade die Umgebungsvariablen aus der .env Datei
|
||||
load_dotenv()
|
||||
|
||||
# Hole die Werte aus der .env Datei
|
||||
zammad_url = os.getenv('ZAMMAD_URL')
|
||||
zammad_api_token = os.getenv('ZAMMAD_API_TOKEN')
|
||||
|
||||
api_url = os.getenv('API_SERVER')
|
||||
api_token = os.getenv('API_TOKEN')
|
||||
|
||||
headers_zammad = {"Authorization": f"Token token={zammad_api_token}"}
|
||||
headers_api = {"access_token": f"{api_token}", "Content-Type": "application/json"}
|
||||
|
||||
# API Anfrage an Zammad für Organisationen
|
||||
response_org = requests.get(f"{zammad_url}/organizations", headers=headers_zammad)
|
||||
# API Anfrage an Zammad für Benutzer
|
||||
response_user = requests.get(f"{zammad_url}/users", headers=headers_zammad)
|
||||
|
||||
if response_org.status_code == 200 and response_user.status_code == 200:
|
||||
organizations = response_org.json()
|
||||
users = response_user.json()
|
||||
|
||||
# Erstelle ein Dictionary, das die Organisationen nach ID speichert
|
||||
org_dict = {org['id']: org['domain'] for org in organizations}
|
||||
# Erstelle ein Dictionary, das die Benutzer nach ID speichert
|
||||
user_dict = {user['id']: user for user in users}
|
||||
|
||||
# Berechne den ersten und letzten Tag des letzten Monats
|
||||
today = datetime.now()
|
||||
first_day_last_month = today.replace(day=1) - timedelta(days=1)
|
||||
first_day_last_month = first_day_last_month.replace(day=1)
|
||||
last_day_last_month = today.replace(day=1) - timedelta(days=1)
|
||||
|
||||
# Formatierung der Daten für den Vergleich
|
||||
start_date_str = first_day_last_month.strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
end_date_str = last_day_last_month.strftime('%Y-%m-%dT%H:%M:%SZ')
|
||||
|
||||
# API Anfrage an Zammad für Tickets mit Pagination und Sortierung
|
||||
params = {
|
||||
'query': f"last_close_at:[{start_date_str} TO {end_date_str}]",
|
||||
'sort_by': 'last_close_at',
|
||||
'order': 'desc',
|
||||
'per_page': 100,
|
||||
'page': 1
|
||||
}
|
||||
response_tickets = requests.get(f"{zammad_url}/tickets/search", headers=headers_zammad, params=params)
|
||||
|
||||
if response_tickets.status_code == 200:
|
||||
response_data = response_tickets.json()
|
||||
|
||||
# Extrahiere die Ticket-IDs und die zugehörigen Ticket-Daten aus assets
|
||||
ticket_ids = response_data.get('tickets', [])
|
||||
ticket_assets = response_data.get('assets', {}).get('Ticket', {})
|
||||
|
||||
# Filtere die Tickets, extrahiere die benötigten Felder und verknüpfe mit Organisationen und Benutzern
|
||||
filtered_tickets = [
|
||||
{
|
||||
'number': ticket_data.get('number'),
|
||||
'title': ticket_data.get('title'),
|
||||
'create_date': datetime.strptime(ticket_data.get('created_at'), '%Y-%m-%dT%H:%M:%S.%fZ').strftime('%Y-%m-%d %H:%M:%S') if ticket_data.get('created_at') else None,
|
||||
'closed_date': datetime.strptime(ticket_data.get('last_close_at'), '%Y-%m-%dT%H:%M:%S.%fZ').strftime('%Y-%m-%d %H:%M:%S') if ticket_data.get('last_close_at') else None,
|
||||
'organization_domain': org_dict.get(ticket_data.get('organization_id')),
|
||||
'time_unit': ticket_data.get('time_unit') if ticket_data.get('time_unit') is not None else "0",
|
||||
'created_by': user_dict.get(ticket_data.get('created_by_id'), {}).get('login')
|
||||
}
|
||||
for ticket_id in ticket_ids
|
||||
if (ticket_data := ticket_assets.get(str(ticket_id)))
|
||||
]
|
||||
|
||||
# Ausgabe der gefilterten Tickets als JSON-String
|
||||
json_output = json.dumps(filtered_tickets, indent=4, ensure_ascii=False)
|
||||
|
||||
|
||||
for tickets in filtered_tickets:
|
||||
# POST-Anfrage an den anderen API-Server
|
||||
print(tickets)
|
||||
response_post = requests.post(f"{api_url}/post/tickets", headers=headers_api, json=tickets)
|
||||
|
||||
# Überprüfen der Antwort des API-Servers
|
||||
if response_post.status_code == 200 or response_post.status_code == 201:
|
||||
print("Data successfully posted.")
|
||||
else:
|
||||
print(f"Failed to post data. Status code: {response_post.status_code}")
|
||||
print(f"Response content: {response_post.content.decode('utf-8')}")
|
||||
|
||||
else:
|
||||
print(f"Failed to retrieve tickets. Status code: {response_tickets.status_code}")
|
||||
else:
|
||||
if response_org.status_code != 200:
|
||||
print(f"Failed to retrieve organizations. Status code: {response_org.status_code}")
|
||||
if response_user.status_code != 200:
|
||||
print(f"Failed to retrieve users. Status code: {response_user.status_code}")
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import socket
|
||||
|
||||
def get_local_ip():
|
||||
try:
|
||||
# Ein temporärer Socket erstellen, um die lokale IP-Adresse zu ermitteln
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
# Verbindung zu einem öffentlichen DNS-Server herstellen
|
||||
s.connect(("8.8.8.8", 80))
|
||||
# Die lokale IP-Adresse aus dem Socket abrufen
|
||||
local_ip = s.getsockname()[0]
|
||||
s.close()
|
||||
return local_ip
|
||||
except Exception as e:
|
||||
print(f"Fehler beim Ermitteln der lokalen IP-Adresse: {e}")
|
||||
return None
|
||||
78
main.py
78
main.py
|
|
@ -1,74 +1,6 @@
|
|||
import time
|
||||
import update_check
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import requests
|
||||
import functions.ipaddress
|
||||
## Services Abfrage am API Server mit IP-Adresse
|
||||
|
||||
api_server = "http://api.stines.de:8001/"
|
||||
api_key = "^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8"
|
||||
headers = {"Content-Type":"application/json",
|
||||
"access_token":f"{api_key}"}
|
||||
|
||||
service_ID = []
|
||||
|
||||
def restart_service():
|
||||
check_os = platform.system()
|
||||
if check_os == ("Linux"):
|
||||
os.popen("systemctl restart agents.services")
|
||||
print("Yes Man!")
|
||||
else:
|
||||
subprocess.run('sc', 'start', 'Agents')
|
||||
|
||||
def get_response(endpoint,data):
|
||||
response = requests.get(f"{api_server}{endpoint}",headers=headers, json=data)
|
||||
print(response.text)
|
||||
return response.text
|
||||
|
||||
def post_response(endpoint, data):
|
||||
response = requests.post(f"{api_server}{endpoint}",headers=headers, json=data)
|
||||
print(response.text)
|
||||
return response.text
|
||||
|
||||
def check_update():
|
||||
if update_check.check_version() == True:
|
||||
restart_service()
|
||||
post_response("update_checked",{"ipaddress":f'{functions.ipaddress.get_local_ip()}',"version": update_check.current_version})
|
||||
|
||||
def ping():
|
||||
post_response("ping",{"ipaddress":f'{functions.ipaddress.get_local_ip()}'})
|
||||
|
||||
def controller_systeminfo():
|
||||
## Check RAM
|
||||
## Check CPU
|
||||
## Check HDD
|
||||
print("controller.systeminfo()")
|
||||
|
||||
def services_run():
|
||||
service_ID = get_response("get/service",{"ipaddress":f'{functions.ipaddress.get_local_ip()}'})
|
||||
print(service_ID)
|
||||
|
||||
|
||||
def main_loop():
|
||||
tasks = [
|
||||
{"interval": 30, "last_run": time.time(), "functions": [ping,services_run]},
|
||||
{"interval": 60, "last_run": time.time(), "functions": [controller_systeminfo]},
|
||||
{"interval": 3600, "last_run": time.time(), "functions": [services_run]}
|
||||
]
|
||||
|
||||
while True:
|
||||
current_time = time.time()
|
||||
|
||||
for task in tasks:
|
||||
if current_time - task["last_run"] >= task["interval"]:
|
||||
for function in task["functions"]:
|
||||
function()
|
||||
task["last_run"] = current_time
|
||||
|
||||
# Eine kurze Pause, um die CPU nicht zu überlasten
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_loop()
|
||||
## Ping 10sec
|
||||
## Service Abfrage aller 60sec
|
||||
## time = 10
|
||||
## for i in time
|
||||
|
|
|
|||
|
|
@ -7,6 +7,4 @@ new_version = []
|
|||
|
||||
# Get Current Version of Files -> Verionfile txt on /opt/agents/version.txt
|
||||
|
||||
# Check Verison on Github by Curl http://172.17.1.251/sebastian.serfling/Agents/src/branch/main/version
|
||||
|
||||
# IF Version same ->
|
||||
# Check Verison on Github by Curl https://gitlab.stines.de
|
||||
41
test_loop.py
41
test_loop.py
|
|
@ -1,41 +0,0 @@
|
|||
import time
|
||||
|
||||
|
||||
def ping():
|
||||
print("Ping alle 30 Sekunden")
|
||||
|
||||
|
||||
def ping1():
|
||||
print("Ping1 alle 30 Sekunden")
|
||||
|
||||
|
||||
def ping2():
|
||||
print("Ping2 alle 60 Sekunden")
|
||||
|
||||
|
||||
def ping3():
|
||||
print("Ping3 alle 3600 Sekunden")
|
||||
|
||||
|
||||
def main_loop():
|
||||
tasks = [
|
||||
{"interval": 3, "last_run": time.time(), "functions": [ping, ping1]},
|
||||
{"interval": 6, "last_run": time.time(), "functions": [ping2]},
|
||||
{"interval": 36, "last_run": time.time(), "functions": [ping3]}
|
||||
]
|
||||
|
||||
while True:
|
||||
current_time = time.time()
|
||||
|
||||
for task in tasks:
|
||||
if current_time - task["last_run"] >= task["interval"]:
|
||||
for function in task["functions"]:
|
||||
function()
|
||||
task["last_run"] = current_time
|
||||
|
||||
# Eine kurze Pause, um die CPU nicht zu überlasten
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_loop()
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
import os
|
||||
import sys
|
||||
import requests
|
||||
import git
|
||||
import shutil
|
||||
|
||||
def current_version():
|
||||
current_version = open("version", "r").read()
|
||||
return current_version
|
||||
|
||||
def get_latest_release(owner, repo):
|
||||
url = f"http://gitlab.stines.de/api/v1/repos/sebastian.serfling/Agents/releases/latest"
|
||||
response = requests.get(url)
|
||||
response.raise_for_status()
|
||||
release_info = response.json()
|
||||
return release_info['name']
|
||||
|
||||
def check_version():
|
||||
new_version = get_latest_release("", "")
|
||||
if current_version() != new_version:
|
||||
try:
|
||||
git.Repo.clone_from("http://172.17.1.251/sebastian.serfling/Agents.git",f'../{get_latest_release("","")}')
|
||||
except:
|
||||
next
|
||||
if os.path.isdir(f"../{new_version}"):
|
||||
try:
|
||||
shutil.move("../latest", f"../{current_version}")
|
||||
except:
|
||||
print("folder not Found")
|
||||
shutil.move(f"../{new_version}", "../latest")
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
# Get Current Version of Files -> Verionfile txt on /opt/agents/version.txt
|
||||
|
||||
# Check Verison on Github by Curl http://172.17.1.251/sebastian.serfling/Agents/src/branch/main/version
|
||||
|
||||
# IF Version same -> close
|
||||
|
||||
# IF not same -> Update, restart service
|
||||
|
||||
Loading…
Reference in New Issue