def username_exists(username): try: sh.id(username) except sh.ErrorReturnCode_1: return False else: return True
def make_user( username: str = "demo_user", password: str = None, *, add_home: bool = True, home_dir: Path = None, allow_existing_user: bool = True, get_sudo: bool = True, ) -> None: """ """ import crypt import sh import getpass query = [] if add_home: query += [f"-m", f"-d"] if home_dir: query += [str(home_dir)] else: query += [f"/home/{username}"] try: user_id = sh.id(["-u", username]) if int(user_id): if not allow_existing_user: raise FileExistsError group_id = sh.id(["-g", username]) print(f"user {username} exists with id {user_id} and {group_id}") except (ValueError, sh.ErrorReturnCode_1): pass with ContextWrapper( sh.contrib.sudo, construction_kwargs=dict( password=getpass.getpass( prompt=f"[sudo] password for {getpass.getuser()}: ") if get_sudo else None, _with=True, ), enabled=get_sudo, ): try: sh.useradd(query + [ f"-p", f"{crypt.crypt(password if password else input(f'new password for user {username}: '), '22')}", f"{username}", ]) except sh.ErrorReturnCode_9: pass
def remove_user(username: str = "demo_user", *, remove_home: bool = True, get_sudo: bool = True) -> None: """ """ import sh import getpass try: user_id = sh.id(["-u", username]) if int(user_id): print(f"User {username} exists with id {user_id}") with ContextWrapper( sh.contrib.sudo, construction_kwargs=dict( password=getpass.getpass( prompt=f"[sudo] password for {getpass.getuser()}: " ) if get_sudo else None, _with=True, ), enabled=get_sudo, ): sh.userdel((["-r"] if remove_home else []) + [f"{username}"]) print(f"Removed user {username}") except (ValueError, sh.ErrorReturnCode_1): pass
def check_and_delete(username): """ Check if the user exists before killing his processes and deleting him. Raise UsernameException when user doesn't exist. """ try: sh.id(username) except sh.ErrorReturnCode: raise UsernameException( 400, {'error': 'Username {0} does not exist.'.format(username)}) # User exists, kill him try: sh.pkill('-u', username, '-9') except sh.ErrorReturnCode: pass sh.userdel('-r', username)
def check_security(username): try: result = sh.id('-G', username) ids = [int(x) for x in result.stdout.decode('ascii').split()] return valid_group_id in ids except Exception as e: logging.error(f'get id error for {username}, reason {str(e)}') return False
def check_and_add(username): """ Check if the user already exists. Raise UsernameException when it exists, create when not. """ try: sh.id(username) except sh.ErrorReturnCode: if not os.path.exists(PATH_PREFIX): # If the initial homes don't exist, create them with the right mode os.makedirs(PATH_PREFIX, mode=0o755) # User does not exist, add it sh.useradd( username, '-b', PATH_PREFIX, '-p', '*', '-s', '/bin/bash') return raise UsernameException( 400, {'error': 'Username {0} already exists.'.format(username)})
def main(): image = "boisgera/pandoc" # Register the current user and commit the image username = os.environ["USER"] userid = str(sh.id("-u", username)).strip() cmd = ["useradd", "-u", userid, username] sh.docker.run(image, cmd) container_id = str(sh.docker.ps("-ql")).strip() image = str(sh.docker.commit(container_id)).strip() # Execute the command. cmd = " ".join(sys.argv[1:]) or "true" mount = ["-v", "{cwd}:/tmp".format(cwd=Path.cwd())] as_user = ["-u", username] bash = "/bin/bash -c".split() cmd = "cd /tmp && " + cmd for line in sh.docker.run(mount, as_user, image, bash, cmd, _iter=True): print(line, end="")
def main(): parser = argparse.ArgumentParser() parser.add_argument('-b', '--brute', action='store_true', help='brute force login of camera ap') parser.add_argument('-i', '--interface', action='store', help='the interface to use (required)', required=True) #add argument for external password list args = parser.parse_args() #do root check if sh.id().find('root') < 0: print 'you must be root, try again' sys.exit(0) if args.brute: scanner(True, args.interface) else: scanner(False, args.interface)
def test_short_bool_option(self): from sh import id i1 = int(id(u=True)) i2 = os.geteuid() self.assertEqual(i1, i2)
def worker(username): with sh.sudo('-u', username, _with=True): sleep(3) print username, sh.id()
def test_long_bool_option(self): from sh import id i1 = int(id(user=True, real=True)) i2 = os.getuid() self.assertEqual(i1, i2)
def install_service( service_entry_point_path: Path, service_name: str, *, description: str = None, auto_enable: bool = True, run_as: RunAsEnum = RunAsEnum.user, # get_sudo: bool = False, restart: RestartServiceEnum = RestartServiceEnum.on_failure, ) -> None: """ Args: :param restart: :param service_entry_point_path: :param service_name: :param description: :param auto_enable: :param run_as: """ assert (service_entry_point_path.is_file() and service_entry_point_path.name.endswith(".py")) project_service_name = f"{PROJECT_NAME}_service_{service_name}" user = getpass.getuser() systemd_service_file_path = target_service_path(project_service_name, run_as=run_as) print(f"Installing {systemd_service_file_path}") get_sudo = run_as != RunAsEnum.user with ContextWrapper( sh.contrib.sudo, construction_kwargs=dict( password=(getpass.getpass( prompt=f"[sudo] password for {user}: ") if get_sudo else None), _with=True, ), enabled=get_sudo, ): if run_as == RunAsEnum.app_user: service_user = service_name + "_user" make_user(service_user, get_sudo=False) service_target = "default.target" service_group = service_user elif run_as == RunAsEnum.root: service_user = "******" service_target = "multi-user.target" service_group = service_user elif run_as == RunAsEnum.user: service_user = user service_target = "default.target" service_group = service_user else: raise ValueError sh.touch(systemd_service_file_path) group_name = str(sh.id(["-g", "-n", service_user])).strip("\n") assert service_group == group_name current_owner = sh.ls("-l", systemd_service_file_path).split(" ")[2] if current_owner != service_user: # SETTING UP PERMISSIONS print( f"Changing owner of service file from {current_owner} to {service_user}" ) if run_as == RunAsEnum.root: group_name = "" else: print(f"with common group {group_name}") # group_id = sh.id(["-g", service_user]) sh.usermod(["-a", "-G", group_name, user]) # TODO: Polluting groups of user sh.chown( [f"{user}:{group_name}", service_entry_point_path] ) # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. sh.chown( [f"{user}:{group_name}", systemd_service_file_path] ) # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. print("writing service file") if not description: description = f"heimdallr service for {service_name}" with open(systemd_service_file_path, "w") as f: f.writelines( SERVICE_TEMPLATE.format( service_name=project_service_name, service_user=service_user, executable=sys.executable, description=description, service_entry_point_path=service_entry_point_path, service_target=service_target, service_group=service_group, restart=restart.value, )) sh.chown( [f"{service_user}:{group_name}", systemd_service_file_path] ) # If a colon but no group name follows the user name, that user is made the owner of the files and the group of the files is changed to that user's login group. sh.chmod(["664", systemd_service_file_path]) sh.chmod(["774", service_entry_point_path]) sh.systemctl("daemon-reload") # TODO: Requires sudo? if auto_enable: enable_service(service_name, get_sudo=False, run_as=run_as)
def _id(self): return str(sh.id())
def _sys_is_user(self, username): sys_user = id(username) return sys_user