CGI script not displaying results in browser - forms

I am attempting to display some info from an infoblox device. When I run this code in a browser using an html post, the table that displays MAC address entries does not display the values from the api. When I run this code in the unix command-line, the variables show up appropriately. Any Advice?
#!/usr/bin/perl
use strict;
use Infoblox;
use CGI;
my $cgi = new CGI;
print
$cgi->header() .
$cgi->start_html( -title => 'Form Results') .
$cgi->h1('Form Results') . "\n";
my #params = $cgi->param();
my $username = $cgi->param('username');
print '<table border="1" cellspacing="0" cellpadding="0">' . "\n";
foreach my $parameter (sort #params) {
print "<tr><th>$parameter</th><td>" . $cgi->param($parameter) . "</td></tr>\n";
}
print "</table>\n";
print "<p>$username</p>";
print $cgi->end_html . "\n";
#Create a session to the Infoblox appliance
my $session = Infoblox::Session->new(
master => "server", #appliance host ip
username => "username", #appliance user login
password => "password" #appliance password
);
unless ($session) {
die("Construct session failed: ",
Infoblox::status_code() . ":" . Infoblox::status_detail());
}
print "Session created successfully\n<br>";
my #list = $session->get(
object => "Infoblox::DHCP::MAC",
filter => "macfilter",
);
my $nextobject = $list[0];
print <<EOF;
<br>
<table>
<tr>
<th>MAC</th>
<th>Description</th>
<th>UserID</th>
<th>Expiration</th>
</tr>
EOF
foreach my $test ( #list ) {
print "<tr>";
print "<td> $test->mac()</td>";
print "<td>" . scalar($test->comment()) . "</td>\n";
print "<td>" . scalar($test->username()) . "</td>\n";
print "<td>" . scalar(localtime(scalar($test->expiration_time()))) . "</td>\n";
print "</tr>";
}
exit (0);

I had incorrect permissions. The script was running as user nobody and would not display the items correctly on the web page.

Related

Getting Blank Screen for Perl CGI Script

I am getting blank screen for the below Perl CGI Script on the web page.
Script is getting executed fine on the terminal, but when I run it from the web browser it is blank. Please help.
This works when I move the Web Content to the top of the page. Basically whatever content I put after the DB connection is not getting displayed on the web browser.
OS : Unix
Apache2 Web Server
Note: The script has execute permission.
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use CGI;
print "Content-type: text/html\n\n";
# Simple HTML code follows
my $driver= "Oracle";
my $dsn = "DBI:$driver:sid=xxxxx;host=xxxxx;port=1521";
my $dbh = DBI->connect($dsn,'xxxx','xxxx');
#print $dbh;
my $sth = $dbh->prepare("SELECT * FROM TABLE WHERE ROWNUM <= 10");
$sth->execute;
print "<html> <head>\n";
print "<title>Hello, world!</title>";
print "</head>\n";
print "<body>\n";
print "<h1>Hello, world!</h1>\n";
print "<p>The Details are as follows:</p>\n";
print "<table cols=5 border=1>\n";
print "<tr>\n";
print "<th>ACTION</th>\n";
print "<th>ALARM_TEXT</th>\n";
print "<th>ALARM_SEV</th>\n";
print "<th>EMS_NAME</th>\n";
print "</tr>";
while( my $ref = $sth->fetchrow_hashref() ) {
print "<tr>\n";
print "<td>", $ref->{'ACTION'}, "</td>\n";
print "<td>", $ref->{'ALARM_TEXT'}, "</td>\n";
print "<td>", $ref->{'ALARM_SEV'}, "</td>\n";
print "<td>", $ref->{'EMS_NAME'}, "</td>\n";
print "</tr>\n";
}
print "</table>\n";
print "<h1>Hello, world!</h1>\n";
print "</body> </html>\n";
Fixed it by adding the below line to the httdd.conf file.
SetEnv ORACLE_HOME /oracle/app/oracle/product/11.2.0.4/db_1

Error Cisco Prime HTTP GET request

I'm trying to make an HTTP GET request with Cisco Prime:
#!/opt/local/bin/perl -w
use strict;
use JSON-support_by_pp;
use LWP 5.64;
use LWP::UserAgent;
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
my $ua = LWP::UserAgent->new;
my $BASE_URL = 'https://Host_name/webacs/api/v1/';
my $UN = "Username";
my $PW = "Password";
sub fetch ($) {
my ( $url ) = #_;
my $req = HTTP::Request->new( GET => $BASE_URL . $url );
$req->authorization_basic( $UN, $PW );
return $ua->request( $req )->content or die( "Cannot read from " . $BASE_URL . $url );
}
my $content = fetch( 'data/AccessPoints.json?.full=true' );
my $json = new JSON;
# these are some nice json options to relax restrictions a bit:
my $json_text =
$json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode( $content );
foreach my $ap ( #{ $json_text->{queryResponse}->{'entity'} } ) {
print "------------------------\nAccess Point " . $ap->{'accessPointsDTO'}->{'#id'} . "\n";
print "Model:" . $ap->{'accessPointsDTO'}->{'model'} . "\n";
print "MAC Address:" . $ap->{'accessPointsDTO'}->{'macAddress'} . "\n";
print "Serial Number:" . $ap->{'accessPointsDTO'}->{'serialNumber'} . "\n";
print "Software Version:" . $ap->{'accessPointsDTO'}->{'softwareVersion'} . "\n";
print "Status:" . $ap->{'accessPointsDTO'}->{'status'} . "\n";
print "Location:" . $ap->{'accessPointsDTO'}->{'location'} . "\n";
What do I do wrong? I have already tried with curl in shell and it works:
curl --tlsv1 --user USER:PASSWORD--insecure https://Host_name/webacs/api/v1/data/AccessPoints.json?.full=true
but my Perl script doesn't work.
I have this error:
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "Can't connect to 10....") at ersteProbe.pl line 28.
Fix already. Thank you Borodin :)
New question:
I need authentication for Cisco Prime.
Code works already, but authentication doesn't work.
I have with error
500 Can't connect to 10.10.10.10:443 (certificate verify failed) at ersteProbeAuth.pl line 27.
Line 27:
die $res->status_line unless $res->is_success;
I'm rather new in Perl und cann't fix this myself. If you have Idee, I'll be happy :)
#!/opt/local/bin/perl -w
use strict;
use warnings;
use JSON -support_by_pp;
use LWP 5.64;
use LWP::UserAgent;
use MIME::Base64;
use REST::Client;
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;
my $ua = LWP::UserAgent->new;
my $BASE_URL = 'https://10.10.10.10/webacs/api/v1/';
my $UN='admin';
my $PW='admin';
# coding with Base 64
my $sys_id='Balalalalalal';
my $encoded_auth = encode_base64("$UN:$PW", '');
sub fetch {
my ($url) = #_;
my $res = $ua->get($BASE_URL . $url,
{'Authorization' => "Basic $encoded_auth",
'Accept' => 'application/json'});
die $res->status_line unless $res->is_success;
my $json = $res->decoded_content;
return $json
}
my $content = fetch('data/AccessPoints.json?.full=true/$sys_id');
my $json = new JSON;
# these are some nice json options to relax restrictions a bit: my$json_text=$json->allow_nonref->utf8->relaxed->escape_slash->loose->allow_singlequote->allow_barekey->decode($content);
foreach my $ap (#{$json_text->{queryResponse}->{'entity'}}){
print "------------------------\nAccess Point ".$ap->{'accessPointsDTO'}->{'#id'}."\n";
print "Model:".$ap->{'accessPointsDTO'}->{'model'}."\n";
print "MAC Address:".$ap->{'accessPointsDTO'}->{'macAddress'}."\n";
print "Serial Number:".$ap->{'accessPointsDTO'}->{'serialNumber'}."\n";
print "Software Version:".$ap->{'accessPointsDTO'}->{'softwareVersion'}."\n";
print "Status:".$ap->{'accessPointsDTO'}->{'status'}."\n";
print "Location:".$ap->{'accessPointsDTO'}->{'location'}."\n";
}
It's hard to tell what's wrong without access to the web page, but almost certainly your request has failed
I suggest you replace your fetch subroutine with this
sub fetch {
my ( $url ) = #_;
my $res = $ua->get( $BASE_URL . $url );
die $res->status_line unless $res->is_success;
my $json = $res->decoded_content;
return $json;
}
Print your raw answer from server in console.
malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "Can't connect to 10....")
"Can't connect to 10...."
Maybe, your code is not have connect

STDOUT from Pidgin plugin script

