def _create_update_from_cfg(mode='create', uuid=None, vmcfg=None): ''' Create vm from configuration ''' ret = {} vmadm = _check_vmadm() # vmadm validate create|update [-f <filename>] cmd = 'echo {vmcfg} | {vmadm} validate {mode} {brand}'.format( vmadm=vmadm, mode=mode, brand=get(uuid)['brand'] if uuid is not None else '', vmcfg=_quote_args(json.dumps(vmcfg)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = _exit_status(retcode) if 'stderr' in res: if res['stderr'][0] == '{': ret['Error'] = json.loads(res['stderr']) else: ret['Error'] = res['stderr'] return ret # vmadm create|update [-f <filename>] cmd = 'echo {vmcfg} | {vmadm} {mode} {uuid}'.format( vmadm=vmadm, mode=mode, uuid=uuid if uuid is not None else '', vmcfg=_quote_args(json.dumps(vmcfg)) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = _exit_status(retcode) if 'stderr' in res: if res['stderr'][0] == '{': ret['Error'] = json.loads(res['stderr']) else: ret['Error'] = res['stderr'] return ret else: if res['stderr'].startswith('Successfully created VM'): return res['stderr'][24:] return True
def reprovision(vm, image, key='uuid'): ''' Reprovision a vm vm : string vm to be reprovisioned image : string uuid of new image key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 salt '*' vmadm.reprovision nacl c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 key=alias ''' ret = {} vmadm = _check_vmadm() if key not in ['uuid', 'alias', 'hostname']: ret['Error'] = 'Key must be either uuid, alias or hostname' return ret vm = lookup('{0}={1}'.format(key, vm), one=True) if 'Error' in vm: return vm if image not in __salt__['imgadm.list'](): ret['Error'] = 'Image ({0}) is not present on this host'.format(image) return ret # vmadm reprovision <uuid> [-f <filename>] cmd = 'echo {image} | {vmadm} reprovision {uuid}'.format( vmadm=vmadm, uuid=vm, image=_quote_args(json.dumps({'image_uuid': image})) ) res = __salt__['cmd.run_all'](cmd, python_shell=True) retcode = res['retcode'] if retcode != 0: ret['Error'] = res['stderr'] if 'stderr' in res else _exit_status(retcode) return ret return True
def delete(login): ''' Delete user account login : string login name CLI Example: .. code-block:: bash salt '*' pdbedit.delete wash ''' if login in list_users(False): res = __salt__['cmd.run_all']( 'pdbedit --delete {login}'.format(login=_quote_args(login)), ) if res['retcode'] > 0: return {login: res['stderr'] if 'stderr' in res else res['stdout']} return {login: '******'} return {login: '******'}
def modify( login, password=None, password_hashed=False, domain=None, profile=None, script=None, drive=None, homedir=None, fullname=None, account_desc=None, account_control=None, machine_sid=None, user_sid=None, reset_login_hours=False, reset_bad_password_count=False, ): ''' Modify user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the follwing can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter .. note:: if user is absent and password is provided, the user will be created CLI Example: .. code-block:: bash salt '*' pdbedit.modify inara fullname='Inara Serra' salt '*' pdbedit.modify simon password=r1v3r salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile' salt '*' pdbedit.modify mal account_control=NX ''' ret = 'unchanged' ## flag mapping flags = { 'domain': '--domain=', 'full name': '--fullname=', 'account desc': '--account-desc=', 'home directory': '--homedir=', 'homedir drive': '--drive=', 'profile path': '--profile=', 'logon script': '--script=', 'account flags': '--account-control=', 'user sid': '-U ', 'machine sid': '-M ', } ## field mapping provided = { 'domain': domain, 'full name': fullname, 'account desc': account_desc, 'home directory': homedir, 'homedir drive': drive, 'profile path': profile, 'logon script': script, 'account flags': account_control, 'user sid': user_sid, 'machine sid': machine_sid, } ## update password if password: ret = create(login, password, password_hashed)[login] if ret not in ['updated', 'created', 'unchanged']: return {login: ret} elif login not in list_users(False): return {login: '******'} ## check for changes current = get_user(login, hashes=True) changes = {} for key, val in provided.items(): if key in ['user sid', 'machine sid']: if val is not None and key in current and not current[key].endswith(str(val)): changes[key] = str(val) elif key in ['account flags']: if val is not None: if val.startswith('['): val = val[1:-1] new = [] for f in val.upper(): if f not in ['N', 'D', 'H', 'L', 'X']: log.warning( 'pdbedit.modify - unknown {f} flag for account_control, ignored'.format(f=f) ) else: new.append(f) changes[key] = "[{flags}]".format(flags="".join(new)) else: if val is not None and key in current and current[key] != val: changes[key] = val ## apply changes if len(changes) > 0 or reset_login_hours or reset_bad_password_count: cmds = [] for change in changes: cmds.append('{flag}{value}'.format( flag=flags[change], value=_quote_args(changes[change]), )) if reset_login_hours: cmds.append('--logon-hours-reset') if reset_bad_password_count: cmds.append('--bad-password-count-reset') res = __salt__['cmd.run_all']( 'pdbedit --modify --user {login} {changes}'.format( login=_quote_args(login), changes=" ".join(cmds), ), ) if res['retcode'] > 0: return {login: res['stderr'] if 'stderr' in res else res['stdout']} if ret != 'created': ret = 'updated' return {login: ret}
def create(login, password, password_hashed=False, machine_account=False): ''' Create user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text machine_account : boolean set to create a machine trust account instead CLI Example: .. code-block:: bash salt '*' pdbedit.create zoe 9764951149F84E770889011E1DC4A927 nthash salt '*' pdbedit.create river 1sw4ll0w3d4bug ''' ret = 'unchanged' ## generate nt hash if needed if password_hashed: password_hash = password.upper() password = "" # wipe password else: password_hash = generate_nt_hash(password) ## create user if login not in list_users(False): # NOTE: --create requires a password, even if blank res = __salt__['cmd.run_all']( cmd='pdbedit --create --user {login} -t {machine}'.format( login=_quote_args(login), machine="--machine" if machine_account else "", ), stdin="{password}\n{password}\n".format(password=password), ) if res['retcode'] > 0: return {login: res['stderr'] if 'stderr' in res else res['stdout']} ret = 'created' ## update password if needed user = get_user(login, True) if user['nt hash'] != password_hash: res = __salt__['cmd.run_all']( 'pdbedit --modify --user {login} --set-nt-hash={nthash}'.format( login=_quote_args(login), nthash=_quote_args(password_hash) ), ) if res['retcode'] > 0: return {login: res['stderr'] if 'stderr' in res else res['stdout']} if ret != 'created': ret = 'updated' return {login: ret}
def modify( login, password=None, password_hashed=False, domain=None, profile=None, script=None, drive=None, homedir=None, fullname=None, account_desc=None, account_control=None, machine_sid=None, user_sid=None, reset_login_hours=False, reset_bad_password_count=False, ): """ Modify user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the following can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter .. note:: if user is absent and password is provided, the user will be created CLI Example: .. code-block:: bash salt '*' pdbedit.modify inara fullname='Inara Serra' salt '*' pdbedit.modify simon password=r1v3r salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile' salt '*' pdbedit.modify mal account_control=NX """ ret = "unchanged" # flag mapping flags = { "domain": "--domain=", "full name": "--fullname=", "account desc": "--account-desc=", "home directory": "--homedir=", "homedir drive": "--drive=", "profile path": "--profile=", "logon script": "--script=", "account flags": "--account-control=", "user sid": "-U ", "machine sid": "-M ", } # field mapping provided = { "domain": domain, "full name": fullname, "account desc": account_desc, "home directory": homedir, "homedir drive": drive, "profile path": profile, "logon script": script, "account flags": account_control, "user sid": user_sid, "machine sid": machine_sid, } # update password if password: ret = create(login, password, password_hashed)[login] if ret not in ["updated", "created", "unchanged"]: return {login: ret} elif login not in list_users(False): return {login: "******"} # check for changes current = get_user(login, hashes=True) changes = {} for key, val in provided.items(): if key in ["user sid", "machine sid"]: if ( val is not None and key in current and not current[key].endswith(str(val)) ): changes[key] = str(val) elif key in ["account flags"]: if val is not None: if val.startswith("["): val = val[1:-1] new = [] for f in val.upper(): if f not in ["N", "D", "H", "L", "X"]: log.warning( "pdbedit.modify - unknown {f} flag for account_control, ignored".format( f=f ) ) else: new.append(f) changes[key] = "[{flags}]".format(flags="".join(new)) else: if val is not None and key in current and current[key] != val: changes[key] = val # apply changes if len(changes) > 0 or reset_login_hours or reset_bad_password_count: cmds = [] for change in changes: cmds.append( "{flag}{value}".format( flag=flags[change], value=_quote_args(changes[change]), ) ) if reset_login_hours: cmds.append("--logon-hours-reset") if reset_bad_password_count: cmds.append("--bad-password-count-reset") res = __salt__["cmd.run_all"]( "pdbedit --modify --user {login} {changes}".format( login=_quote_args(login), changes=" ".join(cmds), ), ) if res["retcode"] > 0: return {login: res["stderr"] if "stderr" in res else res["stdout"]} if ret != "created": ret = "updated" return {login: ret}
def create(login, password, password_hashed=False, machine_account=False): """ Create user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text machine_account : boolean set to create a machine trust account instead CLI Example: .. code-block:: bash salt '*' pdbedit.create zoe 9764951149F84E770889011E1DC4A927 nthash salt '*' pdbedit.create river 1sw4ll0w3d4bug """ ret = "unchanged" # generate nt hash if needed if password_hashed: password_hash = password.upper() password = "" # wipe password else: password_hash = generate_nt_hash(password) # create user if login not in list_users(False): # NOTE: --create requires a password, even if blank res = __salt__["cmd.run_all"]( cmd="pdbedit --create --user {login} -t {machine}".format( login=_quote_args(login), machine="--machine" if machine_account else "", ), stdin="{password}\n{password}\n".format(password=password), ) if res["retcode"] > 0: return {login: res["stderr"] if "stderr" in res else res["stdout"]} ret = "created" # update password if needed user = get_user(login, True) if user["nt hash"] != password_hash: res = __salt__["cmd.run_all"]( "pdbedit --modify --user {login} --set-nt-hash={nthash}".format( login=_quote_args(login), nthash=_quote_args(password_hash) ), ) if res["retcode"] > 0: return {login: res["stderr"] if "stderr" in res else res["stdout"]} if ret != "created": ret = "updated" return {login: ret}
def rotate(name, pattern=None, conf_file=default_conf, **kwargs): ''' Set up pattern for logging. .. versionchanged:: Nitrogen name : string alias for entryname pattern : string alias for log_file conf_file : string optional path to alternative configuration file **kwargs : boolean|string|int optional additional flags and parameters .. note:: ``name`` and ``pattern`` were kept for backwards compatibility reasons. ``name`` is an alias for the ``entryname`` argument, ``pattern`` is an alias for ``log_file``. These aliasses wil only be used if the ``entryname`` and ``log_file`` arguments are not passed. For a full list of arguments see ```logadm.show_args```. CLI Example: .. code-block:: bash salt '*' logadm.rotate myapplog pattern='/var/log/myapp/*.log' count=7 salt '*' logadm.rotate myapplog log_file='/var/log/myapp/*.log' count=4 owner=myappd mode='0700' ''' ## cleanup kwargs kwargs = salt.utils.clean_kwargs(**kwargs) ## inject name into kwargs if 'entryname' not in kwargs and name and not name.startswith('/'): kwargs['entryname'] = name ## inject pattern into kwargs if 'log_file' not in kwargs: if pattern and pattern.startswith('/'): kwargs['log_file'] = pattern # NOTE: for backwards compatibility check if name is a path elif name and name.startswith('/'): kwargs['log_file'] = name ## build command log.debug("logadm.rotate - kwargs: {}".format(kwargs)) command = "logadm -f {}".format(conf_file) for arg, val in kwargs.items(): if arg in option_toggles.values() and val: command = "{} {}".format( command, _arg2opt(arg), ) elif arg in option_flags.values(): command = "{} {} {}".format(command, _arg2opt(arg), _quote_args(str(val))) elif arg != 'log_file': log.warning( "Unknown argument {}, don't know how to map this!".format(arg)) if 'log_file' in kwargs: # NOTE: except from ```man logadm``` # If no log file name is provided on a logadm command line, the entry # name is assumed to be the same as the log file name. For example, # the following two lines achieve the same thing, keeping two copies # of rotated log files: # # % logadm -C2 -w mylog /my/really/long/log/file/name # % logadm -C2 -w /my/really/long/log/file/name if 'entryname' not in kwargs: command = "{} -w {}".format(command, _quote_args(kwargs['log_file'])) else: command = "{} {}".format(command, _quote_args(kwargs['log_file'])) log.debug("logadm.rotate - command: {}".format(command)) result = __salt__['cmd.run_all'](command, python_shell=False) if result['retcode'] != 0: return dict(Error='Failed in adding log', Output=result['stderr']) return dict(Result='Success')
def modify( login, password=None, password_hashed=False, domain=None, profile=None, script=None, drive=None, homedir=None, fullname=None, account_desc=None, account_control=None, machine_sid=None, user_sid=None, reset_login_hours=False, reset_bad_password_count=False, ): ''' Modify user account login : string login name password : string password password_hashed : boolean set if password is a nt hash instead of plain text domain : string users domain profile : string profile path script : string logon script drive : string home drive homedir : string home directory fullname : string full name account_desc : string account description machine_sid : string specify the machines new primary group SID or rid user_sid : string specify the users new primary group SID or rid account_control : string specify user account control properties .. note:: Only the follwing can be set: - N: No password required - D: Account disabled - H: Home directory required - L: Automatic Locking - X: Password does not expire reset_login_hours : boolean reset the users allowed logon hours reset_bad_password_count : boolean reset the stored bad login counter .. note:: if user is absent and password is provided, the user will be created CLI Example: .. code-block:: bash salt '*' pdbedit.modify inara fullname='Inara Serra' salt '*' pdbedit.modify simon password=r1v3r salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile' salt '*' pdbedit.modify mal account_control=NX ''' ret = 'unchanged' ## flag mapping flags = { 'domain': '--domain=', 'full name': '--fullname=', 'account desc': '--account-desc=', 'home directory': '--homedir=', 'homedir drive': '--drive=', 'profile path': '--profile=', 'logon script': '--script=', 'account flags': '--account-control=', 'user sid': '-U ', 'machine sid': '-M ', } ## field mapping provided = { 'domain': domain, 'full name': fullname, 'account desc': account_desc, 'home directory': homedir, 'homedir drive': drive, 'profile path': profile, 'logon script': script, 'account flags': account_control, 'user sid': user_sid, 'machine sid': machine_sid, } ## update password if password: ret = create(login, password, password_hashed)[login] if ret not in ['updated', 'created', 'unchanged']: return {login: ret} elif login not in list_users(False): return {login: '******'} ## check for changes current = get_user(login, hashes=True) changes = {} for key, val in provided.items(): if key in ['user sid', 'machine sid']: if val is not None and key in current and not current[ key].endswith(str(val)): changes[key] = str(val) elif key in ['account flags']: if val is not None: if val.startswith('['): val = val[1:-1] new = [] for f in val.upper(): if f not in ['N', 'D', 'H', 'L', 'X']: log.warning( 'pdbedit.modify - unknown {f} flag for account_control, ignored' .format(f=f)) else: new.append(f) changes[key] = "[{flags}]".format(flags="".join(new)) else: if val is not None and key in current and current[key] != val: changes[key] = val ## apply changes if len(changes) > 0 or reset_login_hours or reset_bad_password_count: cmds = [] for change in changes: cmds.append('{flag}{value}'.format( flag=flags[change], value=_quote_args(changes[change]), )) if reset_login_hours: cmds.append('--logon-hours-reset') if reset_bad_password_count: cmds.append('--bad-password-count-reset') res = __salt__['cmd.run_all']( 'pdbedit --modify --user {login} {changes}'.format( login=_quote_args(login), changes=" ".join(cmds), ), ) if res['retcode'] > 0: return {login: res['stderr'] if 'stderr' in res else res['stdout']} if ret != 'created': ret = 'updated' return {login: ret}