Adicionando usuários

Publicado por Marcelo Gonçalves da Cunha 22/05/2004

[ Hits: 15.208 ]

Download adicionauser.sh




Um programinha em shell script muito bom que adiciona usuários linux com muito pouco esforço.

  



Esconder código-fonte

#!/bin/bash

##########################################################################
# Program: /usr/sbin/adduser
# Purpose: Interactive front end to /usr/sbin/useradd for Slackware Linux
# Author : Stuart Winter <stuart@polplex.co.uk>
#          Based on the original Slackware adduser by Hrvoje Dogan
#          with modifications by Patrick Volkerding
# Brazilian Portuguese by Helio Cavichiolo Jr <helio@definitylinux.com.br>
# Version: 1.07
##########################################################################
# Uso....: adduser [<nome_do_novo_usuário>]
##########################################################################
# History #
###########
# v1.07 - 07/03/03
#       * When supplying a null string for the uid (meaning 'Choose next available'), 
#         if there were file names in the range 'a-z' in the pwd then the 
#         egrep command considered these files rather than the null string. 
#         The egrep expression is now in quotes.  
#         Reported & fixed by Vadim O. Ustiansky <sw>
# v1.06 - 31/03/03
#       * Ask to chown user.group the home directory if it already exists.
#         This helps reduce later confusion when adding users whose home dir
#         already exists (mounted partition for example) and is owned
#         by a user other than the user to which the directory is being
#         assigned as home.  Default is not to chown.
#         Brought to my attention by mRgOBLIN. <sw>
# v1.05 - 04/01/03
#       * Advise & prevent users from creating logins with '.' characters
#         in the user name. <sw>
#       * Made pending account creation info look neater <sw>
# v1.04 - 09/06/02
#       * Catered for shadow-4.0.3's 'useradd' binary that no longer
#         will let you create a user that has any uppercase chars in it
#         This was reported on the userlocal.org forums
#         by 'xcp' - thanks. <sw,pjv>
# v1.03 - 20/05/02
#       * Support 'broken' (null lines in) /etc/passwd and 
#         /etc/group files <sw>       
#       * For recycling UIDs (default still 'off'), we now look in 
#         /etc/login.defs for the UID_MIN value and use it
#         If not found then default to 1000 <sw>
# v1.02 - 10/04/02
#       * Fix user-specified UID bug. <pjv>
# v1.01 - 23/03/02
#       * Match Slackware indenting style, simplify. <pjv>
# v1.00 - 22/03/02
#       * Created
#######################################################################

# Path to files
pfile=/etc/passwd
gfile=/etc/group
sfile=/etc/shells

# Paths to binaries
useradd=/usr/sbin/useradd
chfn=/usr/bin/chfn
passwd=/usr/bin/passwd
chmod=/bin/chmod

# Defaults
defhome=/home
defshell=/bin/bash
defchmod=711 # home dir permissions - may be preferable to use 701, however.
defgroup=users

# Determine what the minimum UID is (for UID recycling)
# (we ignore it if it's not at the beginning of the line (i.e. commented out with #))
export recycleUIDMIN="$(grep ^UID_MIN /etc/login.defs | awk '{print $2}' 2>/dev/null)"
# If we couldn't find it, set it to the default of 1000
if [ -z "$recycleUIDMIN" ]; then
   export recycleUIDMIN=1000  # this is the default from Slackware's /etc/login.defs
fi


# This setting enables the 'recycling' of older unused UIDs.
# When you userdel a user, it removes it from passwd and shadow but it will
# never get used again unless you specify it expliticly -- useradd (appears to) just
# look at the last line in passwd and increment the uid.  I like the idea of 
# recycling uids but you may have very good reasons not to (old forgotten
# confidential files still on the system could then be owned by this new user).
# We'll set this to no because this is what the original adduser shell script
# did and it's what users expect.
recycleuids=no

# Function to read keyboard input.
# bash1 is broken (even ash will take read -ep!), so we work around
# it (even though bash1 is no longer supported on Slackware).
function get_input() { 
  local output
  if [ "`echo $BASH_VERSION | cut -b1`" = "1" ]; then
    echo -n "${1} " >&2 ; # fudge for use with bash v1
    read output
  else # this should work with any other /bin/sh
    read -ep "${1} " output
  fi
  echo $output
}

# Function to display the account info
function display () {
  local goose
  goose="$(echo $2 | cut -d ' ' -f 2-)"  # lop off the prefixed argument useradd needs
  echo -n "$1 "
  # If it's null then display the 'other' information
  if [ -z "$goose" -a ! -z "$3" ]; then 
    echo "$3" 
  else 
    echo "$goose" 
  fi
}

# Function to check whether groups exist in the /etc/group file
function check_group () {
  local got_error group
  if [ ! -z "$@" ]; then  
  for group in $@ ; do
    local uid_not_named="" uid_not_num=""
    grep -v "$^" $gfile | awk -F: '{print $1}' | grep "^${group}$" >/dev/null 2>&1 || uid_not_named=yes  
    grep -v "$^" $gfile | awk -F: '{print $3}' | grep "^${group}$" >/dev/null 2>&1 || uid_not_num=yes
    if [ ! -z "$uid_not_named" -a ! -z "$uid_not_num" ]; then
      echo "- Grupo '$group' não existe"
      got_error=yes
    fi
  done
  fi
  # Return exit code of 1 if at least one of the groups didn't exist
  if [ ! -z "$got_error" ]; then
    return 1
  fi
}   