Yesterday, I wrote a perl plugin script for Pidgin 2.10.9, running on Windows 7, and using Strawberry Perl 5.10.1.5
Basically, on the receipt of an IM, it uses backticks to call a console application (written in .NET) and returns the console output to the sender as an IM.
I had to reboot this morning, but ever since I rebooted, it has stopped working.
So, I changed the backticks to use "capture". That didn't work either, but it at least gave me this error:
(15:00:33) Plugin: Error: Error in IPC::System::Simple plumbing: "Can't dup STDOUT" - "Bad file descriptor" at (eval 12) line 53
I have no idea what's changed from yesterday to today, and wondered if anybody knew what might be causing the error?
Thanks
Edit: Thought I'd add my code
use Purple;
#use IPC::System::Simple qw(system systemx capture capturex);
use IPC::System::Simple qw(capture capturex);
%PLUGIN_INFO = (
perl_api_version => 2,
name => "PlugIn",
version => "0.1",
summary => "AutoResp",
description => "PlugIn",
author => "Mark Watkin",
url => "http://",
load => "plugin_load",
unload => "plugin_unload"
);
sub plugin_init {
return %PLUGIN_INFO;
}
sub plugin_load {
my $plugin = shift;
Purple::Debug::info("PlugIn", "plugin_load()\n");
$data = "";
$conversation_handle = Purple::Conversations::get_handle();
Purple::Signal::connect($conversation_handle, "received-im-msg", $plugin, \&signal_chat_callback, $data);
}
sub plugin_unload {
my $plugin = shift;
Purple::Debug::info("PlugIn", "plugin_unload()\n");
}
sub signal_chat_callback {
# The signal data and the user data come in as arguments
my ($account, $sender, $message, $conv, $flags) = #_;
Purple::Debug::info("PlugIn", "Account Alias \"" . $account->get_alias() . "\"\n");
if( $account->get_alias() eq "PlugIn" )
{
Purple::Debug::info("PlugIn", "Request: \"" . $message . "\"\n");
if(!$conv)
{
Purple::Debug::info("PlugIn", "No conversation\n");
$conv = Purple::Conversation->new(1, $account, $sender);
}
$im = $conv->get_im_data();
$im->send( "One moment please..." );
my $query = "";
# eval {
# $query = capture("\"D:\\SourceCode\\PlugInNET\\bin\\Debug\\PlugInNET.exe\" \"" . $message . "\"");
# #$query = capture("\"D:\\SourceCode\\PlugInNET\\bin\\Debug\\PlugInNET.exe\"", "\"" . $message . "\"");
# #my $query = capture("D:\\SourceCode\\PlugInNET\\bin\\Debug\\PlugInNET.exe");
# #my $query = `\"D:\\SourceCode\\PlugInNET\\bin\\Debug\\PlugInNET.exe\" \"$message\"`;
# #my $query = `dir /b`;
# };
# if( $# )
# {
# Purple::Debug::info("PlugIn", "Error: " . $# . "\n");
# }
Purple::Debug::info("PlugIn", "Query: " . $query . "\n");
open ( my $fh, "-|", "D:\\SourceCode\\PlugInNET\\bin\\Debug\\PlugInNET.exe \"$message\"" ) or die "Cannot run free, $ERRNO";
while (<$fh>)
{
Purple::Debug::info("PlugIn", "Read: Line " . $_ . "\n");
$query = $query . $_ . "\n";
}
close $fh;
Purple::Debug::info("PlugIn", "Query: " . $query . "\n");
if( $query eq "" )
{
$im->send( "I'm sorry, my brain doesn't seem to be functioning at the moment" );
} else {
#msgs = split(/-----------\n/, $query);
foreach( #msgs )
{
Purple::Debug::info("PlugIn", "Result Msg: \"" . $_ . "\"\n");
$im->send( "<BODY>" . $_ . "</BODY>" );
}
}
}
}
The plan was to fix up the paths once I had it working properly
Please consider using file handles instead of backticks to capture stdout from another source. You'll be able collect errors.
#!/usr/bin/perl
use strict;
use warnings;
use English;
# No taint protection in this example
open ( my $fh, '-|', '/usr/bin/free' ) or die "Cannot run free, $ERRNO";
while (<$fh>)
{
print;
}
close $fh;

Global symbol "$line" and "$addr" requires explicit package name

I'm trying to get the output to show a list of ip addresses and login with the corresponding country but I keep getting these errors: Global symbol $line and $addr requires explicit package name. It works fine in Perl but I'm running this script from the server. Anyone have any ideas? Thanks.
#!/usr/bin/perl
my $psql = "/usr/local/pgsql/current/bin/psql";
my $db = 'cpi';
my $args = "-U postgres -qc";
my $date = `/bin/date +\%y\%m\%d%H`;
my $reportfile = "/tmp/multiiplogins-$date";
my $sendmail = "/usr/sbin/sendmail -t -fcpi\#cpi-syndication.com";
my $mailsubject = "Login Report";
my $mailto = 'user#yahoo.com';
my $query = "SELECT userid, login, email, logins, ips FROM (SELECT userid,login,email, count(userid) AS logins, count(ipaddr) AS ips FROM (SELECT l.userid, u.login, u.email$
my $query2 = "SELECT l.userid, login, email, ipaddr FROM synloginaccess l, synusers u where l.accesstime > (now() - interval '24 hours') and l.type=2 and l.userid=u.userid $
open (REPORT, ">$reportfile");
my $command = qq/$psql $db $args "$query"/;
my $command2 = qq/$psql $db $args "$query2"/;
my $result = `$command`;
my $result2 = `$command2`;
#update IP addresses with country
use strict;
use warnings;
use Net::IPInfoDB;
my $g = Net::IPInfoDB->new;
$g->key("api_key");
#we split $login into an array, line-by-line
my #lines = split("\n",$result2);
for my $line (#lines) {
#now we iterate through every line one-by-one
$line =~ /(?<ip>\d+\.\d+\.\d+\.\d+)/;
my $addr = $g->get_country("$1");
print "$line " . "| ". "$addr->country_name" ."\n";
}
#print REPORT "$result2\n";
#print REPORT "\n";
print REPORT "$line " . "| ". "$addr->country_name" ."\n";
close REPORT;
mailReport();
sub mailReport{
#mail it
open(MAIL, "|$sendmail");
print MAIL "To: $mailto\n";
print MAIL "Subject: $mailsubject\n";
print MAIL "\n";
open (INFILE, "$reportfile");
my #contents = <INFILE>;
Your $line and $addr variables are no longer in scope when you try to print them after your for loop:
#print REPORT "$result2\n";
#print REPORT "\n";
print REPORT "$line " . "| ". "$addr->country_name" ."\n";
I imagine this line is supposed to be commented out.

Inspect cookies using Perl

I've written a short Perl script that lists the current cookies for the website, but somehow it reports the cookie's domain and expires empty. What am I doing wrong or am I misunderstanding the mechanics behind cookies?
My ultimate goal is to be able to delete exsisting cookies with a button.
The script is live here, but it may help if you visit my blog first so there are actually some cookies set. Here is my source code:
use warnings;
use strict;
use CGI::Cookie;
my $table;
my %cookies = CGI::Cookie->fetch;
if ( keys %cookies ) {
$table .= "<table border=\"3\" cellpadding=\"5\">";
$table .= "<caption>COOKIES</caption>";
$table .= "<tr><th>Name</th><th>Domain</th><th>Path</th><th>Expires</th>
<th align=\"left\">Value</th></tr>";
foreach my $cookie ( keys %cookies ) {
$table .= "<tr>";
$table .= "<td>$cookie</td>";
$table .= "<td>" . $cookies{ $cookie }->domain() . "</td>";
$table .= "<td>" . $cookies{ $cookie }->path . "</td>";
$table .= "<td>" . $cookies{ $cookie }->expires . "</td>";
$table .= "<td>" . $cookies{ $cookie }->value . "</td>";
$table .= "</tr>";
}
$table .= "</table>";
}
print "Content-Type: text/html\n\n";
print "<html>\n";
print "<head></head>\n";
print "<body>\n";
print "$table";
print "</body>\n";
print "</html>\n";
Regardless the various cookies on various websites where I install the script, the output looks like this and Domain and Expires is always empty:
+-----------------------------------------------------------------------------------------+
| Name | Domain | Path | Expires | Value |
|---------------+--------+------+---------+-----------------------------------------------|
| bb2_screener_ | | / | | 1379007156 2001:980:1b7f:1:a00:27ff:fea6:a2e7 |
+-----------------------------------------------------------------------------------------+
Browsers does not provide any meta information to the server about the cookies they send. There isn't even a way for them to send it. What the browser sends looks like the following:
Cookie: a=b; c=d; e=f