Skip to content

Commit

Permalink
admin scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
geeknik committed Jun 19, 2023
1 parent bfa78bc commit ea49f7d
Show file tree
Hide file tree
Showing 30 changed files with 686 additions and 0 deletions.
37 changes: 37 additions & 0 deletions admin/backup_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

import os
import shutil
import datetime

def backup_files(source_directory, backup_directory):
try:
# Check if source directory exists
if not os.path.exists(source_directory):
raise FileNotFoundError(f"Source directory {source_directory} does not exist")

# Create backup directory if it does not exist
if not os.path.exists(backup_directory):
os.makedirs(backup_directory)

# Get current date and time to create a unique backup directory
current_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
backup_subdirectory = os.path.join(backup_directory, current_time)

# Create backup subdirectory
os.makedirs(backup_subdirectory)

# Copy files from source directory to backup directory
for filename in os.listdir(source_directory):
source_file = os.path.join(source_directory, filename)
destination_file = os.path.join(backup_subdirectory, filename)
shutil.copy2(source_file, destination_file)

print(f"Backup of files from {source_directory} completed successfully at {backup_subdirectory}")

except Exception as e:
print(f"An error occurred while backing up files: {str(e)}")

if __name__ == "__main__":
source_directory = "/path/to/source/directory"
backup_directory = "/path/to/backup/directory"
backup_files(source_directory, backup_directory)
26 changes: 26 additions & 0 deletions admin/change_file_permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import os
import sys

def change_file_permissions(filepath, permissions):
try:
os.chmod(filepath, permissions)
except FileNotFoundError:
print(f"File {filepath} not found.")
sys.exit(1)
except PermissionError:
print(f"Insufficient permissions to change the file {filepath}.")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {str(e)}")
sys.exit(1)

if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python change_file_permissions.py <filepath> <permissions>")
sys.exit(1)

filepath = sys.argv[1]
permissions = int(sys.argv[2], 8)

change_file_permissions(filepath, permissions)
27 changes: 27 additions & 0 deletions admin/change_owner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

import os
import sys

def change_owner(filename, user, group=None):
try:
os.chown(filename, user, group if group else user)
except FileNotFoundError:
print(f"File {filename} not found.")
sys.exit(1)
except PermissionError:
print("Permission denied.")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {str(e)}")
sys.exit(1)

if __name__ == "__main__":
if len(sys.argv) != 4:
print("Usage: change_owner.py <filename> <user> <group>")
sys.exit(1)

filename = sys.argv[1]
user = int(sys.argv[2])
group = int(sys.argv[3])

change_owner(filename, user, group)
14 changes: 14 additions & 0 deletions admin/check_disk_space.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

import os
import sys
import shutil

def check_disk_space():
total, used, free = shutil.disk_usage("/")

print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))

if __name__ == "__main__":
check_disk_space()
16 changes: 16 additions & 0 deletions admin/check_installed_software.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

import subprocess

def check_installed_software(software_name):
try:
output = subprocess.check_output("dpkg -s " + software_name, shell=True)
if "install ok installed" in output:
print(software_name + " is installed.")
else:
print(software_name + " is not installed.")
except subprocess.CalledProcessError:
print(software_name + " is not installed.")

if __name__ == "__main__":
software_name = input("Enter the name of the software to check: ")
check_installed_software(software_name)
21 changes: 21 additions & 0 deletions admin/check_service_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

import subprocess

def check_service_status(service_name):
try:
output = subprocess.check_output(
"systemctl is-active --quiet " + service_name, shell=True
)
if output == b'active\n':
print(f"The {service_name} is running.")
else:
print(f"The {service_name} is not running.")
except subprocess.CalledProcessError:
print(f"Failed to get the status of {service_name}.")

if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python check_service_status.py <service_name>")
sys.exit(1)
check_service_status(sys.argv[1])
18 changes: 18 additions & 0 deletions admin/clean_temp_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

import os
import shutil