#: Read the login name for the new user :#
#
# Remember that most Mail Transfer Agents are case independant, so having
# 'uSer' and 'user' may cause confusion/things to break.  Because of this,
# useradd from shadow-4.0.3 no longer accepts usernames containing uppercase,
# and we must reject them, too.

# Set the login variable to the command line param
echo
LOGIN="$1"
needinput=yes
while [ ! -z $needinput ]; do
  if [ -z "$LOGIN" ]; then 
    while [ -z "$LOGIN" ]; do LOGIN="$(get_input "Nome do login para o novo usuário []:")" ; done
  fi
  grep "^${LOGIN}:" $pfile >/dev/null 2>&1  # ensure it's not already used
  if [ $? -eq 0 ]; then
    echo "- O usuário '$LOGIN' já existe; favor escolher outro"
    unset LOGIN
  elif [ ! "$LOGIN" = "`echo $LOGIN | tr A-Z a-z`" ]; then # useradd does not allow uppercase
    echo "- O usuário '$LOGIN' contém caracteres ilegais (maiúsculo); favor escolher outro"
    unset LOGIN
  elif [ ! -z "$( echo $LOGIN | grep '\.' )" ]; then
    echo "- O usuário '$LOGIN' contém caracteres ilegais (ponto); favor escolher outro"
    unset LOGIN
  else
    unset needinput
  fi
done

# Display the user name passed from the shell if it hasn't changed
if [ "$1" = "$LOGIN" ]; then
  echo "Nome do login para o novo usuário: $LOGIN"
fi

#: Get the UID for the user & ensure it's not already in use :#
#
# Whilst we _can_ allow users with identical UIDs, it's not a 'good thing' because
# when you change password for the uid, it finds the first match in /etc/passwd 
# which isn't necessarily the correct user
#
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  _UID="$(get_input "ID do usuário ('UID') [ próximo disponível ]:")"
  grep -v "^$" $pfile | awk -F: '{print $3}' | grep "^${_UID}$" >/dev/null 2>&1
  if [ $? -eq 0 ]; then
    echo "- Esse UID já está em uso; favor escolher outro"
  elif [ ! -z "$(echo $_UID | egrep '[A-Za-z]')" ]; then
    echo "- Os UIDs são apenas numéricos"         
  else
    unset needinput
  fi
done
# If we were given a UID, then syntax up the variable to pass to useradd
if [ ! -z "$_UID" ]; then 
  U_ID="-u ${_UID}"
else
  # Will we be recycling UIDs?
  if [ "$recycleuids" = "yes" ]; then
    U_ID="-u $(awk -F: '{uid[$3]=1} END { for (i=ENVIRON["recycleUIDMIN"];i in uid;i++);print i}' $pfile)"
  fi   
fi

#: Get the initial group for the user & ensure it exists :#
#
# We check /etc/group for both the text version and the group ID number 
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  GID="$(get_input "Grupo principal [ ${defgroup} ]:")"
  check_group "$GID"
  if [ $? -gt 0 ]; then
    echo "- Favor escolher outro"
  else
    unset needinput 
  fi
done
# Syntax the variable ready for useradd
if [ -z "$GID" ]; then
  GID="-g ${defgroup}"
else
  GID="-g ${GID}"
fi

#: Get additional groups for the user :#
#
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  AGID="$(get_input "Grupos adicionais (separados por vírgulas) []:")"
  AGID="$(echo "$AGID" | tr -d ' ' | tr , ' ')" ; # fix up for parsing 
  if [ ! -z "$AGID" ]; then
    check_group "$AGID"  # check all groups at once (treated as N # of params)
    if [ $? -gt 0 ]; then
      echo "- Favor re-entrar os grupos"
    else
      unset needinput # we found all groups specified
      AGID="-G $(echo "$AGID" | tr ' ' ,)"
    fi
  else
    unset needinput   # we don't *have* to have additional groups
  fi
done

#: Get the new user's home dir :#
#       
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  HME="$(get_input "Home directory [ ${defhome}/${LOGIN} ]")"
  if [ -z "$HME" ]; then
    HME="${defhome}/${LOGIN}"
  fi 
  # Warn the user if the home dir already exists
  if [ -d "$HME" ]; then
    echo "- Atenção: '$HME' já existe !"
    getyn="$(get_input "  Quer escolher outro caminho para o diretório home ? (S/n) ")"
    if [ "$(echo $getyn | grep -i "n")" ]; then
      unset needinput
      # You're most likely going to only do this if you have the dir *mounted* for this user's $HOME
      getyn="$(get_input "  Ajustar o proprietário $LOGIN.$( echo $GID | awk '{print $2}') $HME ? (s/N) ")"
      if [ "$(echo $getyn | grep -i "s")" ]; then
         CHOWNHOMEDIR=$HME # set this to the home directory
      fi
    fi
  else
    unset needinput
  fi
