From 97fc68aa907374173d41146ec8f3e7580c4223c5 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Wed, 21 Apr 2021 10:15:52 +0200 Subject: [PATCH] Added python script to edit .bashrc for each user --- users/vsrv/scripts/write_bashrc.py | 96 ++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 users/vsrv/scripts/write_bashrc.py diff --git a/users/vsrv/scripts/write_bashrc.py b/users/vsrv/scripts/write_bashrc.py new file mode 100644 index 0000000..38e90d4 --- /dev/null +++ b/users/vsrv/scripts/write_bashrc.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +""" +# -*- coding: utf-8 -*- + +Write bashrc script +~~~~~~~~~~~~~~~~~~~ + +Script to comment all alias ls="ls *" to allow global bashrc alias ls="lsd" + +:copyright: (c) 2021 sh-edraft.de +:license: MIT, see LICENSE for more details. + +""" + +__title__ = 'sh_write_bashrc' +__author__ = 'Sven Heidemann' +__license__ = 'MIT' +__copyright__ = 'Copyright (c) 2021 sh-edraft.de' +__version__ = '2021.4' + +# At first check for root +# Then load all .bashrc files from /home// +# Each folder in /home/ must contain a .bashrc file, if not it won't be created + +import os +import sys + +_file_name = '.bashrc' + + +def _check_dependencies(): + if sys.platform != 'linux': + raise Exception('You must use this script on linux!') + + if os.geteuid() != 0: + raise PermissionError('You must be root to use this script on linux.') + + +def _load_all_scripts(home_dir: str, root_user_dir: str) -> list[str]: + files = [] + + for user in os.listdir(home_dir): + file = os.path.join(home_dir, user, _file_name) + if os.path.isfile(file): + files.append(file) + + file = os.path.join(root_user_dir, 'root', _file_name) + if os.path.isfile(file): + files.append(file) + + return files + + +def _edit_script(file: str): + lines: list[str] = [] + content = '' + + try: + with open(file, 'r') as f: + lines = f.readlines() + f.close() + except Exception as e: + print(e) + + for line in lines: + line_words = line.split() + e_line = ' '.join(line_words) + if not e_line.startswith('#') and e_line.startswith('alias ls'): + line = line.replace(e_line, f'#{e_line}') + + elif not e_line.startswith('#') and e_line.startswith('alias') and '\'ls' in e_line or '\"ls' in e_line: + line = line.replace(e_line, f'#{e_line}') + + content += line + + try: + pass + with open(file, 'w') as f: + f.write(content) + f.close() + except Exception as e: + print(e) + + +def main(): + _check_dependencies() + files = _load_all_scripts('/home/', '/root/') + for file in files: + _edit_script(file) + + print('Success!', '\nChanged files:') + print('\n'.join(files)) + + +if __name__ == '__main__': + main()