Change the default shell of the user

    CLI Example:

    .. code-block:: bash

        salt '*' user.chshell foo /bin/zsh
162350
def chshell(name, shell):
    '''
    
    '''
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError(
            'User \'{0}\' does not exist'.format(name)
        )
    if shell == pre_info['shell']:
        return True
    cmd = ['usermod', '-s', shell, name]
    __salt__['cmd.run'](cmd, python_shell=False)
    return info(name).get('shell') == shell
256381
def cli(env, user, template):
    
    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, user, 'username')

    user_template = {}
    if template is not None:
        try:
            template_object = json.loads(template)
            for key in template_object:
                user_template[key] = template_object[key]
        except ValueError as ex:
            raise exceptions.ArgumentError("Unable to parse --template. %s" % ex)

    result = mgr.edit_user(user_id, user_template)
    if result:
        click.secho("%s updated successfully" % (user), fg='green')
    else:
        click.secho("Failed to update %s" % (user), fg='red')
289687
def set_pidfile(pidfile, user):
    '''
    
    '''
    pdir = os.path.dirname(pidfile)
    if not os.path.isdir(pdir) and pdir:
        os.makedirs(pdir)
    try:
        with salt.utils.files.fopen(pidfile, 'w+') as ofile:
            ofile.write(str(os.getpid()))  # future lint: disable=blacklisted-function
    except IOError:
        pass

    log.debug('Created pidfile: %s', pidfile)
    if salt.utils.platform.is_windows():
        return True

    import pwd  # after confirming not running Windows
    #import grp
    try:
        pwnam = pwd.getpwnam(user)
        uid = pwnam[2]
        gid = pwnam[3]
        #groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
    except (KeyError, IndexError):
        sys.stderr.write(
            'Failed to set the pid to user: {0}. The user is not '
            'available.\n'.format(
                user
            )
        )
        sys.exit(salt.defaults.exitcodes.EX_NOUSER)

    if os.getuid() == uid:
        # The current user already owns the pidfile. Return!
        return

    try:
        os.chown(pidfile, uid, gid)
    except OSError as err:
        msg = (
            'Failed to set the ownership of PID file {0} to user {1}.'.format(
                pidfile, user
            )
        )
        log.debug('%s Traceback follows:', msg, exc_info=True)
        sys.stderr.write('{0}\n'.format(msg))
        sys.exit(err.errno)
    log.debug('Chowned pidfile: %s to user: %s', pidfile, user)
848825
def _fix_install_dir_for_user_site(self):
        
        if not self.user or not site.ENABLE_USER_SITE:
            return

        self.create_home_path()
        if self.install_userbase is None:
            msg = "User base directory is not specified"
            raise DistutilsPlatformError(msg)
        self.install_base = self.install_platbase = self.install_userbase
        scheme_name = os.name.replace('posix', 'unix') + '_user'
        self.select_scheme(scheme_name)
515530
def _handle_shell(self,cfg_file,*args,**options):
        """"""
        args = ("--interactive",) + args
        return supervisorctl.main(("-c",cfg_file) + args)
