I'm trying to write a wrapper for Oracle Connection(see the Ora package).
I'm using it like the following:
$fine->dbconnect()or die $_;
my $h = $fine->execSql("update qot set qot_sup_xpressfeed='$s' where qot_id=$h->{$k}->{'QOT_ID'}") ;
print "update qot set qot_sup_xpressfeed='$s' where qot_id=$h->{$k}->{'QOT_ID'}";
$fine->dbdisconnect() or die $_;
And here the Ora class:
package Ora;
use strict;
use warnings;
use DBI;
use DBD::Oracle;
use DBD::Oracle qw(:ora_types);
use Utils;
sub new
{
my ($class, $dbname, $user) = #_;
my $self = {
_dbname => lc($dbname),
_user => lc($user),
# _sth => {}
};
bless $self, $class;
return $self;
}
sub dbconnect
{
use Ora::Ora_db;
my ($this) = #_;
my $dberror = "";
my $dbdriver;
my $OS = $^O;
$ENV{'ORACLE_SID'} = $this->{_dbname};
$ENV{'ORACLE_TERM'} = "vt220";
if ($OS =~ /linux/ )
{
$ENV{'ORACLE_HOME'} = "/opt/oracle/product/10.2";
$ENV{'ORACLE_BASE'} = "/opt/oracle";
$ENV{'TNS_ADMIN'} = "/opt/oracle/product/10.2/network/admin";
$ENV{'ORA_NLS33'} = "/opt/oracle/product/10.2/ocommon/nls/admin/data"; ## TODO: Weg, wenn nur noch 1 Client!!
$ENV{'NLS_LANG'} = "GERMAN_GERMANY.WE8ISO8859P1";
}
$dbdriver = DBI->install_driver('Oracle')
or return("DB-Treiber konnte nicht geladen werden");
my $utils=new Utils();
$utils->meldung( 'Basis',"Starte DB-Verbindung|". $this->{_dbname});
my $oradb = new Ora_db($this->{_dbname});
$this->{_connection} = $dbdriver->connect(
$this->{_dbname},
"QF",
$oradb->getParam() ,
{
RaiseError => 1,
AutoCommit => 0
}) || die "Database connection not made: $DBI::errstr";
return 1;
}
sub dbdisconnect
{
my ($this ) = (#_);
return($this->{_connection}->disconnect);
}
sub execSql
{
my ($this, $mysql, $key) = (#_);
my $sth;
my $i=0;
my #rs_to; # 2dim Array!
$sth = $this->{_connection}->prepare($mysql) || die "$mysql -> ".$this->{_connection}->errstr;
$sth->execute() or die "Fehler bei sth->execute: ".$this->{_connection}->errstr;
##my $rs = $this->_toArray($sth);
my $rs = $this->_toHash($sth, $key);
$sth->finish();
$this->{_connection}->commit;
return $rs;
}
sub _toHash
{
my ($this, $sth, $key) =#_;
$sth->fetchall_hashref($key)or die($_);
}
But I'm getting this error:
Assertion i == (((((SV *) (name_av))->sv_flags & 0x00008000)) ? Perl_mg_size(my_perl, (SV *) name_av) : ((XPVAV*) (name_av)->sv_any)->xav_fill)+1 failed: file "DBI.xs", line 1844 at /usr/lib/perl5/site_perl/5.8.7/i586-linux-thread-multi/DBI.pm line 1999.
Issuing rollback() for database handle being DESTROY'd without explicit disconnect().
Could anyone give me any clue what am I doing wrong?
TIA,
Greetings
r.
I got it...This solved my problem!
my $rs ;
$rs = $this->_toHash($sth, $key) if ($key);
$sth->finish();
$this->{_connection}->commit;
return $rs;
Greetings & thanks!
Related
I don't understand what undef is doing in this snippet:
$dbh->do (qq {
INSERT INTO todo SET t = NOW(), status = 'open', content = ?
}, undef, $content);
Can someone please explain? I think I understand the whole code, but not this where it came from.
use warnings;
use strict;
use lib q(/data/TEST/perl/lib);
use CGI qw(:standard);
use WebDB;
sub insert_item {
my $content = shift;
my $dbh;
$content =~ s/^\s+//;
$content =~ s/^\s+$//;
if ($content ne "") {
$dbh = WebDB::connect();
$dbh->do (qq {
INSERT INTO todo SET t = NOW(), status = 'open', content = ?
}, undef, $content);
$dbh->disconnect();
}
}
sub display_entry_form {
print start_form(-action=> url()),
"To-do item:", br (),
textarea ( -name => "content",
-value => "",
-override => 1,
-rows =>3,
-columns => 80),
br (),
submit(-name=> "choice", -value => "Submit"),
end_form();
}
print header(), start_html(-title=>"To-Do List", -bgcolor => "white"), h2("To-Do List");
my $choice = lc(param ("choice"));
if ($choice eq "") {
display_entry_form();
} elsif ( $choice eq "submit" ) {
insert_item(param("content"));
display_entry_form();
} else {
print p ("Logic error, unknown choice: $choice");
}
The do() method takes 3 arguments: the query, query attributes, and bind data. The undef in your example means that there are no attributes to apply.
See "do()" in DBI on CPAN.
$rows = $dbh->do($statement) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
$rows = $dbh->do($statement, \%attr, #bind_values) or die ...
I was using this in the perl script, where it is login to a couple of servers and trying to change the password for the servers through a remote host. But the problem is that the password is not getting changed on both the servers as well as i am not finding a way to check if the new passwords are passed to the servers using expect. i am posting that part of the code where it is checking for the prompt and trying to change the password.
#!/usr/bin/perl
package Session;
use strict;
use warnings;
use Expect;
use IO::Pty;
use Data::Dumper;
use Time::HiRes qw(usleep);
use Switch;
use YAML;
use feature 'say';
my $host1 = $ARGV[0];
my $host2 = $ARGV[1];
my $host1_adapter_name = $ARGV[2];
my $host2_adapter_name = $ARGV[3];
my $exp = Expect->new;
my ($selfObj) = #_;
my $str = "{$host1}\{root} # ";
my $cmdStr; my $result; my $dev_id;
my $timeout = 10;
my $min = 192;
my $range = 32;
my $host1_dev_id = _adapter($host1_adapter_name);
my $host2_dev_id = _adapter($host2_adapter_name);
my #hosts = ("$host1", "$host2");
print ("host2 name is=$host2------");
foreach my $n (#hosts)
{
print ("value of n is $n\n");
if ( $n eq $host1 )
{
_login($n,$host1_dev_id);
}
if ( $n eq $host2)
{
print ("inside 2nd if-----\n");
_login($n,$host2_dev_id);
}
}
sub _login
{
my ($host,$host_dev_id) = #_;
my $exit = 1;
$exp->raw_pty(1);
$exp = Expect->spawn("telnet $host") or die "unable to connect , Please check the connection & retry again: $!\n";
if (!defined($exp))
{
print "Please check the connection & retry again\n";
return -1;
}
`sleep 2 `;
$exp->expect($timeout,
[
qr'[lL]ogin:[\s]?[a]?[s]?[\s]?$',
sub
{
$exp->send("root\r");
`sleep 3 `;
exp_continue;
}
],
[
qr'[pP]assword:[\s]?$',
sub
{
$exp->send("That11NeverWork!\r");
exp_continue;
}
],
[
qr '[#>:][\s]?$',
sub {
$cmdStr = "passwd\r";
$result =_run_cmd($cmdStr);
qr'root\'s New password:\s*';
$exp->send("raym0nd24");
qr'Enter the new password again:\s*';
$exp->send("raym0nd24");
# $exp->send('passwd:\s*',5);
$exit = 0;
exp_continue;
}
],
[
eof =>
sub
{
print("FileName : Session.pm , ERROR: premature EOF in command execution.\n");
}
],
'-re', qr'[#$>:]\s?$', # wait for shell prompt, then exit expect
);
}
#############################################################
#############################################################################
sub _adapter
{
my ($adapter_name) = #_;
print "Adapter name: $adapter_name\n";
chomp($adapter_name);
switch($adapter_name){
case "AUSTIN" {$dev_id="e414571614102004"}
case "CX5" {$dev_id="b315191014103506"}
case "CX4" {$dev_id="b31513101410f704"}
case "CX4_EG10" {$dev_id="b315151014101f06"}
case "CX4_EG25" {$dev_id="b315151014101e06"}
case "CX3" {$dev_id="RoCE"}
case "CX2" {$dev_id="b315506714106104"}
case "CX3_PRO" {$dev_id="RoCE"}
case "CX3_PRO1" {$dev_id="b31507101410e704"}
case "HOUSTON_LR" {$dev_id="df1020e214104004"}
case "HOUSTON_SR" {$dev_id="df1020e214100f04"}
case "HOUSTON_Cu" {$dev_id="df1020e214103d04"}
case "SHINER_S" {$dev_id="e4148a1614109304"}
case "SHINER_T" {$dev_id="e4148e1614109204"}
case "SLATE_SR" {$dev_id="df1020e21410e304"}
case "SLATE_CU" {$dev_id="df1020e21410e404"}
case "EVERGLADES" {$dev_id="b315151014101e06"}
else { print "Adapter not in list\n"}
}
return $dev_id;
}
#######################################################################################
##########################################################
sub _run_cmd
{
my $output; my $output1;
my ($cmdStr) = #_;
$exp->send($cmdStr ."\r");
$exp->expect(21, '-re', $str);
$output = $exp->exp_before();
$exp->clear_accum();
my #PdAt_val = split("\r?\n", $output);
foreach my $line1 (#PdAt_val)
{
chomp($line1);
if ( $line1 =~ /(\(\d+\))(\s*root\s*\#\s*)/)
{
if ( $1 =~ /\((\d+)\)/)
{
if ($1 != 0)
{
print("*************** Command $cmdStr didn't ran sucessfully ***************\n");
exit;
}
}
}
}
return $output;
}
######################################################################
There are individual solutions for different systems. So some systems got from their god the must have highlevel restrictions. So the regular says, that you cant login as root directly. To step up the long way to the stage you can use sudo or su. I didnt see that mind in your lines.
# The simpliest way is to use what you have!
sub passwd
{
my $user = #_[0];
my $password = #_[1];
#
# as root
my $execline = qq~passwd $user:$password~;
#
# as root with second password
my $execline = qq~passwd $user:$password\n$password~;
#
# for microsoft certified ubuntu noobs, kidding mint's
my $execline = qq~sudo $password && passwd $user:$password~;
#
# for apple greyed, debian nerds, solaris freaks
my $execline = qq~su $password && passwd $user:$password~;
#
my $return = system("$execline");
}
print &passwd("root","the magical word");
#
# elseif read this.url([to get the higher experience][1]);
[1]: https://stackoverflow.com/questions/714915/using-the-passwd-command-from-within-a-shell-script
I can't see any information in the Azure Blob Service Error Code list https://msdn.microsoft.com/en-us/library/dd179439.aspx that relates to error 596.
I am trying to upload some blocks to the Azure service and am getting a response back from the API with code 596 and description 'Broken pipe'.
Has anyone encountered this before ?
(N.B. Yes, I know the code below is not complete yet in that the code as-is does not upload the final chunk)
#!/usr/bin/perl
use 5.014;
use strict;
use warnings;
use autodie;
use Data::Dumper;
use Digest::MD5 qw(md5_base64);
use Crypt::PRNG::Fortuna qw(random_bytes_b64u random_bytes);
use Digest::SHA qw(hmac_sha256_base64);
use Getopt::Long;
use Sys::Syslog qw( :DEFAULT setlogsock);
use File::stat;
use AnyEvent;
use AnyEvent::HTTP;
use Time::Piece;
use Encode qw(decode encode);
use MIME::Base64 qw(encode_base64 decode_base64 encode_base64url);
use FileHandle;
use Fcntl ':flock', 'SEEK_SET';
delete #ENV{'PATH', 'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
use sigtrap 'handler' => \&term_handler, 'normal-signals';
####### PARAMS
my $script="upload.pl";
my $maxSingleUpload=1048576; # Maximum size of a single attempt upload (in bytes);
my $multiChunkSize=4194304; # Maximum size of a single block (in bytes)
my $multiLimit=6; # Maximum number of parallel HTTP requests
####### AZURE
my $azureKey="<REMOVED>";
my $azureKeyBin=decode_base64($azureKey);
####### ARGS
my ($vault,$container,$localfile,$remotefile);
my $debug=0;
GetOptions(
"vault|v=s" => \$vault,
"container|c=s" => \$container,
"localfile|l=s" => \$localfile,
"remotefile|r=s" => \$remotefile,
"debug|d+" => \$debug
);
if (!defined $vault || !defined $container || !defined $localfile || !defined $remotefile) {
say "USAGE: -v <vault> -c <container> -l <localfile> -r <remotefile> [-d (debug)]";
exit 1;
}
if (!-e $localfile) {
say "Local file does not exist !";
exit 1;
}
####### Vars
my ($wholeChunks,$chunkRemainder,$runID,$condvar,#offsets,#blocklist);
my $activeCount=0;
my $putBlockURL="https://${vault}.blob.core.windows.net/${container}/${remotefile}?comp=block&blockid=";
####### FUNCTIONS
# Quotient remainder calculator
sub qrem {
use integer;
my( $dividend, $divisor ) = #_;
my $quotient = $dividend / $divisor;
my $remainder = $dividend % $divisor;
my #result = ( $quotient, $remainder );
return #result;
}
# Do pad
sub doPad {
my ($raw) = #_;
while (length($raw) % 4) {
$raw .= '=';
}
return $raw;
}
# Random
sub getRandom {
my ($len) = #_;
#return doPad(random_bytes_b64u($len));
return doPad(encode_base64(random_bytes($len)));
}
# Term handler
sub term_handler {
doLog("err","term_handler: Program terminated early due to user input");
exit 2;
}
# Log sub
sub doLog {
my ($priority,$msg) = #_;
return 0 unless ($priority =~ /info|err|debug/);
setlogsock('unix');
openlog($script, 'pid,cons', 'user');
syslog($priority, $msg);
closelog();
return 1;
}
# Get file size
sub fileSz {
my($file) = #_;
my $stat = stat($file);
return $stat->size;
}
# Get data
sub readData {
my ($file,$length,$offset)=#_;
my $fh = FileHandle->new;
my ($data);
if ($debug) { say "Reading ${file} offset ${offset} for length ${length}";}
#open ($fh,"<",$file);
$fh->open("< $file");
binmode($fh);
seek($fh,$offset,SEEK_SET);
read($fh,$data,$length);
if ($debug) { say "readData read ".byteSize($data);}
#close($fh);
$fh->close;
return $data;
}
# Calc MD5
sub calcMD5 {
my ($data)=#_;
my $hash = md5_base64($data);
return doPad($hash);
}
# Populate offsets
sub populateOffsets {
my ($count,$offsetSize)=#_;
if (!defined $count || !defined $offsetSize) {exit 1;}
my $offset=0;
my #offsets;
for my $i (1..$count) {
push #offsets,$offset;
$offset = $offset + $offsetSize;
}
return #offsets;
}
# Calc auth string
sub azureAuth {
my($t,$signstring)=#_;
if (!defined $signstring) { exit 1;}
if ($debug) {say "String to sign:${signstring}";}
my $auth;
$auth=doPad(hmac_sha256_base64($signstring,$azureKeyBin));
if ($debug) { say "Sig:${auth}";}
return $auth;
}
# Byte size
sub byteSize {
use bytes;
my ($inval)=#_;
return length($inval);
}
# Process
sub doProcess {
return if $activeCount >= $multiLimit;
my $offset = shift #offsets;
return if !defined $offset;
$activeCount++;
if ($debug) { say "Active:${activeCount}, Offset:${offset}";}
$condvar->begin;
my $t = localtime;
my $tNow = $t->strftime();
my $blockid = getRandom(8);
my $subRunID=getRandom(5);
my $contentLength=$multiChunkSize-1;
my $content = readData($localfile,$contentLength,$offset);
my $hash = calcMD5($content);
if ($debug) { say "Block ID:${blockid}, Hash: ${hash}";}
my $url = $putBlockURL.$blockid;
my $canocResource="/${vault}/${container}/${remotefile}\nblockid:${blockid}\ncomp:block";
my $hdrs="x-ms-client-request-id:${runID}\nx-ms-date:${tNow}\nx-ms-version:2009-09-19";
my $byteLength=byteSize(${content});
my $canocHeaders=encode('UTF-8',"PUT\n\n\n${byteLength}\n${hash}\n\n\n\n\n\n\n\n${hdrs}\n${canocResource}",Encode::FB_CROAK);
my $authData=azureAuth($t,$canocHeaders);
if ($debug) {say "Length:${byteLength}";say "Sig: ${authData}"; say "URL:${url}";}
my $azureArr = {
"Authorization"=>"SharedKey ${vault}:${authData}",
"Content-Length"=>${byteLength},
"Content-MD5"=>${hash},
"x-ms-version"=>"2009-09-19",
"x-ms-date"=>${tNow},
"x-ms-client-request-id"=>"${runID}"
};
####### ERROR OCCURS HERE ....
http_request "PUT" => $url,
persistent=>0,
headers=>$azureArr,
body=>$content,
sub {
my ($body, $hdr) = #_;
say Dumper($hdr);
#say "received, Size: ", length $body;
#say $body;
$activeCount--;
$condvar->end;
doProcess();
};
return 1;
}
####### MAIN
$runID=getRandom(5);
doLog("info","${runID} Starting upload for ${localfile} (${remotefile})");
if (fileSz($localfile)<$maxSingleUpload) {
if ($debug) {say "Using single upload method";}
} else {
if ($debug) {say "Using multi-upload method";}
# Calculate chunk quantity
my #chunks = qrem(fileSz($localfile),$multiChunkSize);
$wholeChunks=$chunks[0];
$chunkRemainder=$chunks[1];
if ($debug) {say "Whole chunks (${multiChunkSize}):${wholeChunks}, Remainder:${chunkRemainder}";}
# Init
#offsets=populateOffsets(${wholeChunks},${multiChunkSize});
say Dumper(#offsets);
$condvar = AnyEvent->condvar;
# DO IT
for (1..$multiLimit) {
doProcess();
}
$condvar->recv;
}
doLog("info","${runID} Upload complete");
exit 0;
Error 596 is a client-side error returned by AnyEvent::HTTP. You need to investigate locally to see why you are hitting this error.
See this page for more info:
https://metacpan.org/pod/AnyEvent::HTTP
596 - errors during TLS negotiation, request sending and header processing.
I am try to get the list items from share point server site using perl
script.i am write the script but give the error "401 Unauthorized". please help to solve
this problem.In this i am geven domain ,username ,password also.once see the credentials.
i am write script below
use LWP::UserAgent;
use LWP::Debug;
use Data::Dumper;
use SOAP::Lite on_action => sub { "$_[0]$_[1]"; };
import SOAP::Data 'name', 'value';
our $sp_endpoint = 'http://sezdsk22787/_vti_bin/lists.asmx';
our $sp_domain = 'dev:80';
our $sp_username = 'spadmin';
our $sp_password = 'Cmc#1234';
$debug = 0;
if ($debug) {
LWP::Debug::level('+');
SOAP::Lite->import(+trace => 'all');
}
my #ua_args = (keep_alive => 1);
my #credentials = ($sp_domain, "", $sp_username, $sp_password);
my $schema_ua = LWP::UserAgent->new(#ua_args);
$schema_ua->credentials(#credentials);
$soap = SOAP::Lite->proxy($sp_endpoint, #ua_args, credentials => \#credentials);
$soap->schema->useragent($schema_ua);
$soap->uri("http://schemas.microsoft.com/sharepoint/soap/GetVersions");
$lists = $soap->GetListCollection();
quit(1, $lists->faultstring()) if defined $lists->fault();
sub lists_getid
{
my $title = shift;
my #result = $lists->dataof('//GetListCollectionResult/Lists/DL_Accounts');
foreach my $data (#result) {
my $attr = $data->attr;
return $attr->{ID} if ($attr->{Title} eq $title);
}
return undef;
}
print "#credentials \n";
sub lists_getitems
{
my $listid = shift;
my $in_listName = name('listName' => $listid);
my $in_viewName = name('viewName' => '');
my $in_rowLimit = name('rowLimit' => 99999);
my $call = $soap->GetListItems($in_listName, $in_viewName, $in_rowLimit);
quit(1, $call->faultstring()) if defined $call->fault();
return $call->dataof('//GetListItemsResult/listitems/data/row');
}
my $list_id = lists_getid('Disk Space');
print "List ID is: $list_id\n";
my #items = lists_getitems($list_id);
foreach my $data (#items) {
my $attr = $data->attr;
print Dumper($attr);
}
When starting the proxyserver (DBI::ProxyServer) with
dbiproxy --logfile C:\WINDOWS\temp\dbiproxy.log --debug 1 --localport 2000
or with
dbiproxy --configfile dbiproxy.config
everything works, except the writing of a logfile.
My dbiproxy config file:
{ 'logfile' => 'C:\WINDOWS\temp\dbiproxy.log',
'localport' => '2000',
'debug' => 1, }
I pass a filename, but the Net::Daemon::Log needs a filehandle.
Is the code not OK or have I missed something?
# Net/Daemon.pm
sub ReadConfigFile {
my($self, $file, $options, $args) = #_;
# ...
my $copts = do $file;
# ...
# Override current configuration with config file options.
while (my($var, $val) = each %$copts) {
$self->{$var} = $val;
}
}
sub new ($$;$) {
my($class, $attr, $args) = #_;
my($self) = $attr ? \%$attr : {};
bless($self, (ref($class) || $class));
my $options = ($self->{'options'} ||= {});
# ...
# ...
my $file = $options->{'configfile'} || $self->{'configfile'};
if ($file) {
$self->ReadConfigFile($file, $options, $args);
}
while (my($var, $val) = each %$options) {
$self->{$var} = $val;
}
# ...
# ...
$self;
}
# Net/Daemon/Log.pm
sub OpenLog($) {
my $self = shift;
return 1 unless ref($self);
return $self->{'logfile'} if defined($self->{'logfile'});
# ...
# ...
}
sub Log ($$$;#) {
my($self, $level, $format, #args) = #_;
my $logfile = !ref($self) || $self->OpenLog();
# ...
# ...
if ($logfile) {
my $logtime = $self->LogTime();
# <- get this far, but don't pass the "ref($logfile)"
if (ref($logfile)) {
$logfile->print(sprintf("$logtime $level, $tid$format\n", #args));
} else {
printf STDERR ("$logtime $level, $tid$format\n", #args);
}
} elsif (my $eventLog = $self->{'eventLog'}) {
# ...
# ...
}
What about putting
'logfile' => IO::File->new('C:\WINDOWS\temp\dbiproxy.log', 'a'),
into your dbiproxy config file? I don't have a way how to test it, but according to Net::Daemon::Log docs it should work.