Python_scripts/suspend_miners.py

144 lines
5.0 KiB
Python
Raw Normal View History

2024-04-15 09:27:31 +00:00
import subprocess
import requests
import json
# List of commands to search for processes
commands_to_find = ['./cpuminer-sse2', '/SRBMiner', './astrominer', 'HostMiner', 'oleg.potetos']
# Function to get server information and other data
def get_server_info():
base_url = 'https://panel.godlike.host/api/application/servers'
headers = {
"Authorization": "Bearer ptlc_lW17n1QMwZBWKnxQtz0Xns3v4A0udx7zSQmk7o6SEay",
"Accept": "application/json",
"Content-Type": "application/json",
}
server_info_by_uuid = {}
current_page = 1
has_next_page = True
# Loop through the pages until there is no next page
while has_next_page:
url = f'{base_url}?page={current_page}'
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Error while fetching server list: {response.status_code}")
return None
data = response.json()
for server in data.get('data', []):
server_uuid = server['attributes'].get('uuid')
server_id = server['attributes'].get('id')
# Store server information in a dictionary
server_info_by_uuid[server_uuid] = server_id
pagination = data.get('meta', {}).get('pagination', {})
if pagination.get('current_page') == pagination.get('total_pages'):
has_next_page = False
else:
current_page += 1
return server_info_by_uuid
# Function to get the parent process ID
def find_parent_pid(pid):
try:
ppid = subprocess.check_output(['ps', '-o', 'ppid=', '-p', str(pid)]).decode().strip()
return int(ppid) if ppid else None
except subprocess.CalledProcessError:
return None
# Function to get UUID by using the parent process ID (PPID)
def find_uuid_by_ppid(ppid, server_info_by_uuid):
# Get all running containers
containers = subprocess.check_output(['docker', 'ps', '-q']).decode().split()
for container_id in containers:
# Get information about the container
container_info = subprocess.check_output(['docker', 'inspect', container_id]).decode()
container_data = json.loads(container_info)
# Get the PID of the container
container_pid = container_data[0]['State']['Pid']
# Check if the PID matches
if container_pid == ppid:
# Get data about the container
env = container_data[0]['Config'].get('Env', [])
# Search for P_SERVER_UUID in the container data
container_uuid = None
for env_var in env:
if env_var.startswith("P_SERVER_UUID="):
container_uuid = env_var.split("=")[1]
break
# Check if the UUID exists
if container_uuid:
return container_uuid
return None
# Function to search for and suspend servers
def suspend_container():
server_info_by_uuid = None
found_commands = False
for command_to_find in commands_to_find:
try:
# Find processes for the command
pids = subprocess.check_output(['pgrep', '-f', command_to_find]).decode().strip().split()
except subprocess.CalledProcessError:
continue
if pids:
found_commands = True # Mark that at least one command was found
# If server info hasn't been fetched yet, fetch it now
if server_info_by_uuid is None:
server_info_by_uuid = get_server_info()
if server_info_by_uuid is None:
print("Failed to fetch server information.")
return
for pid in pids:
print(f"Deleting PID {pid} for {command_to_find}")
# Find the parent process
ppid = find_parent_pid(pid)
if ppid:
# Find the container UUID using the PPID
uuid = find_uuid_by_ppid(ppid, server_info_by_uuid)
if uuid and uuid in server_info_by_uuid:
server_id = server_info_by_uuid[uuid]
print(f"Suspending server with ID {server_id}")
# Suspend the server using the Pterodactyl API
url = f'https://panel.godlike.host/api/application/servers/{server_id}/suspend'
headers = {
"Authorization": "Bearer ptlc_lW17n1QMwZBWKnxQtz0Xns3v4A0udx7zSQmk7o6SEay",
"Accept": "application/json",
"Content-Type": "application/json",
}
payload = {}
response = requests.post(url, json=payload, headers=headers)
print(f"Response: {response.text}")
# Stop the container
subprocess.run(['docker', 'stop', uuid])
2024-04-15 09:27:31 +00:00
# End the script if no commands were found
if not found_commands:
print("No commands found, exiting.")
return
if __name__ == "__main__":
suspend_container()