This repository has been archived on 2021-11-23. You can view files and clone it, but cannot push or open issues or pull requests.
sh_multi_install/users/vsrv/scripts/write_bashrc.py

106 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2021-04-21 10:20:38 +02:00
"""
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.
2021-04-21 10:25:12 +02:00
At first check for root
Then load all .bashrc files from /home/<user>/
Each folder in /home/ must contain a .bashrc file, if not it won't be created
Usage: sudo python write_bashrc.py <home-dir> <root-dir>
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'
2021-04-21 10:25:12 +02:00
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.')
2021-04-21 12:23:31 +02:00
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():
2021-04-21 10:25:12 +02:00
if len(sys.argv) < 3:
2021-04-21 10:25:54 +02:00
print('Usage: sudo python write_bashrc.py <home-dir> <root-dir>')
2021-04-21 10:25:12 +02:00
exit()
_check_dependencies()
2021-04-21 10:25:12 +02:00
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()