done           
HME="-d ${HME}"  
    
#: Get the new user's shell :#
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  unset got_error
  SHL="$(get_input "Shell [ ${defshell} ]")"
  if [ -z "$SHL" ]; then
    SHL="${defshell}"
  fi 
  # Warn the user if the shell doesn't exist in /etc/shells or as a file
  if [ -z "$(grep "^${SHL}$" $sfile)" ]; then
    echo "- Atenção: ${SHL} não está no ${sfile} (poderá ser impedido de usar o FTP)"
    got_error=yes
  fi
  if [ ! -f "$SHL" ]; then
    echo "- Atenção: ${SHL} não existe como arquivo"
    got_error=yes
  fi
  if [ ! -z "$got_error" ]; then
    getyn="$(get_input "  Quer alterar o shell ? (S/n) ")"
    if [ "$(echo $getyn | grep -i "n")" ]; then
      unset needinput
    fi
  else
    unset needinput
  fi
done           
SHL="-s ${SHL}"

#: Get the expiry date :#
echo
needinput=yes
while [ ! -z "$needinput" ]; do
  EXP="$(get_input "Data de expiração (AAAA-MM-DD) []:")"
  if [ ! -z "$EXP" ]; then
    # Check to see whether the expiry date is in the valid format
    if [ -z "$(echo "$EXP" | grep "^[[:digit:]]\{4\}[-]\?[[:digit:]]\{2\}[-]\?[[:digit:]]\{2\}$")" ]; then
      echo "- Essa data não é uma data válida"
    else
      unset needinput 
      EXP="-e ${EXP}" 
    fi
  else
    unset needinput
  fi
done

# Display the info about the new impending account
echo
echo "A nova conta será criada como segue:"
echo
echo "---------------------------------------"
display "Nome do login....: " "$LOGIN"
display "UID..............: " "$_UID" "[ Próximo disponível ]"
display "Grupo principal..: " "$GID"
display "Grupos adicionais: " "$AGID" "[ Nenhum ]"
display "Diretório home...: " "$HME"
display "Shell............: " "$SHL"
display "Data de expiração: " "$EXP" "[ Nunca ]"
echo

echo "É isso aí... se quiser desistir, pressione Control-C. Caso contrário"
echo "pressione ENTER para seguir em frente e criar a conta."
read junk

echo
echo "Criando a nova conta..."
echo
echo

# Add the account to the system
CMD="$useradd "$HME" -m "$EXP" "$U_ID" "$GID" "$AGID" "$SHL" "$LOGIN""
$CMD

if [ $? -gt 0 ]; then
  echo "- Erro ao executar o comando useradd -- conta não criada!"
  echo "(cmd: $CMD)"
  exit 1
fi

# chown the home dir ?  We can only do this once the useradd has
# completed otherwise the user name doesn't exist.
if [ ! -z "${CHOWNHOMEDIR}" ]; then
  chown "$LOGIN"."$( echo $GID | awk '{print $2}')" "${CHOWNHOMEDIR}"
fi

# Set the finger information
$chfn "$LOGIN"
if [ $? -gt 0 ]; then
  echo "- Atenção: ocorreu um erro ao ajustar as informações do finger"
fi

# Set a password
$passwd "$LOGIN"
if [ $? -gt 0 ]; then
  echo "* ATENÇÃO: Ocorreu um erro ao ajustar a senha para esta"
  echo "           conta.  Favor investigar isto manualmente *"
  exit 1
fi

# If it was created (it should have been!), set the permissions for that user's dir 
HME="$(echo "$HME" | awk '{print $2}')"  # We have to remove the -g prefix
if [ -d "$HME" ]; then
  $chmod $defchmod "$HME"
fi

echo
echo
echo "Configuração da conta completada."
exit 0

Scripts recomendados

manutenção do squid

Ajuste de brilho do monitor

Backup Facil e rapido

Instalação do Layer7 e compilação do kernel (automático)

Instalação do Snoopy


  

Comentários
[1] Comentário enviado por flexsystem em 09/07/2004 - 23:08h

Exelente script, vai me ajudar um bocado. Parabéns!!!!

[2] Comentário enviado por edersomangelo em 03/11/2004 - 13:42h

Legal, gostei, me ajudou pakas!!!!!!!!!!

[3] Comentário enviado por isaacson em 28/02/2005 - 01:30h

vc tem um escripte com formulario para adicionar e deletrar usuario

[4] Comentário enviado por tecnet em 31/05/2005 - 17:25h

Legall, Ajuda muittooo messmooo!

[5] Comentário enviado por removido em 11/06/2005 - 13:57h

oi gostaria de saber como funciona este script para adicionar usuarios no linux.Em que diretorio devo colocar o script e com faço para criar nos usuarios?
Gostaria de saber tambem com fucionar o script de controle de espaço em disco pois e uma ferramente muito importante para mim, porem nao sei com executa-lo.
Aguardo Retorno
Obrigado.

[6] Comentário enviado por AlexPinto em 23/02/2010 - 11:27h

Bem feito, porem enorme hehe


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts