11.04.2013 Views

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

Guida avanzata di scripting Bash - Portale Posta DMI

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Esempio A-14. password: generare password casuali <strong>di</strong> 8 caratteri<br />

Appen<strong>di</strong>ce A. Script aggiuntivi<br />

#!/bin/bash<br />

# Su macchine un po’ vecchie,<br />

#+ potrebbe essere necessario cambiare l’intestazione in #!/bin/bash2.<br />

#<br />

# Generatore <strong>di</strong> password casuali per <strong>Bash</strong> 2.x<br />

#+ <strong>di</strong> Antek Sawicki ,<br />

# che ha generosamente permesso all’autore del documento il suo utilizzo.<br />

#<br />

# ==> Commenti aggiunti dall’autore del libro ==><br />

MATRICE="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"<br />

# ==> La password viene formata con caratteri alfanumerici.<br />

LUNGHEZZA="8"<br />

# ==> Se desiderate passaword più lunghe mo<strong>di</strong>ficate ’LUNGHEZZA’.<br />

while [ "${n:=1}" -le "$LUNGHEZZA" ]<br />

# ==> Ricordo che := è l’operatore "sostiruzione default".<br />

# ==> Quin<strong>di</strong>, se ’n’ non è stata inizializzata, viene impostata ad 1.<br />

do<br />

PASS="$PASS${MATRICE:$(($RANDOM%${#MATRICE})):1}"<br />

# ==> Molto intelligente e scaltro.<br />

# ==> Iniziando dall’annidamento più interno...<br />

# ==> ${#MATRICE} restituisce la lunghezza dell’array MATRICE.<br />

# ==> $RANDOM%${#MATRICE} restituisce un numero casuale compreso tra 1<br />

# ==> e [lunghezza <strong>di</strong> MATRICE] - 1.<br />

# ==> ${MATRICE:$(($RANDOM%${#MATRICE})):1}<br />

# ==> restituisce l’espansione <strong>di</strong> lunghezza 1 <strong>di</strong> MATRICE<br />

# ==> partendo da una posizione casuale.<br />

# ==> Ve<strong>di</strong> la sostituzione <strong>di</strong> parametro {var:pos:lun},<br />

# ==> con relativi esempi, al Capitolo 9.<br />

# ==> PASS=... aggiunge semplicemente il risultato al precedente<br />

# ==> valore <strong>di</strong> PASS (concatenamento).<br />

# ==> Per visualizzare tutto questo più chiaramente,<br />

# ==> decommentate la riga seguente<br />

# echo "$PASS"<br />

# ==> e vedrete come viene costruita PASS,<br />

# ==> un carattere alla volta ad ogni iterazione del ciclo.<br />

let n+=1<br />

# ==> Incrementa ’n’ per il passaggio successivo.<br />

done<br />

echo "$PASS" # ==> Oppure, se preferite, re<strong>di</strong>rigetela in un file.<br />

635

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!