Farid Hajji: Perl - Einführung, Anwendungen, Referenz
2., aktualisierte und erweiterte Auflage
Addison-Wesley Longman, ISBN 3-8273-1535-2
db-tiedbi.pl
#!/usr/local/bin/perl -w
# db-tiedbi.pl -- Persistente Hashes mit Datenbank-Backend: Tie::DBI
use Tie::DBI;
use constant DATABASE => 'test';
use constant TABLE => 'unixpwd';
use constant AUSER => ''; # Irgend ein User.
use constant APASS => ''; # Irgend ein Passwort.
# Die Tabelle, an die wir uns anschliessen, muss schon existieren:
create_table_if_not_exists(DATABASE, TABLE);
# Wir schliessen uns an die Datenbanktabelle an:
tie %uxpw, 'Tie::DBI', { db => "dbi:mysql:database=" . DATABASE,
table => TABLE,
key => 'login',
user => AUSER, password => APASS,
CLOBBER => 2 }
or die "Error: Can't tie to database: $!\n";
# Wir lesen alle Eintraege ein und fuehren eventuell auch Updates
# alter Eintraege durch.
$ix = 0; %FN = map { $ix++ => $_ } qw(login pw uid gid gcos home shell);
open(PASSWD, "< /etc/passwd") or die "can't open file: $!\n";
while (<PASSWD>) {
chomp; my @f = split(/:/);
foreach my $f (@f) { undef $f if defined $f and $f eq '' };
delete $uxpw{$f[0]} if exists $uxpw{$f[0]};
$uxpw{$f[0]} = { map { $FN{$_} => $f[$_] } 2 .. 6 };
$found{$f[0]} = 1; # Fuer das spaetere loeschen.
}
close(PASSWD);
# Wir loeschen alle Eintraege, die nicht mehr vorhanden sind:
while (($key, undef) = each(%uxpw)) {
delete $uxpw{$key} unless exists $found{$key};
}
# MySQL kennt keine Transaktionen, sonst haetten wir sagen koennen:
# tied(%uxpw)->commit(); # Wenn alles okay ist.
# tied(%uxpw)->rollback(); # Nein, wir wollen es doch nicht.
# Einige Abfragen:
@adminkeys = tied(%uxpw)->select_where('gcos rlike "[Aa]dmin"');
@homeless = tied(%uxpw)->select_where('home is null');
@shellless = tied(%uxpw)->select_where('shell is null');
@nameless = tied(%uxpw)->select_where('gcos is null');
@roots = tied(%uxpw)->select_where('uid = 0');
print "Admins : ", join(',', @adminkeys), "\n";
print "Homeless : ", join(',', @homeless), "\n";
print "Shellless: ", join(',', @shellless), "\n";
print "Nameless : ", join(',', @nameless), "\n";
print "Superuser: ", join(',', @roots), "\n";
use DBI;
sub create_table_if_not_exists {
my ($dbase, $table) = @_;
my $dbh = DBI->connect("DBI:mysql:database=$dbase");
die "Error: $DBI::errstr\n" if $DBI::err;
# Statt grep() und func('_ListTables') kann ab MySQL 3.23.x
# auch CREAT TABLE IF NOT EXISTS $table ... benutzt werden
if (not grep(/^$table$/, $dbh->func('_ListTables'))) {
$dbh->do(qq{ CREATE TABLE $table
( login CHAR(8) NOT NULL PRIMARY KEY,
uid SMALLINT NOT NULL,
gid SMALLINT NOT NULL,
gcos CHAR(32),
home CHAR(20),
shell CHAR(25) )
});
die "Error: $DBI::errstr\n" if $DBI::err;
}
$dbh->disconnect();
}
[Prev] [Up] [Relevant Chapter] [Next]
[Alte Quelle]
| Last modified: $Date: 2006/05/18 12:55:55 $ FH. Search :: Sitemap :: Disclaimer :: Copyright :: Privacy |
|