Mostrando postagens com marcador Linux. Mostrar todas as postagens
Mostrando postagens com marcador Linux. Mostrar todas as postagens

quarta-feira, 29 de dezembro de 2010

Shell Script de backup para PostgreSQL

Esse script pode ser usado p/ fazer backups diários de todas as bases postgres
exemplo no crontab diariamente as 23:50
50 23 * * * /scripts/backup_pgsql.sh

#!/bin/sh
# Script to backup postgres databases 
# Create a complete bkp with all databses and a separated for each one
# Author: Mario Cezzare mcezzare@gmail.com 
# last update on Wed Dec 29 16:24:11 on ttys005   
PGDUMPALL="$(which pg_dumpall)"
PSQL="$(which psql)"
GZIP="$(which gzip)"


x=`date '+BACKUP-%d.%m.%y'`
separator="-----------------------------------"
path_backup=/backup/pgsql/
notify="sysadmin@email.com.br"
cd $path_backup
mkdir $x
path_backup="$path_backup/$x"
echo $x
now=`date '+%d.%m.%y %H:%M:%S'`
##################################################################################
# PART 1 - LOGS 
##################################################################################
echo " starting at $x $now"  >> $path_backup/pgsql-databases-$x.log


##################################################################################
# PART 2 - ALL DATAL 
##################################################################################
$PGDUMPALL -U postgres |  $GZIP -c  > $path_backup/$x-all-pg.pgsql.gz


##################################################################################
# PART 3 - EACH ONE
##################################################################################
DIR=$path_backup
[ ! $DIR ] && mkdir -p $DIR || :
LIST=$($PSQL -U postgres -l | awk '{ print $1}' | grep -vE '^-|^List|^\(|^Name|template[0|1]')
for d in $LIST
do
  echo "Dumping $d" 
  pg_dump -U postgres $d | $GZIP -c >  $DIR/$d.pgsql.gz
  now=`date '+%d.%m.%y %H:%M:%S'`
  echo "$d em $now"  >> $path_backup/pgsql-databases-$x.log
done
##################################################################################
# PART 1B - END LOGS 
##################################################################################
echo " ending at $x $now"  >> $path_backup/pgsql-databases-$x.log


##################################################################################
# PART 4 - NOTIFICATIONS 
##################################################################################


ls -aloh $path_backup | mail -s BACKUP_POSTGRES_DATABASES $notify

Shell Script de backup para Mysql

Esse script pode ser usado p/ fazer backups diários de todas as bases mysql
exemplo no crontab diariamente as 23:50
50 23 * * * /scripts/backup_mysql.sh
como root no mysql de permissao de leitura p/ o usuario backup_operator
GRANT ALL ON *.* TO 'backup_operator'@'localhost'

#!/bin/sh
# Script to backup mysql databases
# Create a complete bkp with all databses and a separated for each one
# Author: Mario Cezzare mcezzare@gmail.com 
# last update on Wed Dec 29 16:24:11 on ttys005

x=`date '+BACKUP-%d.%m.%y'`
now=`date '+%d.%m.%y %H:%M:%S'`
separator="-----------------------------------"
path_backup=/backup/mysql/
notify="sysadmin@email.com.br"
cd $path_backup
mkdir $x
path_backup="$path_backup/$x"
echo $x
##################################################################################
# PART 1 - LOGS
##################################################################################

echo " starting at $x $now"  >> $path_backup/mysql_databases-$x.log
echo $separator

MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
MYSQLUSER="backup_operator"
MYSQLPASSWD="senha_do_backup_operator"
MYSQLHOST="localhost"
GZIP="$(which gzip)"
##################################################################################
# PART 2 - ALL DATA
##################################################################################

echo "backup of mysql  databases "
mysqldump --all-databases -h $MYSQLHOST -u $MYSQLUSER -p$MYSQLPASSWD | gzip -c > $path_backup/backup-all-mysql-$x.mysql.gz

##################################################################################
# PART 3 - EACH ONE
##################################################################################

DBS="$($MYSQL -u $MYSQLUSER -h $MYSQLHOST -p$MYSQLPASSWD -Bse 'show databases')"
for db in $DBS ; do
 echo "backing up $db"
 FILE="mysql_$db-$x.mysql.gz"
 $MYSQLDUMP -u $MYSQLUSER -h $MYSQLHOST -p$MYSQLPASSWD $db | $GZIP -c  > $path_backup/$FILE
 now=`date '+%d.%m.%y %H:%M:%S'`
 echo " $db at $x $now"  >> $path_backup/mysql_databases-$x.log
