Linux Active Directory

Publicado por Fábio Antonio Ferreira (última atualização em 24/06/2011)

[ Hits: 7.015 ]

Homepage: http://fantonio.wordpress.com

Download 4978.linuxad.sh




Este script adiciona máquina linux ao dominio Windows.

  



Esconder código-fonte

#!/bin/sh

###############################################################################
# Copyright (C) 2011 - Fabio Antonio Ferreira                                 #
# http://fantonio.wordpress.com | fantonios@gmail.com                         #
#                                                                             #
# Este trabalho está licenciado sob uma Licença Creative Commons              #
# Atribuição-Compartilhamento pela mesma Licença 2.5 Brasil. Para ver a copia #
# desta licença, acesse: http://creativecommons.org/licenses/by-sa/2.5/br/    #
# ou envie uma carta para Creative Commons, 171 Second Street, Suite 300,     #
# San Francisco, California 94105, USA.                                       #
#                                                                             #
# Modificações em 15 de abril de 2011 por Fábio Antonio (fantonio)            #
#                                                                             #
###############################################################################
#
# Versão 1.0
# - Versão original
#

preto="{FONTE}33[0;30m"
vermelho="{FONTE}33[0;31m"
verde="{FONTE}33[0;32m"

# == FUNCOES ==================================================================
USUARIO=`whoami`
if [ "$USUARIO" != "root" ]; then 
  echo 
  echo "=============================================================================="
  echo " ESTE PROGRAMA PRECISA SER EXECUTADO COM PERMISSOES DE SUPERUSUARIO!          "  
  echo " Abortando...                              "
  echo "=============================================================================="
  echo 
  exit 1
fi

_HEAD () {
`which clear`
echo "=============================================================================="
echo "          SISTEMA PARA ADICIONAR MAQUINA LINUX AO DOMÍNIO WINDOWS"
echo "=============================================================================="
}

_PACOTES () {
        echo "Instalando os pacotes necessários";
        aptitude install krb5-user libpam-krb5 winbind samba smbfs smbclient krb5-config libkrb53 libkadm55 -y > /dev/null;
        check=$?
        if [ $check -eq 0 ]; then
           echo "Pacotes instalados com sucesso {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
        else
           echo "Falha ao instalar os pacotes {FONTE}33[0;31m [fail]  {FONTE}33[0m "
        fi
}

_HORA () {
        echo "Atualizando data e hora"; 
        ntpdate br.pool.ntp.org > /dev/null;
        echo "Horario atual:" `date`
        echo "Hora alterada com sucesso {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
}

