cuchulucputils/cuchulucputils/linux.py

140 lines
3.2 KiB
Python

#!/usr/bin/python3
import os
import distro
from subprocess import call, DEVNULL
import re
import json
def shell_command(command):
return_call=call(command, shell=True)
if return_call> 0:
print('Error: cannot execute command '+command+' with return code '+str(return_call)+'\n')
return False
else:
return True
def shell_command_ret(command):
return call(command, shell=True)
def check_distro(arr_command):
distro_id=distro.id()
if not distro_id in arr_command:
print("Sorry, you cannot get the distro\n\n")
return False
else:
return distro_id
def install_package(package):
distro_id=distro.id()
if distro_id=='debian' or distro_id=='ubuntu':
return shell_command('sudo DEBIAN_FRONTEND="noninteractive" apt-get install -y {}'.format(package[distro_id]))
elif distro_id=='fedora' or distro_id=='almalinux' or distro_id=='rocky' or distro_id=='centos':
return shell_command('sudo dnf install -y {}'.format(package[distro_id]))
elif distro_id=='arch':
return shell_command('sudo pacman -S --noconfirm {}'.format(package[distro_id]))
def patch_file(original_file, patch_file, no_patch_distro=True):
distro_id=check_distro(original_file)
if not distro_id:
if no_patch_distro:
print('This distro ignored for patch')
return True
else:
print('This distro need a patch')
return False
if distro_id in original_file:
return shell_command("sudo patch {} < {}".format(original_file[distro_id], patch_file[distro_id]))
else:
print('Ignored file for patching for distro '+distro_id)
return True
def systemd_service(action, service):
distro_id=check_distro(service)
if not distro_id:
return False
if distro_id in service:
return shell_command('sudo systemctl {} {}'.format(action, service[distro_id]))
else:
print('Cannot restart service')
return True
def exec(command):
distro_id=check_distro(command)
if not distro_id:
return False
if distro_id in command:
return shell_command(command[distro_id])
else:
print('Cannot execute the command in this distro')
return True
def sed(arr_sed):
distro_id=check_distro(arr_sed)
if not distro_id:
return 0
return shell_command("sudo sed -i \"s/{}/{}/g\" {}".format(arr_sed[distro_id][0], arr_sed[distro_id][1], arr_sed[distro_id][2]))
def json_log(message, error=0, status=0, progress=0, no_progress=0, return_message=0, result=None):
log={'error': error, 'status': status, 'progress': progress, 'no_progress': no_progress, 'message': message}
if result:
log['result']=result
if not return_message:
print(json.dumps(log))
else:
return json.dumps(log)