done

##################################################################################
# PART 3 - EACH ONE
##################################################################################

now=`date '+%d.%m.%y %H:%M:%S'` 
echo " ending at $x $now"  >> $path_backup/mysql_databases-$x.log

##################################################################################
# PART 4 - NOTIFICATIONS
##################################################################################

ls -aloh $path_backup | mail -s BACKUP_MYSQL_DATABASES $notify

sexta-feira, 9 de julho de 2010

Troca de senha de múltiplos Usuários com SAMBA e shell script e teste com SMBCLIENT

Como no exemplo anterior a lista de usuarios saem de uma  tabela Mysql , onde tenho os logins e senhas. A partir dela gero um arquivo csv (userstrocasenha.txt) e um script em shell p/ fazer a tarefa (troca_senha.sh) como descrito abaixo : 

Exemplo feito em 

Linux pdc-sp 2.6.18-6-686 #1 SMP Sun Feb 10 22:11:31 UTC 2008 i686 GNU/Linux

Samba : 
pdc-sp:~/scripts# smbd -V
Version 3.0.24
 

OBS 1: Para aumentar a segurança do sistema os existem usuários locais do linux p/ os Homedirs que nao não podem logar na máquina e em qq outro serviço exceto o Samba que funciona como PDC. 


O arquivo de senhas do SAMBA fica em /etc/samba/smbpasswd.db
 
O texto q estiver dessa maneira é o q foi digitado : 
Exemplo para a  Autenticação no SAMBA
pdc-sp:~/scripts# cat troca_senha.sh
#!/bin/sh
# modelo do arquivo user;senha
FILEIMPORT="userstrocasenha.txt"
for x in `cat $FILEIMPORT`;
do

usuario=$(echo $x | cut -d ";" -f 1)
senha=$(echo $x | cut -d ";" -f 2)
#usuario=$1
#senha=$2
#echo $usuario
echo "trocando a senha do usuario:$usuario"
#echo $senha
#(echo $senha;  echo $senha) |  smbpasswd -e $usuario -s
echo -e "$senha\n$senha" | (smbpasswd -a -s $usuario)
done

Antes de rodar o script , se quiser criar usuarios p/ testar o script , utilizo o seguinte script p/ criar usuários:

pdc-sp:~/scripts# cat adu.sh
#!/bin/sh
#script p/ adicionar usuyarios ao samba e ao linux
# Author Mario Cezzare mcezzare@gmail.com
if [ -n "$1" ]
then
usuario="$1"
#senha=$2
#echo $usuario
#echo $senha

#STEP 1
#create user at linux system with no login
/usr/sbin/useradd -m  -s /bin/false -c ntuser -G ntusers $usuario

#STEP 2
#locka a senha
passwd -l $usuario


#STEP 3
#add smb user
smbpasswd -a $usuario

#STEP 4
echo -e "$senha\n$senha" | (smbpasswd -e -s $usuario)
else
echo "Informe o Usuario"
fi


p/ ter certeza de que não existirá esse usuario 
pdc-sp:~/scripts# smbpasswd -x usertest1
Deleted user usertest1.
pdc-sp:~/scripts# userdel -r usertest1
 
Vamos criar o usuário usertest1
pdc-sp:~/scripts# sh adu.sh usertest1
Senha modificada.
New SMB password:x
Retype new SMB password:
x
Added user usertest1.
Enabled user usertest1.

Vamos testar o acesso com a senha errada 
pdc-sp:~/scripts# smbclient  -L \\localhost -U usertest1
Password: qqqq
session setup failed: NT_STATUS_LOGON_FAILURE

Vamos testar o acesso com a senha correta




pdc-sp:~/scripts# smbclient  -L \\localhost -U usertest1
Password: x
Domain=[PDCSERVER-SP] OS=[Unix] Server=[Samba 3.0.24]

    Sharename       Type      Comment
    ---------       ----      -------
    IPC$            IPC       IPC Service (pdc-sp server)
    usertest1       Disk      Home Directories
Domain=[PDCSERVER-SP] OS=[Unix] Server=[Samba 3.0.24]

    Server               Comment
    ---------            -------
    PDCSERVER-PDC-SP       pdc-sp server

    Workgroup            Master
    ---------            -------
    PDCSERVER-SP           PDCSERVER-D8DBD85


vamos trocar a senha desse usuário : 

pdc-sp:~/scripts# sh troca_senha.sh
trocando a senha do usuario:usertest1



vamos testar com senha antiga (x)

pdc-sp:~/scripts# smbclient  -L \\localhost -U usertest1
Password:x
session setup failed: NT_STATUS_LOGON_FAILURE
pdc-sp:~/scripts# 




Vamos testar o acesso com a senha alterada pelo script (xxx)

pdc-sp:~/scripts# smbclient  -L \\localhost -U usertest1
Password: xxx
Domain=[PDCSERVER-SP] OS=[Unix] Server=[Samba 3.0.24]

    Sharename       Type      Comment
    ---------       ----      -------
    IPC$            IPC       IPC Service (pdc-sp server)
    usertest1       Disk      Home Directories
Domain=[PDCSERVER-SP] OS=[Unix] Server=[Samba 3.0.24]

    Server               Comment
    ---------            -------
    PDCSERVER-PDC-SP       pdc-sp server

    Workgroup            Master
    ---------            -------
    PDCSERVER-SP           PDCSERVER-D8DBD85

vamos remover esses usuario de teste 

pdc-sp:~/scripts# smbpasswd -x usertest1
Deleted user usertest1.
pdc-sp:~/scripts# userdel -r usertest1


Essa é uma maneira rápida e simples de trocar as senhas quando o método de Autenticação é o próprio SAMBA , e os logins e senhas ficam nos arquivos /etc/samba/smbpasswd.db , que são gerenciados pelo programa smbpasswd. 


Depois desses scripts o proximo post pode ser a instação de um LDAP neh , rs .. 
[]'s

Troca de senha de múltiplos Usuários com SQUID e shell script e teste com WGET


Como no exemplo anterior a lista de usuarios saem de uma  tabela Mysql , onde tenho os logins e senhas. A partir dela gero um arquivo csv (userstrocasenha.txt) e um script em shell p/ fazer a tarefa (troca_senha.sh) como descrito abaixo : 

Exemplo feito em 
surfer@proxy:~$uname -a 
OpenBSD proxy.portari.com.br 4.6 GENERIC.MP#89 i386 

surfer@proxy:~$squid -v
Squid Cache: Version 2.7.STABLE6
configure options:  '--datadir=/usr/local/share/squid' '--enable-auth=basic digest' '--enable-arp-acl' '--enable-basic-auth-helpers=NCSA YP' '--enable-digest-auth-helpers=password' '--enable-delay-pools' '--enable-external-acl-helpers=ip_user unix_group' '--enable-forw-via-db' '--enable-negotiate-auth-helpers=squid_kerb_auth' '--enable-pf-transparent' '--enable-removal-policies=lru heap' '--enable-ssl' '--enable-storeio=aufs ufs diskd null' '--with-pthreads' '--localstatedir=/var/squid' '--enable-follow-x-forwarded-for' '--enable-snmp' '--prefix=/usr/local' '--sysconfdir=/etc' '--mandir=/usr/local/man' '--infodir=/usr/local/info' 'CC=cc' 'CFLAGS=-O2 -pipe' )

O arquivo de senhas do squid fica em /etc/squid/squid-passwd
 
O texto q estiver dessa maneira é o q foi digitado : 
Exemplo para a  Autenticação no SQUID 

surfer@proxy:~$cat userstrocasenha.txt                                     
usertest1;xxx
usertest2;yyy




 surfer@proxy:~$cat troca_senha.sh                                          
#!/bin/sh
# Author : Mario Cezzare - mcezzare@gmail.com# modelo do arquivo user;senha
FILEIMPORT="userstrocasenha.txt"
for x in `cat $FILEIMPORT`;
do

usuario=$(echo $x | cut -d ";" -f 1)
senha=$(echo $x | cut -d ";" -f 2)
#usuario=$1
#senha=$2
#echo $usuario
echo "trocando a senha do usuario:$usuario"
#echo $senha
( /usr/bin/htpasswd -b /etc/squid/squid-passwd $usuario $senha)
done 


Antes de rodar o script , se quiser criar usuarios p/ testar o script:                                                        
surfer@proxy:~$sudo htpasswd /etc/squid/squid-passwd usertest1                                          
New password:x
Re-type new password:
x
Adding password for user usertest1
surfer@proxy:~$sudo htpasswd /etc/squid/squid-passwd usertest2
New password:y
Re-type new password:
y
Adding password for user usertest2

conferindo

surfer@proxy:~$sudo cat /etc/squid/squid-passwd | grep usertest 
usertest1:$2a$06$x1OeGXv5KjBqHTRXyP/WrOrcLVmx9.cjREt812COWJ36hwgaLIll.
usertest2:$2a$06$5Wxexk5S/YUhDaWxNm6f/uY3pRTiKlbAyy0B5v2gaZRUBT3zA5E3.

reiniciando o squid p/ reconhecimento dos usuários :
surfer@proxy:~$sudo squid -k reconfigure

p/ testar e poder mostrar no post o acesso, log e erros, utilizarei o apt de uma maquina debian/linux na mesma rede deste proxy, p/ não instalar ferramentas de download no Proxy por motivos de segurança.
veja a configuração do arquivo /etc/apt.conf da maquina cliente : 

hostmachine:~# cat /etc/apt/apt.conf
Acquire::http::Proxy "http://usertest1:x@proxy:3128";
hostmachine:~# apt-get update
Get:1 http://ftp.br.debian.org lenny Release.gpg [1033B]
Ign http://ftp.br.debian.org lenny/main Translation-en_US                               
Ign http://ftp.br.debian.org lenny/non-free Translation-en_US                           
Ign http://ftp.br.debian.org lenny/contrib Translation-en_US                            
Hit http://ftp.br.debian.org lenny Release                                              
Ign http://ftp.br.debian.org lenny/main Packages/DiffIndex                              
Ign http://ftp.br.debian.org lenny/non-free Packages/DiffIndex
Ign http://ftp.br.debian.org lenny/contrib Packages/DiffIndex                           
Ign http://ftp.br.debian.org lenny/main Sources/DiffIndex                               
Ign http://ftp.br.debian.org lenny/non-free Sources/DiffIndex                           
Ign http://ftp.br.debian.org lenny/contrib Sources/DiffIndex  
         
etc...

e nos logs do Squid 

surfer@proxy:~$sudo tail -f /var/squid/logs/access.log
1278698863.984     30 200.xxx.xxx.xxx TCP_REFRESH_HIT/304 245 GET http://ftp.br.debian.org/debian/dists/lenny/Release.gpg usertest1 DIRECT/200.17.202.1 -
1278698863.984     30 200.xxx.xxx.xxx TCP_REFRESH_HIT/304 245 GET http://ftp.br.debian.org/debian/dists/lenny/Release.gpg usertest1 DIRECT/200.17.202.1 -
1278698863.985      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 626 GET http://ftp.br.debian.org/debian/dists/lenny/main/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698863.985      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 626 GET http://ftp.br.debian.org/debian/dists/lenny/main/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698863.986      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 630 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698863.986      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 630 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698863.987      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 629 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698863.987      0 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 629 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/i18n/Translation-en_US.bz2 usertest1 NONE/- text/html
1278698864.002     15 200.xxx.xxx.xxx TCP_MISS/304 247 GET http://ftp.br.debian.org/debian/dists/lenny/Release usertest1 DIRECT/200.17.202.1 -
1278698864.002     15 200.xxx.xxx.xxx TCP_MISS/304 247 GET http://ftp.br.debian.org/debian/dists/lenny/Release usertest1 DIRECT/200.17.202.1 -
1278698864.016      1 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 631 GET http://ftp.br.debian.org/debian/dists/lenny/main/binary-i386/Packages.diff/Index usertest1 NONE/- text/html
1278698864.016      1 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 631 GET http://ftp.br.debian.org/debian/dists/lenny/main/binary-i386/Packages.diff/Index usertest1 NONE/- text/html
1278698864.018      1 200.xxx.xxx.xxx TCP_NEGATIVE_HIT/404 635 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/binary-i386/Packages.diff/Index usertest1 NONE/- text/html

 
e rode o script p/ trocar a senha 
surfer@proxy:~$sudo sh troca_senha.sh
trocando a senha do usuario:usertest1
Updating password for user usertest1
trocando a senha do usuario:usertest2
Updating password for user usertest2


no cliente com a nova senha


