Source code for reemote.operations.users.add_sudo_user1
# Copyright (c) 2025 Kim Jarvis TPF Software Services S.A. kim.jarvis@tpfsystems.com # This software is licensed under the MIT License. See the LICENSE file for details.#
[docs]classAdd_sudo_user:""" A class to encapsulate the functionality of adding a user with sudo privileges in Unix-like operating systems. It creates a new user account and configures sudo access by adding the user to the sudoers system. Attributes: user (str): The username to be created with sudo privileges. password (str): The password for the new user account. guard (bool): If `False` the user creation and sudo configuration will not be executed. sudo (bool): If `True`, the operations will be executed with `sudo` privileges. su (bool): If `True`, the operations will be executed with `su` privileges. **Examples:** .. code:: python # Create a new user with sudo privileges yield Add_sudo_user(user="admin", password="securepass123") # Create a sudo user with specific privilege escalation yield Add_sudo_user(user="deployer", password="deploy123", sudo=True) Usage: This class is designed to be used in a generator-based workflow where user creation and sudo configuration commands are yielded for execution on remote hosts. Notes: - The user creation uses `adduser -D` to create a system user without a home directory. - The password is set using `chpasswd` for secure password assignment. - Sudo privileges are configured by creating a builtin in `/etc/sudoers.d/` directory. - The operation includes cleanup of temporary builtin used during configuration. - The sudo configuration grants the user full sudo privileges (`ALL=(ALL:ALL) ALL`). """def__init__(self,user:str=None,password:str=None,guard:bool=True,sudo:bool=False,su:bool=False):self.user=userself.password=passwordself.guard=guardself.sudo=sudoself.su=sudef__repr__(self):return(f"Add_sudo_user("f"user={self.user!r}, "f"password={self.password!r}, "f"guard={self.guard!r}, "f"sudo={self.sudo!r}, su={self.su!r})")defexecute(self):ifself.guard:fromreemote.operations.server.shellimportShellfromreemote.operations.sftp.write_fileimportWrite_filefromreemote.operations.sftp.chmodimportChmodfromreemote.operations.sftp.removeimportRemoveyieldShell(f'adduser -D {self.user} && echo "{self.user}:{self.password}" | chpasswd',su=self.su)yieldRemove(path=f'/tmp/{self.user}',)yieldRemove(path='/tmp/set_owner.sh',)yieldWrite_file(path=f'/tmp/{self.user}',text=f'{self.user} ALL=(ALL:ALL) ALL')yieldWrite_file(path='/tmp/set_owner.sh',text=f'chown root:root /tmp/{self.user};cp /tmp/{self.user} /etc/sudoers.d')yieldChmod(path='/tmp/set_owner.sh',mode=0o755,)yieldShell("bash /tmp/set_owner.sh",su=self.su)