def clean_temp_files():
temp_dir = '/tmp'
for filename in os.listdir(temp_dir):
file_path = os.path.join(temp_dir, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(f'Failed to delete {file_path}. Reason: {e}')

if __name__ == "__main__":
clean_temp_files()
28 changes: 28 additions & 0 deletions admin/copy_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import shutil
import sys
import os

def copy_files(src, dest):
try:
shutil.copy2(src, dest)
print(f"File {src} copied to {dest}")
except FileNotFoundError:
print(f"Source file {src} not found.")
except PermissionError:
print(f"Permission denied.")
except Exception as e:
print(f"Unable to copy file. Error: {str(e)}")

if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python copy_files.py <source> <destination>")
sys.exit(1)

source = sys.argv[1]
destination = sys.argv[2]

if not os.path.isfile(source):
print(f"Source file {source} does not exist.")
sys.exit(1)

copy_files(source, destination)
20 changes: 20 additions & 0 deletions admin/create_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

import os

def create_directory(directory_path):
try:
os.makedirs(directory_path)
print(f"Directory {directory_path} created successfully")
except FileExistsError:
print(f"Directory {directory_path} already exists")
except Exception as e:
print(f"Error occurred while creating directory {directory_path}: {str(e)}")

if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python create_directory.py <directory_path>")
sys.exit(1)

directory_path = sys.argv[1]
create_directory(directory_path)
26 changes: 26 additions & 0 deletions admin/create_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import os
import subprocess

def create_user(username, password):
try:
# Create a new user
subprocess.run(['useradd', '-m', username], check=True)

# Set the user's password
subprocess.run(['echo', f'{username}:{password}', '|', 'chpasswd'], check=True)

print(f'User {username} created successfully.')
except subprocess.CalledProcessError:
print(f'Failed to create user {username}.')

if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: create_user.py <username> <password>")
sys.exit(1)

username = sys.argv[1]
password = sys.argv[2]

create_user(username, password)
20 changes: 20 additions & 0 deletions admin/delete_directory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import os
import sys

def delete_directory(directory_path):
try:
if os.path.exists(directory_path):
os.rmdir(directory_path)
print(f"Directory {directory_path} deleted successfully.")
else:
print(f"Directory {directory_path} does not exist.")
except Exception as e:
print(f"An error occurred while deleting directory {directory_path}: {str(e)}")

if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python delete_directory.py <directory_path>")
sys.exit(1)

directory_path = sys.argv[1]
delete_directory(directory_path)
23 changes: 23 additions & 0 deletions admin/delete_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

import os
import sys

def delete_files(file_paths):
for file_path in file_paths:
try:
os.remove(file_path)
print(f"File {file_path} deleted successfully")
except FileNotFoundError:
print(f"File {file_path} does not exist")
except PermissionError:
print(f"Permission denied for deleting {file_path}")
except Exception as e:
print(f"Error occurred while deleting {file_path}: {str(e)}")

if __name__ == "__main__":
if len(sys.argv) < 2:
print("Please provide at least one file path to delete")
sys.exit(1)

file_paths = sys.argv[1:]
delete_files(file_paths)
21 changes: 21 additions & 0 deletions admin/delete_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

import os
import sys

def delete_user(username):
try:
result = os.system(f'userdel {username}')
if result == 0:
print(f'User {username} has been deleted successfully.')
else:
print(f'Failed to delete user {username}.')
except Exception as e:
print(f'An error occurred: {str(e)}')

if __name__ == "__main__":
if len(sys.argv) != 2:
print('Usage: python delete_user.py <username>')
sys.exit(1)

username = sys.argv[1]
delete_user(username)
17 changes: 17 additions & 0 deletions admin/install_software.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

import subprocess
import sys

def install_software(software_name):
try:
subprocess.check_call(['sudo', 'apt-get', 'install', '-y', software_name])
print(f"{software_name} installed successfully.")
except subprocess.CalledProcessError as e:
print(f"Failed to install {software_name}. Error: {e}")
sys.exit(1)

if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python install_software.py <software_name>")
sys.exit(1)
install_software(sys.argv[1])
27 changes: 27 additions & 0 deletions admin/list_directory_contents.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import os

def list_directory_contents(directory_path):
try:
# Check if the directory exists
if not os.path.isdir(directory_path):
print(f"The directory {directory_path} does not exist.")
return

# List the contents of the directory
directory_contents = os.listdir(directory_path)

# Print the contents of the directory
for content in directory_contents:
print(content)

except Exception as e:
print(f"An error occurred while listing the contents of the directory: {e}")

if __name__ == "__main__":
import sys
if len(sys.argv) != 2:
print("Usage: python list_directory_contents.py <directory_path>")
sys.exit(1)

directory_path = sys.argv[1]
list_directory_contents(directory_path)
11 changes: 11 additions & 0 deletions admin/list_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

import os
import pwd

def list_users():
users = pwd.getpwall()
for user in users:
print(f'Username: {user.pw_name}, User ID: {user.pw_uid}, Group ID: {user.pw_gid}, Home: {user.pw_dir}')

if __name__ == "__main__":
list_users()
26 changes: 26 additions & 0 deletions admin/log_system_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import os
import sys
import logging
from datetime import datetime

def log_system_errors():
log_file = "/var/log/syslog"
error_log_file = "system_errors.log"

if not os.path.exists(log_file):
print(f"Log file {log_file} does not exist.")
sys.exit(1)

with open(log_file, "r") as file:
lines = file.readlines()

with open(error_log_file, "w") as file:
for line in lines:
if "error" in line.lower():
file.write(line)

print(f"System errors have been logged in {error_log_file}.")

if __name__ == "__main__":
log_system_errors()
Loading

0 comments on commit ea49f7d

Please sign in to comment.