hostmachine:/home/surfer# cat /etc/apt/apt.conf
Acquire::http::Proxy "http://usertest1:xxx@proxy:3128";
hostmachine:/home/surfer# apt-get update
Hit http://ftp.br.debian.org lenny Release.gpg
Ign http://ftp.br.debian.org lenny/main Translation-en_US
Ign http://ftp.br.debian.org lenny/non-free Translation-en_US                           
Ign http://ftp.br.debian.org lenny/contrib Translation-en_US                            
Hit http://ftp.br.debian.org lenny Release                                              
Ign http://ftp.br.debian.org lenny/main Packages/DiffIndex                              
Ign http://ftp.br.debian.org lenny/non-free Packages/DiffIndex
Ign http://ftp.br.debian.org lenny/contrib Packages/DiffIndex                           
Ign http://ftp.br.debian.org lenny/main Sources/DiffIndex                               
Ign http://ftp.br.debian.org lenny/non-free Sources/DiffIndex                           
Ign http://ftp.br.debian.org lenny/contrib Sources/DiffIndex                            
Hit http://ftp.br.debian.org lenny/main Packages                                        
Hit http://ftp.br.debian.org lenny/non-free Packages                                    
Hit http://ftp.br.debian.org lenny/contrib Packages                                     
Hit http://ftp.br.debian.org lenny/main Sources                                         
Hit http://ftp.br.debian.org lenny/non-free Sources
Hit http://ftp.br.debian.org lenny/contrib Sources
etc...

e no servidoor proxy : 

surfer@proxy:~$sudo tail -f /var/squid/logs/access.log
1278711296.118    360 200.xxx.xxx.xxx TCP_REFRESH_HIT/304 245 GET http://ftp.br.debian.org/debian/dists/lenny/Release.gpg usertest1 DIRECT/200.17.202.1 -
1278711296.118    360 200.xxx.xxx.xxx TCP_REFRESH_HIT/304 245 GET http://ftp.br.debian.org/debian/dists/lenny/Release.gpg usertest1 DIRECT/200.17.202.1 -
1278711296.152     32 200.xxx.xxx.xxx TCP_MISS/404 617 GET http://ftp.br.debian.org/debian/dists/lenny/main/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.152     32 200.xxx.xxx.xxx TCP_MISS/404 617 GET http://ftp.br.debian.org/debian/dists/lenny/main/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.174     20 200.xxx.xxx.xxx TCP_MISS/404 621 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.174     20 200.xxx.xxx.xxx TCP_MISS/404 621 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.191     16 200.xxx.xxx.xxx TCP_MISS/404 620 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.191     16 200.xxx.xxx.xxx TCP_MISS/404 620 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/i18n/Translation-en_US.bz2 usertest1 DIRECT/200.17.202.1 text/html
1278711296.209     17 200.xxx.xxx.xxx TCP_MISS/304 247 GET http://ftp.br.debian.org/debian/dists/lenny/Release usertest1 DIRECT/200.17.202.1 -
1278711296.209     17 200.xxx.xxx.xxx TCP_MISS/304 247 GET http://ftp.br.debian.org/debian/dists/lenny/Release usertest1 DIRECT/200.17.202.1 -
1278711296.238     16 200.xxx.xxx.xxx TCP_MISS/404 622 GET http://ftp.br.debian.org/debian/dists/lenny/main/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.238     16 200.xxx.xxx.xxx TCP_MISS/404 622 GET http://ftp.br.debian.org/debian/dists/lenny/main/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.255     16 200.xxx.xxx.xxx TCP_MISS/404 626 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.255     16 200.xxx.xxx.xxx TCP_MISS/404 626 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.272     16 200.xxx.xxx.xxx TCP_MISS/404 625 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.272     16 200.xxx.xxx.xxx TCP_MISS/404 625 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/binary-i386/Packages.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.289     16 200.xxx.xxx.xxx TCP_MISS/404 616 GET http://ftp.br.debian.org/debian/dists/lenny/main/source/Sources.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.289     16 200.xxx.xxx.xxx TCP_MISS/404 616 GET http://ftp.br.debian.org/debian/dists/lenny/main/source/Sources.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.309     18 200.xxx.xxx.xxx TCP_MISS/404 620 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/source/Sources.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.309     18 200.xxx.xxx.xxx TCP_MISS/404 620 GET http://ftp.br.debian.org/debian/dists/lenny/non-free/source/Sources.diff/Index usertest1 DIRECT/200.17.202.1 text/html
1278711296.335     25 200.xxx.xxx.xxx TCP_MISS/404 619 GET http://ftp.br.debian.org/debian/dists/lenny/contrib/source