_BACKUP_ORIG () {
        # Rotina de Backup dos arquivos de configurações.
        cp /etc/krb5.conf /etc/krb5.conf_backup > /dev/null
        cp /etc/samba/smb.conf /etc/samba/smb.conf_backup > /dev/null
        cp /etc/nsswitch.conf /etc/nsswitch.conf_backup > /dev/null
        cp /etc/pam.d/common-account /etc/pam.d/common-account_backup > /dev/null
        cp /etc/pam.d/common-auth /etc/pam.d/common-auth_backup > /dev/null
        cp /etc/pam.d/common-session /etc/pam.d/common-session_backup > /dev/null
        cp /etc/pam.d/sudo /etc/pam.d/sudo_backup > /dev/null
        
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Rotina de Backup executada com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao fazer o Backup. {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
        
}

_NOME_DOMINIO () {
        #Entrada do nome do dominio ao qual deseja engreçar.
        read -p "Entre com o nome do Domínio:" var1
        dominio=$(echo $var1 | tr a-z A-Z)
        read -p "Entre com o seu KDC (key Distribution Center):" var2
        kdc=$(echo $var2 | tr A-Z a-z)
        
}

_KRB5 () {
   echo "[libdefaults]
         default_realm = $dominio

# The following krb5.conf variables are only for MIT Kerberos.
      krb4_config = /etc/krb.conf
      krb4_realms = /etc/krb.realms
      kdc_timesync = 1 
      ccache_type = 4 
           forwardable = true
           proxiable = true

# The following libdefaults parameters are only for Heimdal Kerberos.
           v4_instance_resolve = false
           v4_name_convert = { 
                   host = { 
                           rcmd = host
                           ftp = ftp 
                   }   
                   plain = { 
                           something = something-else
                   }   
           }   
           fcc-mit-ticketflags = true

   [realms]
           $dominio = { 
                   kdc = $kdc
                   #kdc = $kdc2
                   #kdc = $kdc3
                   admin_server = $kdc
           }   
            
   [domain_realm]
           .$var1 = $kdc

   [login]
           krb4_convert = true
           krb4_get_tickets = false" > /etc/krb5.conf

   echo "Configuração alterada com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
}

_TESTEAD () {
   read -p "Entre com um usuário para testar sua conexão com o Active Directory:" user
   kinit $user@$dominio
   
   check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Sua máquina conectou com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao se conectar com o Active Directory {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
   
}

_SMB () {
   
   maquina=$(hostname)
   echo "# Sample configuration file for the Samba suite for Debian GNU/Linux.
   #======================= Global Settings =======================
   [global]
   #
   # Browsing/Identification ###
           workgroup = $var1
           netbios name = $maquina
           realm = $var1
   # server string is the equivalent of the NT Description field
      server string = %h Server
   # WINS Support - Tells the NMBD component of Samba to enable its WINS Server
   #   wins support = no
   # WINS Server - Tells the NMBD components of Samba to be a WINS Client
      ;   wins server = w.x.y.z
   # This will prevent nmbd to search for NetBIOS names through DNS.
      dns proxy = no
   # What naming service and in what order should we use to resolve host names
   # to IP addresses
      ;   name resolve order = lmhosts host wins bcast
   #### Networking ####
   # The specific set of interfaces / networks to bind to
      ;   interfaces = 127.0.0.0/8 eth0
   # Only bind to the named interfaces and/or networks; 
      ;   bind interfaces only = yes
   #
   #### Debugging/Accounting ####
   # This tells Samba to use a separate log file for each machine
   # that connects
      log file = /var/log/samba/log.%m
   # Cap the size of the individual log files (in KiB).
      max log size = 1000
   # We want Samba to log a minimum amount of information to syslog.
      syslog = 0
   # Do something sensible when Samba crashes: mail the admin a backtrace
      panic action = /usr/share/samba/panic-action %d
   
   ####### Authentication #######
      security = ADS
      password server = $kdc
   # You may wish to use password encryption.  See the section on
   # 'encrypt passwords' in the smb.conf(5) manpage before enabling.
      encrypt passwords = true
   # If you are using encrypted passwords, Samba will need to know what
   # password database type you are using.  
      passdb backend = tdbsam
      obey pam restrictions = yes
   # This boolean parameter controls whether Samba attempts to sync the Unix
   # password with the SMB password when the encrypted SMB password in the
   # passdb is changed.
      unix password sync = yes
   # For Unix password sync to work on a Debian GNU/Linux system,
      passwd program = /usr/bin/passwd %u
      passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
   # This boolean controls whether PAM will be used for password changes
   # when requested by an SMB client instead of the program listed in
   # 'passwd program'. The default is 'no'.
      pam password change = yes
   ########## Domains ###########
   # Is this machine able to authenticate users. Both PDC and BDC
   # must have this setting enabled. If you are the BDC you must
   # change the 'domain master' setting to no
   #
      ;   domain logons = yes
   # The following required a [profiles] share to be setup on the
   # samba server (see below)
      ;   logon path = \\%N\profiles\%U
   # The following setting only takes effect if 'domain logons' is set
   # It specifies the location of a user's home directory (from the client
   # point of view)
      ;   logon drive = H:
   # The following setting only takes effect if 'domain logons' is set
   # It specifies the script to run during logon.
      ;   logon script = logon.cmd
   # This allows Unix users to be created on the domain controller via the SAMR
   # RPC pipe.  
      ; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u
   # The following assumes a "machines" group exists on the system
      ; add machine script  = /usr/sbin/useradd -g machines -c "%u machine account" -d /var/lib/samba -s /bin/false %u
   # This allows Unix groups to be created on the domain controller via the SAMR
      ; add group script = /usr/sbin/addgroup --force-badname %g
   ########## Printing ##########
   # printcap file
      ;   printing = bsd
      ;   printcap name = /etc/printcap
   # CUPS printing.  See also the cupsaddsmb(8) manpage in the
   # cupsys-client package.
      ;   printing = cups
      ;   printcap name = cups
   ############ Misc ############

   # Using the following line enables you to customise your configuration
   # on a per machine basis.
      ;   include = /home/samba/etc/smb.conf.%m
   # The following parameter is useful only if you have the linpopup package installed.
      ;   message command = /bin/sh -c '/usr/bin/linpopup "%f" "%m" %s; rm %s' &
   # Domain Master specifies Samba to be the Domain Master Browser.
      idmap uid = 10000-20000
      winbind gid = 10000-20000
      winbind enum users = yes
      winbind enum groups = yes
      winbind use default domain = yes
      template homedir = /home/%D/%U
      template shell = /bin/bash
   # Maximum number of usershare. 0 (default) means that usershare is disabled.
      ;   usershare max shares = 100
   #======================= Share Definitions =======================

   [homes]
      comment = Home Directories
      browseable = no
   # By default, the home directories are exported read-only.
      read only = yes
   # File creation mask is set to 0700 for security reasons. 
      create mask = 0700
   # Directory creation mask is set to 0700 for security reasons.
      directory mask = 0700
   # This might need tweaking when using external authentication schemes
      valid users = %S
   # Un-comment the following and create the netlogon directory for Domain Logons
   # (you need to configure Samba to act as a domain controller too.)
      ;[netlogon]
         ;   comment = Network Logon Service
         ;   path = /home/samba/netlogon
         ;   guest ok = yes
         ;   read only = yes
         ;   share modes = no
   # The path below should be writable by all users so that their
   # profile directory may be created the first time they log on
      ;[profiles]
         ;   comment = Users profiles
         ;   path = /home/samba/profiles
         ;   guest ok = no
         ;   browseable = no
         ;   create mask = 0600
         ;   directory mask = 0700
   [printers]
      comment = All Printers
      browseable = no
      path = /var/spool/samba
      printable = yes
      guest ok = no
      read only = yes
      create mask = 0700

   # Windows clients look for this share name as a source of downloadable
   # printer drivers
   [print$]
      comment = Printer Drivers
      path = /var/lib/samba/printers
      browseable = yes
      read only = yes
      guest ok = no
   # Please note that you also need to set appropriate Unix permissions
   # to the drivers directory for these users to have write rights in it
      ;   write list = root, @lpadmin
   # A sample share for sharing your CD-ROM with others.
      ;[cdrom]
         ;   comment = Samba server's CD-ROM
         ;   read only = yes
         ;   locking = no
         ;   path = /cdrom
         ;   guest ok = yes
   # If you don't want to use auto-mounting/unmounting make sure the CD
   #       is mounted on /cdrom
      ;   preexec = /bin/mount /cdrom
      ;   postexec = /bin/umount /cdrom" > /etc/samba/smb.conf

   echo "Configuração alterada com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
}

_FUNC_RESTART() {
        # Stop Winbind
        /etc/init.d/winbind stop > /dev/null
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Winbind Stop! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao parar o Winbind {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
        # Restart Samba
        /etc/init.d/samba restart > /dev/null
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Samba restart com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha no restart do Samba! {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
        # Start Winbind
        /etc/init.d/winbind start > /dev/null
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Winbind start! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao fazer iniciar o Winbind! {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
}

_ADDDOMINIO () {

   azul="{FONTE}33[0;34m"
   echo "++++++++++++++++++++++++++++++++++++++++++++"
   echo "++  {FONTE}33[0;34m Adicionando a Máquina no Domínio {FONTE}33[0m    ++"
   echo "++++++++++++++++++++++++++++++++++++++++++++"
        # Adicionando a máquina ao domínio
        read -p "Entre com um usuário administrador de Domínio:" user   
   net ads join -U $user; 
        check=$(echo $?)
        clear
        # Validação da conexão com o domínio
        if [ $check -eq 0 ]; then
      echo "Sua máquina foi adicionada no Domínio! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao adicionar a máquina no Domínio {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
   
}

_TESTDOMINIO () {
        # Teste de requisição ao dominio
        wbinfo -t > /dev/null
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Teste de Domínio! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao testar o Domínio {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
}

_FUNCAUTENTICACAO () {
        # Configurando o arquivo nsswitch.conf
        echo "passwd:         compat winbind
              group:          compat winbind
              shadow:         compat" > /etc/nsswitch.conf

        # Teste de configuração do Winbind        
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "Winbind testado com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao testar o Winbind {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi
        # PAM - common-account
        echo "account sufficient       pam_winbind.so
              account required         pam_unix.so" > /etc/pam.d/common-account
        # PAM - common-auth 
        echo "auth sufficient pam_winbind.so
              auth sufficient pam_unix.so nullok_secure use_first_pass
              auth required   pam_deny.so" > /etc/pam.d/common-auth
        # PAM - common-session       
        echo "session required pam_unix.so
              session required pam_mkhomedir.so umask=0022 skel=/etc/skel" > /etc/pam.d/common-session
        # PAM - sudo
        echo "auth sufficient pam_winbind.so
              auth sufficient pam_unix.so use_first_pass
              auth required   pam_deny.so
              @include common-account" > /etc/pam.d/sudo
        # Teste de configuração do PAM
        check=$(echo $?)
   if [ $check -eq 0 ]; then
      echo "PAM configurado com sucesso! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
   else
      echo "Falha ao configurar o PAM {FONTE}33[0;31m [fail]  {FONTE}33[0m "
   fi

}

_FUNC_HOMEDIR () {
        HOME_DIR=$var1
        if [ -d /home/$HOME_DIR ]; then
                echo "Já existe este diretório !"                
        else
                echo "Este diretório não existe !"
                echo "Criando o diretório $HOME_DIR"
      mkdir /home/$var1
                sleep 2
        fi
}

_FUNC_DEL_MAQ_DOMINIO () {
   
   maquina=$(hostname)
        azul="{FONTE}33[0;34m"
        echo "++++++++++++++++++++++++++++++++++++++++++++"
        echo "++  {FONTE}33[0;34m Removendo a Máquina no Domínio {FONTE}33[0m ++"
        echo "++++++++++++++++++++++++++++++++++++++++++++"
      
        # Remover a máquina ao domínio
        read -p "Entre com um usuário administrador de Domínio:" user
   net ads status -U $user
   check1=$(echo $?)
   clear
   # Validação se a máquina está no domínio
   if [ $check1 -eq 255 ]; then
      echo "A máquina $maquina não está no dominio"
   else
      # Validação de remoção de máquina do domínio
      net ads leave -U $user;
      check=$(echo $?)
      clear
      if [ $check -eq 0 ]; then
         echo "Sua máquina foi removida do Domínio! {FONTE}33[0;32m [Ok]  {FONTE}33[0m "
      else
         echo "Falha ao remover a máquina no Domínio {FONTE}33[0;31m [fail]  {FONTE}33[0m "
      fi
   fi

}


# =============================================================================
# Menu de seleção 
echo "Linux Active Directory:"
echo "(1) Adicionar Máquina no Domínio"
echo "(2) Remover Máquina do Domínio"
echo "(3) Verificar conexão com o Domínio"
echo "(0) Sair"

echo "Digite a opção desejada:"
read resposta

case "$resposta" in
        1)  
      _HEAD
      _PACOTES
      _HORA
      _BACKUP_ORIG
        _NOME_DOMINIO
      _KRB5
      _TESTEAD
      _SMB
      _FUNC_RESTART
      _ADDDOMINIO
      _TESTDOMINIO
      _FUNCAUTENTICACAO
      _FUNC_RESTART
      azul="{FONTE}33[0;34m"
      echo "++++++++++++++++++++++++++++++++++++++++++++"
      echo "++  {FONTE}33[0;34m Bem vindo ao dominio $dominio {FONTE}33[0m           ++"
      echo "++++++++++++++++++++++++++++++++++++++++++++"
 
                ;;  
        2)  
                _FUNC_DEL_MAQ_DOMINIO
                ;;  
        3)  
                _TESTDOMINIO
                ;;  
        0)  
                exit
                ;;  
        *)  
                echo 'Opção Inválida!'
esac

Scripts recomendados

Relatório CSV ZIMBRA

registra quais as máquinas da sala estão ligadas

Atualizando /home dos usuários em rede.(GNOME)

Pequeno, simples mas interessante chat desenvolvido totalmente em shell script.

Script recolher log's servidor


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts