#!/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. 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 Usage: sudo python write_bashrc.py Example: sudo python write_bashrc.py /home/ /root/ """ __title__ = 'sh_write_bashrc' __author__ = 'Sven Heidemann' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2021 sh-edraft.de' __version__ = '2021.4' 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: 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(): if len(sys.argv) < 3: print('Usage: sudo python write_bashrc.py ') exit() _check_dependencies() files = _load_all_scripts(sys.argv[1], sys.argv[2]) for file in files: _edit_script(file) print('Success!', '\nChanged files:') print('\n'.join(files)) if __name__ == '__main__': main()