Bash script to check for shell access

07
2014-07
  • Jeremy

    I am working on a shell script to easily manage accounts. I want to have an option to enable and disable shell access (which is easy) but the tricky part is finding if an account already has shell access so my script can show the proper options.

    This is what I currently have:

    Note: $account is the given account

    function checkIfShellAccess
    {
        ret=false
        getent passwd $account >'/bin/bash' 2>&1 && ret=true
    
        if $ret; then
            HAS_SHELL=1
        else
            HAS_SHELL=0
        fi
    }
    

    My issue is: When I run my script and check if the user has shell access I get the following notice:

    line 241: /bin/bash: Text file busy
    

    line 241 is:

    getent passwd $account >'/bin/bash' 2>&1 && ret=true
    

    I am using: CentOS release 6.5 (Final)

    Thanks for any help on this.

  • Answers
  • John1024
    getent passwd $account >'/bin/bash' 2>&1 && ret=true
    

    The above line is attempting to overwrite /bin/bash. You don't want to do that. To test for the presence of of /bin/bash in the line returned by getent, use instead:

    getent passwd "$account" | grep -q '/bin/bash' && ret=true
    

    This will work because grep sets an exit code according to whether it found the text.

    There are, however, many different shells that users can use. These can include csh, ksh, and zsh. When shell access is disabled, the shell is generally set to /bin/false. If this is true on your system, consider the test:

    getent passwd "$account" | grep -q '/bin/false' || ret=true
    

  • Related Question

    linux - Bash Script Exits su or ssh Session Rather than Script
  • Russ Bradberry

    I am using CentOS 5.4. I created a bash script that does some checking before running any commands. If the check fails, it will simply exit 0. The problem I am having is that on our server, the script will exit the su or ssh session when the exit 0 is called.

    #!/bin/bash
    # check if directory has contents and exit if none
    if [ -z "`ls /ebs_raid/import/*.txt 2>/dev/null`" ]; then
      echo "ok"
      exit 0
    fi
    

    here is the output:

    [root@ip-10-251-86-31 ebs_raid]# . test.sh 
    ok
    [russ@ip-10-251-86-31 ebs_raid]$
    

    as you can see, I was removed from my sudo session, if I wasn't in the sudo session, it would have logged me out of my ssh session. I am not sure what I am doing wrong here or where to start.


  • Related Answers
  • pgs

    When you use . to run a shell script it executes in the current shell rather than starting a new shell. Type bash test.sh to get the behaviour you want.