621932
function ShellCraft() {
  var self = this;

  var ArgumentsList = require('./lib/argumentslist.js');
  var Prompt = require('./lib/prompt.js');

  self._exit = false;
  self._shell = true; /* open the shell be default */
  self._scope = 'global';

  self.arguments = new ArgumentsList();
  self.arguments._add(
    'exit',
    new Command(
      function(callback) {
        self._exit = true;
        if (callback) {
          callback();
        }
      },
      {builtIn: true, scope: '*'},
      'exit the shell'
    )
  );

  self.arguments._add(
    'help',
    new Command(
      function(callback) {
        Object.keys(Object.getPrototypeOf(self.arguments)).forEach(function(
          fct
        ) {
          if (
            !self.arguments.hasOwnProperty(fct) &&
            !/^_/.test(fct) &&
            self.arguments[fct].type() === 'command' &&
            self.arguments[fct].isScoped(self._scope)
          ) {
            console.log(self.arguments[fct].help());
          }
        });

        console.log('');

        if (callback) {
          callback();
        }
      },
      {builtIn: true, scope: '*'},
      'list of commands'
    )
  );

  self.arguments._add(
    'scope',
    new Command(
      function(callback, scope) {
        self._scope = scope[0] || 'global';
        self.autocomplete.reload();
        self.prompt.setScope(self._scope !== 'global' ? scope : '');

        if (callback) {
          callback();
        }
      },
      {
        builtIn: true,
        scope: '*',
        params: {
          optional: 'scope',
        },
      },
      function() {
        var help = 'change scope';
        var scopes = [];

        /* Look for all available scopes */
        Object.keys(Object.getPrototypeOf(self.arguments)).forEach(function(
          fct
        ) {
          if (
            !self.arguments.hasOwnProperty(fct) &&
            !/^_/.test(fct) &&
            self.arguments[fct].type() === 'command'
          ) {
            var scope = self.arguments[fct].scope();
            if (scope === '*' || scope === 'global') {
              return;
            }

            if (scopes.indexOf(scope) === -1) {
              scopes.push(self.arguments[fct].scope());
            }
          }
        });

        var list = scopes.length ? ' (' + scopes.join(', ') + ')' : '';
        return help + list;
      }
    )
  );

  self.options = {
    version: '0.0.1',
  };
  self.prompt = new Prompt();
  self.extensions = {};

  /* HACK inquirer prefix */
  Object.keys(inquirer.prompt.prompts).forEach(function(prompt) {
    inquirer.prompt.prompts[prompt].prototype.getQuestion = function() {
      var msg = inquirer.prompt.prompts[
        prompt
      ].super_.prototype.getQuestion.bind(this)();
      return msg.replace(/[^ ]*\?[^ ]* /, '');
    };
  });
}
1260043
def shell():
    
    ctx = _get_shell_ctx()
    try:
        import IPython
        IPython.embed(header=_get_shell_banner(), user_ns=ctx)
    except ImportError:
        import code
        code.interact(banner=_get_shell_banner(verbose=True), local=ctx)
823017
def _default_runlevel():
    '''
    
    '''
    # Try to get the "main" default.  If this fails, throw up our
    # hands and just guess "2", because things are horribly broken
    try:
        with salt.utils.files.fopen('/etc/init/rc-sysinit.conf') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                if line.startswith('env DEFAULT_RUNLEVEL'):
                    runlevel = line.split('=')[-1].strip()
    except Exception:
        return '2'

    # Look for an optional "legacy" override in /etc/inittab
    try:
        with salt.utils.files.fopen('/etc/inittab') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                if not line.startswith('#') and 'initdefault' in line:
                    runlevel = line.split(':')[1]
    except Exception:
        pass

    # The default runlevel can also be set via the kernel command-line.
    # Kinky.
    try:
        valid_strings = set(
            ('0', '1', '2', '3', '4', '5', '6', 's', 'S', '-s', 'single'))
        with salt.utils.files.fopen('/proc/cmdline') as fp_:
            for line in fp_:
                line = salt.utils.stringutils.to_unicode(line)
                for arg in line.strip().split():
                    if arg in valid_strings:
                        runlevel = arg
                        break
    except Exception:
        pass

    return runlevel
321004
def run(self, commands=None, default_command=None, context=None):
        

        if commands:
            self._commands.update(commands)

            # HACK: Overriding the old shell isn't cool.
            # Should do it by default.
        from alchemist.commands import Shell
        self._commands['shell'] = Shell(context=context)

        if default_command is not None and len(sys.argv) == 1:
            sys.argv.append(default_command)

        try:
            result = self.handle(sys.argv[0], sys.argv[1:])
        except SystemExit as e:
            result = e.code

        sys.exit(result or 0)
530539
def shell(name=None, **attrs):
    
    attrs.setdefault('cls', Shell)
    return click.command(name, **attrs)
127226
def cmd_ls(self, *args):
        
        cmd_str = ' '.join(['ls'] + list(args))
        self.plugin.exec_shell(cmd_str)
128631
def install_user_command_legacy(command, **substitutions):
    '''
    '''
    path = flo('~/bin/{command}')
    install_file_legacy(path, **substitutions)
    run(flo('chmod 755 {path}'))
