I need to change a few mysql passwords using a Perl script. The following works when changing database entries, but when I modified it for mysql user changes, it resets them to a blank password. It would also be nice to 'flush privileges' at the end of it, but I haven't found the method for that.
#!/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;
You're missing a couple of steps.
Use the PASSWORD() command and used 'admin' and not 'root' and also add flush priv's.
I rewrote the script for you, here:
#!/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;
You'll want to use the SET PASSWORD syntax:
SET PASSWORD FOR 'username'#'localhost' = PASSWORD('cleartext password');
Change this:
my $sth = $dbh->prepare("update user set password='$newpass' where User='admin'");
Into this:
my $sth = $dbh->prepare("update mysql.user set Password=Password('$newpass')
where User='admin' and Host='localhost'");
Related
I am trying to make a little script to extract databases/tables/columns from my database, but in the first step I couldn't move on, I am getting databases in strange list, please look:
#!/usr/bin/perl
use DBI;
$host = "localhost";
$user = "wnyclick_siteusr";
$pw = "Hank0402\$";
$dsn = "dbi:mysql:$database:localhost:3306";
$connect = DBI->connect($dsn, $user, $pw);
$databases = $connect->selectcol_arrayref('show databases');
use Data::Dumper;
print Dumper $databases;
executing this code giving me the following:
$VAR1 = [
'information_schema',
'wnyclick_sitedatawp'
];
How can I put this execution result in a list?
print #VAR1[0];
print #databases[0];
I just modified your code. Try the below code:
#!/usr/bin/perl -w
use DBI;
use DBD::mysql;
my $user = "wnyclick_siteusr";
my $pw = "Hank0402\$";
#Connecting Database
$dbh = DBI->connect( 'dbi:mysql:database=mysql;host=localhost;port=3306', '$user', '$pw' )
or die "Connection Error: $DBI::errstr\n";
$sql = "show databases";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
while ( #row = $sth->fetchrow_array ) {
#print $row[1];
print "#row\n";
}
I have connected to one MySQL database which have been hosted in a remote server in Perl. Now I am trying to execute a select statement on a table in subject.pl file using Perl command line. The code is
#!/usr/bin/perl
use DBI;
use strict;
# Connected to mysql audit database in dev server
my $dsn = 'DBI:mysql:Driver={mysql}';
my $host = 'dev-mysql.learn.local';
my $database = 'subject';
my $user = 'testUser';
my $auth = 'testPassword';
my $dbh = DBI->connect("$dsn;host=$host;Database=$database",$user,$auth) or die "Database connection not made: $DBI::errstr";
# Prepare query
my $sql = "SELECT
subject_id
,subject_value
FROM
subject";
my $sth = $dbh->prepare($sql);
#Execute the statement
$sth->execute() or die "Unable to execute".$sth->errstr;
while (my #row = $sth->fetchrow_array()) {
my ($subject_id, $subject_value ) = #row;
print "$subject_id,$subject_value,$subject_db_field\n";
}
$sth->finish();
I am getting error at line $sth->execute() or die "Unable to execute".$sth->errstr;
The error message is Unable to execute at D:\Demo\perl_demo\subject.pl line 24.
But when I am printing the $dbh variable, its giving the result like DBI::db=HASH(0x1ca7884). So I guess the connection is establishing properly.
Please help me to fix this issue as I am completely new in Perl scripting.
Check for errors on prepare,
my $sth = $dbh->prepare($sql) or die $dbh->errstr;
I have created a code that connects to database and i want to delete data from database using a button the same for update. but i just can display data in a table and cant delete.
my $q= new CGI;
print $q->header;
print $q-> start_html(
-title => "",
);
# print $q->start_form;
## mysql user database name
my $db = "people";
## mysql database user name
my $user = "root";
## mysql database password
my $pass = "";
## user hostname : This should be "localhost" but it can be diffrent too
my $host="127.0.0.1";
## SQL query
my $query = "select ID,Name,Surname,Gender from person";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $sqlQuery = $dbh->prepare($query)
or die "Can't prepare $sqlQuery: $dbh->errstr\n";
my $rv = $sqlQuery->execute
or die "can't execute the query: $sqlQuery->errstr";
print start_form (-method => 'post', -action => "modify.pl" );
my #aRows;
while (my #data = $sqlQuery->fetchrow_array()) {
my $cRowId = hidden('ID', $data[0]);
my $bt1 = submit('action','delete');
my $bt2 = submit('action','update');
push #aRows, ($cRowId, $q->Tr($q->td([$data[1], $data[2], $data[3],$bt1,$bt2])));
}
print $q->table({-border =>'1', -align =>'center', -width => '100%'},
$q->Tr([$q->th([ 'Name', 'Surname', 'Gender', 'Delete', 'Update', ])]),
#aRows,
);
print $q->input({-type => 'button', -class => 'button', -onclick => "window.location.href='insert.pl';", -value => 'Shto'});
print $q->end_form;
print $q->end_html;
delete.pl
use CGI;
use CGI qw(standard);
use DBI;
use CGI::Carp qw(set_die_handler);
use CGI qw/:all/;
BEGIN {
sub handle_errors {
my $msg = shift;
print "content-type: text/html\n\n";
#proceed to send an email to a system administrator,
#write a detailed message to the browser and/or a log,
#etc....
}
set_die_handler(\&handle_errors);
}
my $q = CGI->new();
my $db = "people";
my $user = "root";
my $pass = "";
my $host="127.0.0.1";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $action = $q->param('action'){
given ($action){
when('delete'){
my $row_id = $q->param('ID');
my $sth = $dbh->prepare("DELETE FROM person WHERE ID = $row_id ") or die "Can't prepare $query: $dbh->errstr\n";
my $rv = $sth->execute() or die $DBI::errstr;
print "deleted";
my $sth->finish();
my $dbh->commit or die $DBI::errstr;
}
} }
I dont know where may be the problem
The vast majority of Perl CGI problems can be solved by:
Adding use strict and use warnings to your code
Fixing all of the errors that now appear in your error log
You assign a value to $row_id after you try to use that variable to create your query.
Additionally, using raw user input in SQL queries makes you vulnerable to XSS attacks. Rewrite your code to use parameterized queries
Do not use my if you do not want a new variable. Remove all my's from the method calls:
my $sth->finish();
my $dbh->commit or die $DBI::errstr;
I just learned poo and i got to play with perl, achieved this but I do not get the expected output, problem with mysql? Or bad code?. other thing, the same query runs on console and workbench, and this module add chmod +x module.pm
#!/usr/bin/perl
use warnings;
use strict;
use DBI;
use DBD::mysql;
package MysqlTest;
sub new{
my $class = shift;
my $query={};
bless($query, $class);
}
sub conexion{
my $self=shift;
my($database, $host, $user, $pwd)=#_;
my $connect = DBI->connect("DBI:mysql:$database:$host", $user, $pwd) or die $DBI::errstr;;
$self->{"host"}="$host";
$self->{"database"}="$database";
$self->{"user"}="$user";
$self->{"pass"}="$pwd";
my $mysqlopen = 1;
return;
}
sub consulta{
my $self=shift;
if (!$mysqlopen) { &conexion; }
my $id = "SELECT * FROM save_bookmarks WHERE id='123'";
$result = $connect->prepare($id);
$result->execute();
my #resultado = $result->fetchrow_array();
print "#resultado\n";
return;
}
sub datos{
my $self=shift;
print "::DATOS DE ACCESO::\n";
while (($key, $value)=each(%$self)){
print "$key => $value\n";
}
}
1;
this file called method and created object. add to chmod +x file.pl , but i don't know, whats not work?
#!/usr/bin/perl
use MysqlTest;
use warnings;
use strict;
my $mysqltest = MysqlTest->new();
$mysqltest->conexion("bookmarks", "localhost", "root", "pass");
$mysqltest->consulta();
output in console
DBI connect(':','',...) failed: Access denied for user 'delkav'#'localhost' (using password: NO) at MysqlTest.pm line 17.
Access denied for user 'delkav'#'localhost' (using password: NO) at MysqlTest.pm line 17.
any idea?
The OO itself is correct.
The error message comes from MySQL, denying access for the user 'delkav', but I the user you want to connect with is 'root'.
Anyway, seems your DBI->connect() line is wrong. To follow the DBD::mysql docs, you must change your line:
my $connect = DBI->connect("DBI:mysql:$database:$host", $user, $pwd) or die $DBI::errstr;
to
my $connect = DBI->connect("DBI:mysql:database=$database;host=$hostname;", $user, $pwd) or die $DBI::errstr;
How do I call MySQL stored procedures from Perl? Stored procedure functionality is fairly new to MySQL and the MySQL modules for Perl don't seem to have caught up yet.
MySQL stored procedures that produce datasets need you to use Perl DBD::mysql 4.001 or later. (http://www.perlmonks.org/?node_id=609098)
Below is a test program that will work in the newer version:
mysql> delimiter //
mysql> create procedure Foo(x int)
-> begin
-> select x*2;
-> end
-> //
perl -e 'use DBI; DBI->connect("dbi:mysql:database=bonk", "root", "")->prepare("call Foo(?)")->execute(21)'
But if you have too old a version of DBD::mysql, you get results like this:
DBD::mysql::st execute failed: PROCEDURE bonk.Foo can't return a result set in the given context at -e line 1.
You can install the newest DBD using CPAN.
There's an example in the section on Multiple result sets in the DBD::mysql docs.
#!/usr/bin/perl
# Stored Proc - Multiple Values In, Multiple Out
use strict;
use Data::Dumper;
use DBI;
my $dbh = DBI->connect('DBI:mysql:RTPC;host=db.server.com',
'user','password',{ RaiseError => 1 }) || die "$!\n";
my $sth = $dbh->prepare('CALL storedProcedure(?,?,?,?,#a,#b);');
$sth->bind_param(1, 2);
$sth->bind_param(2, 1003);
$sth->bind_param(3, 5000);
$sth->bind_param(4, 100);
$sth->execute();
my $response = $sth->fetchrow_hashref();
print Dumper $response . "\n";
It took me a while to figure it out, but I was able to get what I needed with the above. if you need to get multiple return "lines" I'm guessing you just...
while(my $response = $sth->fetchrow_hashref()) {
print Dumper $response . "\n";
}
I hope it helps.
First of all you should be probably connect through the DBI library and then you should use bind variables. E.g. something like:
#!/usr/bin/perl
#
use strict;
use DBI qw(:sql_types);
my $dbh = DBI->connect(
$ConnStr,
$User,
$Password,
{RaiseError => 1, AutoCommit => 0}
) || die "Database connection not made: $DBI::errstr";
my $sql = qq {CALL someProcedure(1);} }
my $sth = $dbh->prepare($sql);
eval {
$sth->bind_param(1, $argument, SQL_VARCHAR);
};
if ($#) {
warn "Database error: $DBI::errstr\n";
$dbh->rollback(); #just die if rollback is failing
}
$dbh->commit();
Mind you i haven't tested this, you'll have to lookup the exact syntax on CPAN.
Hi, similar to above but using SQL exec. I could not get the CALL command to work. You will need to fill in anything that is within square brackets and remove the square brackets.
use DBI;
#START: SET UP DATABASE AND CONNECT
my $host = '*[server]*\\*[database]*';
my $database = '*[table]*';
my $user = '*[user]*';
my $auth = '*[password]*';
my $dsn = "dbi:ODBC:Driver={SQL Server};Server=$host;Database=$database";
my $dbh = DBI->connect($dsn, $user, $auth, { RaiseError => 1 });
#END : SET UP DATABASE AND CONNECT
$sql = "exec *[stored procedure name]* *[param1]*,*[param2]*,*[param3]*;";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";