如何使用Perl更改mysql密码

时间:2014-03-28 18:41:33

标签: mysql perl

我需要使用Perl脚本更改一些mysql密码。以下在更改数据库条目时有效,但是当我为mysql用户更改修改它时,它会将它们重置为空密码。最后“冲洗特权”也很好,但我还没有找到方法。

#!/usr/bin/perl

use DBI;
use strict;

my $newpass = "newpass";
my $driver = "mysql";
my $database = "mysql";
my $dsn = "DBI:$driver:database=$database";
my $dbh = DBI->connect($dsn, 'root', 'mysql' ) or die $DBI::errstr;
my $sth = $dbh->prepare("update user set password='$newpass' where User='admin'");
$sth->execute() or die $DBI::errstr;
$sth->finish();
$dbh->{AutoCommit} = 0;
$dbh->commit or die $DBI::errstr;

3 个答案:

答案 0 :(得分:4)

你错过了几个步骤。 使用PASSWORD()命令并使用'admin'而不是'root',并添加flush priv。 我在这里为你重写了脚本:

#!/usr/bin/perl

use DBI;
use strict;

my $newpass = "newpass";
my $driver = "mysql";
my $database = "mysql";
my $dsn = "DBI:$driver:database=$database";
my $dbh = DBI->connect($dsn, 'root', 'mysql' ) or die $DBI::errstr;
$dbh->{AutoCommit} = 0;
my $sth = $dbh->prepare("update user set password=PASSWORD('$newpass') where User='root'");
$sth->execute() or die $DBI::errstr;
$dbh->do('FLUSH PRIVILEGES') or die $DBI::errstr;
$sth->finish();
$dbh->commit or die $DBI::errstr;

答案 1 :(得分:1)

您希望使用SET PASSWORD语法:

SET PASSWORD FOR 'username'@'localhost' = PASSWORD('cleartext password');

答案 2 :(得分:1)

改变这个:

my $sth = $dbh->prepare("update user set password='$newpass' where User='admin'");

进入这个:

my $sth = $dbh->prepare("update mysql.user set Password=Password('$newpass') 
                         where User='admin' and Host='localhost'");