384989
def set_policy(vhost,
               name,
               pattern,
               definition,
               priority=None,
               runas=None,
               apply_to=None):
    '''
    
    '''
    if runas is None and not salt.utils.platform.is_windows():
        runas = salt.utils.user.get_user()
    if isinstance(definition, dict):
        definition = salt.utils.json.dumps(definition)
    if not isinstance(definition, six.string_types):
        raise SaltInvocationError(
            'The \'definition\' argument must be a dictionary or JSON string'
        )
    cmd = [RABBITMQCTL, 'set_policy', '-p', vhost]
    if priority:
        cmd.extend(['--priority', priority])
    if apply_to:
        cmd.extend(['--apply-to', apply_to])
    cmd.extend([name, pattern, definition])
    res = __salt__['cmd.run_all'](cmd, reset_system_locale=False, runas=runas, python_shell=False)
    log.debug('Set policy: %s', res['stdout'])
    return _format_response(res, 'Set')
906174
def create_ckan_ini(self):
        
        self.run_command(
            command='/scripts/run_as_user.sh /usr/lib/ckan/bin/paster make-config'
            ' ckan /project/development.ini',
            rw_project=True,
            ro={scripts.get_script_path('run_as_user.sh'): '/scripts/run_as_user.sh'},
            )
810587
def runas_unpriv(cmd, username, password, cwd=None):
    '''
    
    '''
    # Create a pipe to set as stdout in the child. The write handle needs to be
    # inheritable.
    c2pread, c2pwrite = salt.platform.win.CreatePipe(
        inherit_read=False, inherit_write=True,
    )
    errread, errwrite = salt.platform.win.CreatePipe(
        inherit_read=False, inherit_write=True,
    )

    # Create inheritable copy of the stdin
    stdin = salt.platform.win.kernel32.GetStdHandle(
            salt.platform.win.STD_INPUT_HANDLE,
    )
    dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True)

    # Get startup info structure
    startup_info = salt.platform.win.STARTUPINFO(
        dwFlags=win32con.STARTF_USESTDHANDLES,
        hStdInput=dupin,
        hStdOutput=c2pwrite,
        hStdError=errwrite,
    )

    username, domain = split_username(username)

    # Run command and return process info structure
    process_info = salt.platform.win.CreateProcessWithLogonW(
            username=username,
            domain=domain,
            password=password,
            logonflags=salt.platform.win.LOGON_WITH_PROFILE,
            commandline=cmd,
            startupinfo=startup_info,
            currentdirectory=cwd)

    salt.platform.win.kernel32.CloseHandle(dupin)
    salt.platform.win.kernel32.CloseHandle(c2pwrite)
    salt.platform.win.kernel32.CloseHandle(errwrite)
    salt.platform.win.kernel32.CloseHandle(process_info.hThread)

    # Initialize ret and set first element
    ret = {'pid': process_info.dwProcessId}

    # Get Standard Out
    fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT)
    with os.fdopen(fd_out, 'r') as f_out:
        ret['stdout'] = f_out.read()

    # Get Standard Error
    fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT)
    with os.fdopen(fd_err, 'r') as f_err:
        ret['stderr'] = f_err.read()

    # Get Return Code
    if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \
            win32con.WAIT_OBJECT_0:
        exitcode = salt.platform.win.wintypes.DWORD()
        salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess,
                                    ctypes.byref(exitcode))
        ret['retcode'] = exitcode.value

    # Close handle to process
    salt.platform.win.kernel32.CloseHandle(process_info.hProcess)

    return ret
1307632
def chgid(name, gid):
    '''
    
    '''
    if not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')
    pre_info = info(name)
    if not pre_info:
        raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
    if gid == pre_info['gid']:
        return True
    _dscl(
        ['/Users/{0}'.format(name), 'PrimaryGroupID', pre_info['gid'], gid],
        ctype='change'
    )
    # dscl buffers changes, sleep 1 second before checking if new value
    # matches desired value
    time.sleep(1)
    return info(name).get('gid') == gid
48520
def create_shell(shell=None, **kwargs):
    """"""
    if not shell:
        shell = config.default_shell
        if not shell:
            from rez.system import system
            shell = system.shell

    from rez.plugin_managers import plugin_manager
    return plugin_manager.create_instance('shell', shell, **kwargs)