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

quinta-feira, 2 de agosto de 2012

ORACLE SQL PLUS WEB





Se vc já precisou acessar um banco de dados ORACLE com php, este exemplo será bem Util.
Como eu não tinha acesso a rede interna por estar fora da empresa e precisava testar as consultas fiz uma página onde eu pudesse colocar o SQL e retornar os resultados durante o desenvolvimento do site.
É mais fácil visualizar dados de consultas em Grades, certo ?

Porém p/ não comprometer a segurança desses dados procurei fazer essa ferramenta permitindo apenas comandos de SELECT * . 

veja os screenshots :
Consulta efetuada com sucesso

Consulta efetuada com erro



Consulta com palavra negada

Codigo da Página SQLQueryTool.php
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/lib/Conexao.php');
$resultMode = false;
if (isset($_POST['Query'])) {
    $resultMode = true;
    $sql = $_POST['Query'];
    preg_match('/^SELECT./i', $sql, $achei); //instrução tem q começar com SELECT
    if (!$achei) {
        die('1: ONLY SELECTS');
    }
    //bloqueia as palvras
    $pattern = array("DELETE", "UPDATE", "INSERT", "DROP",
        "ALTER", "ANALYZE", "AUDIT", "CONNECT", "CREATE",
        "GRANT", "LOCK", "NOAUDIT", "RENAME", "REVOKE", "SET CONSTRAINTS",
        "SET ROLE", "SET TRANSACTION", "TRUNCATE", "EXIT", "BEGIN",
        "EXEC", "UNION", "\"", "--", "INTERSECT", "MINUS", "TABLE", "VIEW");
    preg_match(sprintf('/%s/i', implode('|', $pattern)), $sql, $achei2);
    if ($achei2) {

        $msgErro = '2: ONLY SELECTS.<br>' .
//            preg_last_error() .
                "Palavra Negada: <b>" . $achei2[0] . "</b>";
    } else {
        $conexao = new Conexao();
        $conexao->conecta();
        $rs = $conexao->executeQuery($sql);
        // p/ pegar o nome das colunas
        $conn = oci_connect($conexao->getUser(), $conexao->getPass(), $conexao->getHost() . "/" . $conexao->getDbname(), $conexao->getEncoding());
        $columns = ociparse($conn, $sql);
        ociexecute($columns);
//    var_dump($columns);
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <title>MCezzare Oracle SQL QUERY TOOL WEB®</title>
        <link href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css" rel="stylesheet" type="text/css"></link>
        <link href="http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css" rel="stylesheet" type="text/css"></link>
        <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js" type="text/javascript">
        </script>
        <script src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js" type="text/javascript">
        </script>
        <script language="javascript">
            SyntaxHighlighter.config.bloggerMode = true;
            SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
            SyntaxHighlighter.all();
        </script>
        <style type="text/css">
            body {
                font-family: Verdana, Geneva, sans-serif;
                font-size: 12px;
            }
            th {
                color: #FFF;
                background-color: #003366;
                font-weight: bold;
                font-size: 12px;
            }
            tr {
                color: #000;
                font-size: 10px;
            }
        </style>
    </head>

    <body>
        <div id="form">
            <form id="form1" name="form1" method="post" action="<? echo $_SERVER['PHP_SELF']; ?>">
                <legend> SQL:  </legend>
                <textarea name="Query" id="Query" cols="45" rows="5" class="brush: sql"></textarea>

                <input type="submit" name="submit" id="submit" value="@GO" />
            </form>
        </div>
        <div id="results">
            <? if (($resultMode) && (!$achei2)) { ?>
                <b>SQL:</b><br> 
                    <pre class="brush: sql" style="font-size: 8px;"><? echo $sql; ?>
                    </pre>
                    <table border="1" cellpadding="1" cellspacing="1">

                        <? // var_dump($rs); ?>
                        <?
                        if (count($rs) > 0) {
                            $controle = 0;

                            foreach ($rs as $row) {

                                if ($controle == 0) { // apenas da 1ª vez p/ gerar o header da tabela
                                    echo "<thead>\n";
                                    echo "<tr>\n";
                                    $ncols = oci_num_fields($columns);
                                    for ($i = 1; $i <= $ncols; $i++) {
                                        echo "<th>" . oci_field_name($columns, $i) . "</th>\n";
                                    }
                                    echo "</tr>\n";
                                    echo "</thead>\n";
                                }
                                echo "<tbody>\n";
                                echo "<tr>\n";
//                    print_r($row);
                                foreach ($row as $linha) {
                                    echo "<td>" . ($linha !== null ? htmlentities($linha, ENT_QUOTES) : "&nbsp;") . "</td>\n";
                                }
                                echo "</tr>\n";
                                $controle++;
                            }
                        }
                        echo "</tbody>\n";
                        echo "</table>";
                    } else {
                        echo $msgErro;
                        ?>
                    <? } ?>

                    </div>
                    </body>
                    </html>

Codigo da lib de Conexão ao Banco
<?

error_reporting('E_ALL');
/*
  @arquivo = /lib/Conexao.php
  MVC :  controller
  objeto : Conexao
  obs : arquivo em uso na versão corrente banco ORACLE
 */

Class Conexao {

    // db data
    private $host;
    private $user;
    private $pass;
    private $dbname;
    private $encoding;
    //controle
    private $status; // 0 / 1
    private $db;  // oci_pconnect 
    private $execMode;
    private $entrada;
    private $saida = array();

    public function getHost() {
        return $this->host;
    }

    public function setHost($host) {
        $this->host = $host;
    }

    public function getUser() {
        return $this->user;
    }

    public function setUser($user) {
        $this->user = $user;
    }

    public function getPass() {
        return $this->pass;
    }

    public function setPass($pass) {
        $this->pass = $pass;
    }

    public function getDbname() {
        return $this->dbname;
    }

    public function setDbname($dbname) {
        $this->dbname = $dbname;
    }

    public function getEncoding() {
        return $this->encoding;
    }

    public function setEncoding($encoding) {
        $this->encoding = $encoding;
    }

    public function getDb() {
        return $this->db;
    }

    public function setDb($db) {
        $this->db = $db;
    }

    public function getStatus() {
        return $this->status;
    }

    public function setStatus($status) {
        $this->status = $status;
    }

    public function getEntrada() {
        return $this->entrada;
    }

    public function setEntrada($entrada) {
        $this->entrada = $entrada;
    }

    public function getSaida() {
        return $this->saida;
    }

    public function setSaida($saida) {
        $this->saida = $saida;
    }

    public function getExecMode() {
        return $this->execMode;
    }

    public function setExecMode($execMode) {
        $this->execMode = $execMode;
    }

    function Conexao() {
        $this->setStatus(0);
        $this->setHost("ENDERECO_IP");
        $this->setUser("USUARIO");
        $this->setPass("SENHA");
        $this->setDbname("NOME_BANCO");
        $this->setEncoding("WE8ISO8859P15");
//        $this->conecta(); // pode ser automatico
    }

    public function conecta() {

        $this->setDb(oci_pconnect($this->getUser(), $this->getPass(), $this->getHost() . "/" . $this->getDbname(), $this->getEncoding()));
        if (!$this->getDb()) {
            $err = oci_error();
            echo $this->mostraErro($err);
            return false;
        } else {
            $this->setStatus(1);
//            echo "Conectado no banco.<br>";
            return true;
        }
    }

    public function executeQuery($sql, $mode = OCI_FETCHSTATEMENT_BY_ROW,$safe=false) {

        if ($this->getStatus() == 1) {
            $this->entrada = ociparse($this->getDb(), $sql);

            if ($safe){
            $r = ociexecute($this->getEntrada()); //OCI_AUTO_COMMIT defaults
            }
            else {
            $r = ociexecute($this->getEntrada(),OCI_NO_AUTO_COMMIT); //OCI_NO_AUTO_COMMIT    
            }
            if (!$r) {
                $err = oci_error($this->entrada);
                echo $this->mostraErro($err);
                $this->desconecta();
            } else {
                if ($nrows = oci_fetch_all($this->getEntrada(), $this->saida, null, null, $mode)) {
                    return $this->getSaida();
                }
            }
        } else {
            echo $this->mostraErro(null, "Não estou conectado.");
        }
    }

    public function executeUpdate($sql) {

        if ($this->getStatus() == 1) {
            $this->entrada = ociparse($this->getDb(), $sql);
            $r = ociexecute($this->getEntrada());
            if (!$r) {
                $err = oci_error($this->entrada);
                echo $this->mostraErro($err);
                $this->desconecta();
            } else {
                return $r;
            }
        } else {
            echo $this->mostraErro(null, "Não estou conectado.");
        }
    }

    function desconecta() {
        $this->setStatus(0);
        if ($this->entrada) {
            oci_free_statement($this->entrada);
        }
        if ($this->db) {
            @oci_close($this->db);
        }
//        return 
    }

    function mostraErro($err, $msg = "") {
//        var_dump($err);
        $logMsg = $msg;
        if (is_array($err)) {
            foreach ($err as $key => $val) {
                $logMsg.="$key :  " . $val . "<br>\n";
            }
        }
        $retorno = "";
        $retorno.="<h1 style=\"color:#F00; font-size:19px; margin:5px 0 20px; text-shadow:1px 1px 2px #602526;\">Erro</h1>";
        $retorno.="<pre style=\"border:solid 1px #EA9C5C; padding:3px; color:#000000; background-color:#ededed \">$logMsg</pre>";
        return $retorno;
        die(); // opcional p/ travar a pagina
    }

    public function __destruct() {
        $this->desconecta();
    }

}
?>
e boas consultas.

OBS: não esqueça de restringir o acesso a essa página por autenticação ou um arquivo .htaccess
exemplo de um arquivo .htaccess que bloqueia o acesso  esse arquivo


<Files SQLQueryTool.php>
AuthType Basic
AuthName "Restricted Area" 
AuthBasicProvider file
AuthUserFile /var/www/html/delagelanden3.portari.com.br/pages/.htpasswd
Require  valid-user
</Files>

e crie o arquivo (logado no servidor) com o comando (comandos em negrito)
usuario@host:~#
htpasswd -c .htpasswd usuario

New password:
Re-type new password:x 
Adding password for user usuario

explicação:
htpasswd = programa
-c = p/ criar o arquivo .htpasswd
usuario = o login q vc quiser

veja conteudo do arquivo gerado:
usuario@host:~#cat .htpasswd 
usuario:DQK07/M2P2hkY


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