etc.. 

Essa é uma maneira rápida e simples de trocar as senhas quando o método de Autenticação é o NCSA , e os logins e senhas ficam nos arquivos /etc/squid/ARQUIVO , que são gerenciados pelo programa htpasswd (do apache)
(no squid.conf : 
auth_param basic program /usr/local/libexec/ncsa_auth /etc/squid/squid-passwd  )


Samba fica p/ o próximo post
[]'s

Troca de senha de múltiplos Usuários com PAM e shell script e teste com POP 3

Pense nessa situação:

Você tem vários usuarios e vários serviços diferentes em maquinas diferentes.

Serviços de Email, Proxy, Samba mas ainda nao usa uma base centralizada como LDAP.

Bem, segue uma dica com scripts p/ automatização dessa tarefa (já pensou trocar a senha manualmente de 400 usuários ?:( , ninguém merece neh ?)

Neste caso tenho uma tabela Mysql , onde tenho os logins e senhas. A partir dela gero um arquivo csv (userstrocasenha.txt) e um script em shell p/ fazer a tarefa (troca_senha.sh) como descrito abaixo : 

o texto q estiver dessa maneira é o q foi digitado : 




hostmachine:~/scripts# cat userstrocasenha.txt
usertest1;xxx
usertest2;yyy


 
Exemplo de Autenticação com PAM

hostmachine:~/scripts# cat troca_senha.sh
#!/bin/sh
# script p/ troca de senha
# Author : Mario Cezzare - mcezzare@gmail.com
# modelo do arquivo user;senha
FILEIMPORT="userstrocasenha.txt"
for x in `cat $FILEIMPORT`;
do

usuario=$(echo $x | cut -d ";" -f 1)
senha=$(echo $x | cut -d ";" -f 2)
#usuario=$1
#senha=$2
#echo $usuario
echo "trocando a senha do usuario:$usuario"
#echo $senha
#( /usr/bin/passwd $usuario $senha)
echo -e "$senha\n$senha" | (passwd $usuario)

done 

 
Antes de rodar o script , se quiser criar usuarios p/ testar o script :
(exemplo num Debian Linux hostmachine 2.6.26-2-686 #1 SMP Wed Nov 4 20:45:37 UTC 2009 i686 GNU/Linux )

hostmachine:~/scripts# adduser usertest1
Adding user `usertest1' ...
Adding new group `usertest1' (1007) ...
Adding new user `usertest1' (1007) with group `usertest1' ...
Creating home directory `/home/usertest1' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:x
Retype new UNIX password:x
passwd: password updated successfully
Changing the user information for usertest1
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] Y
hostmachine:~/scripts# adduser usertest2
Adding user `usertest2' ...
Adding new group `usertest2' (1013) ...
Adding new user `usertest2' (1013) with group `usertest2' ...
Creating home directory `/home/usertest2' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:y
Retype new UNIX password:
y
passwd: password updated successfully
Changing the user information for usertest2
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] Y
hostmachine:~/scripts#

Vamos testar o acesso via pop3 p/ mostrar :


hostmachine:~/scripts# telnet localhost 110
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user usertest1
+OK Password required.
pass x
+OK logged in.
list
+OK POP3 clients that break here, they violate STD53.
.
quit
+OK Bye-bye.
Connection closed by foreign host.
hostmachine:~/scripts#


ok vamos rodar o script troca_senha.sh e ver se funciona :

hostmachine:~/scripts# sh troca_senha.sh
trocando a senha do usuario:usertest1
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully
trocando a senha do usuario:usertest2
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully


Agora vamos testar com a nova senha :

hostmachine:~/scripts# telnet localhost 110
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
user usertest1
+OK Password required.
pass xxx
+OK logged in.
list
+OK POP3 clients that break here, they violate STD53.
.
quit
+OK Bye-bye.
Connection closed by foreign host.

OBS: Não se esqueça de remover esses 2 usuários após os testes:

hostmachine:~/scripts# userdel -r usertest1
hostmachine:~/scripts# userdel -r usertest2


Essa é uma maneira rápida e simples de trocar as senhas quando o método de Autenticação é o PAM , e os logins e senhas ficam nos arquivos /etc/passwd e /etc/shadow , usando o programa /usr/bin/passwd (no caso dessa versão do Debian e na maioria do sistemas UNIX-LIKE)


Samba e Squid ficam p/ o próximo post
[]'s