Manually add parameters in perl cgi - perl

I've written a cgi script and it does the following:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:cgi-lib :standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
my $q = new CGI;
print $q->header;
print "<center>";
print $q->h1('Let\'s do something!');
print "</center>";
print $q->start_html(-title => 'Do something');
print $q->end_form;
our %in;
&ReadParse(%in);
my #keys = keys %in;
my #values = values %in;
main();
sub main{
print "<center>";
my $q0 = new CGI;
print $q0->start_form(
-name => 'sniff_button',
-method => 'POST',
-enctype => &CGI::URL_ENCODED,
);
print $q0->submit(
-name => 'button',
-value => 'Do something',
);
print $q0->end_form;
print "</center>";
}
What I want to do is add some parameters manually, because the next that depends on the previous state and not only on the current state (So I have to pass a parameter twice.).
I've done stuff with param() and URI, but none of them work. Any advice?

A hidden field is the answer:
sub main{
print "<center>";
my $q0 = new CGI;
print $q0->start_form(
-name => 'sniff_button',
-method => 'POST',
-enctype => &CGI::URL_ENCODED,
);
print $q0->hidden(
-name => 'machine_state',
-default => 'some_previous_value');
print $q0->submit(
-name => 'button',
-value => 'Do something',
);
print $q0->end_form;
print "</center>";
}

Related

Put data from a text file into an HTML form

I have a text file that shows a list of currency exchanges rates.
I have read the first line of the text file content and I need this line to be inserted into the input form.
Perl
#!/usr/local/bin/perl
use strict;
use warnings;
use CGI qw(:standard);
#use Data::Dumper;
#use CGI;
my $q = CGI->new;
my %data;
$data{name} = $q->param('name');
print header;
my $file = '/admin/currencyX.txt';
open my $info, $file or die "Could not open $file: $!";
while ( my $line = <$info> ) {
print $line, "<br>";
last if $. == 1;
}
print
start_html('A Simple Example'),
h1('A Simple Example'),
start_form,
"What's your value? <br>",
textfield(-name => 'name', -class => 'nm', -value => '$line'),
p,
submit(-value => 'Add', -name => 'ed'),
end_form,
hr;
if ( $ENV{'REQUEST_METHOD'} eq "POST" ) {
if ( $data{name} eq '' ) {
print "Please provide the input";
exit;
}
#print "response " . Dumper \%data;
}
if ( param() ) {
print
"Your name is",em(param('name')),
hr;
}
print end_html;
The text file has a similar values like
Text file
AFN Afghan Afghani 73.0556951371 0.0136881868
ALL Albanian Lek 108.3423252926 0.0092300031
DZD Algerian Dinar 117.9799583224 0.0084760159
AOA Angolan Kwanza 249.2606313396 0.0040118650
ARS Argentine Peso 28.2508833695 0.0353971232
AMD Armenian Dram 482.0941933740 0.0020742834
I need a correction to make this work.
textfield(-name => 'name', -class => 'nm', -value => '$line'),
Your problem appears to be that you have put $line in single quotes - which stops it being interpolated. Try just removing them.
textfield(-name => 'name', -class => 'nm', -value => $line),
The best way to do this is to find an alternative to out putting the text value
open my $getV, '<', "/admin/currencyX.txt";
my $realV = <$getV>;
close $getV;
print $realV; # will out put AFN Afghan Afghani 73.0556951371 0.0136881868
Then append the string to a html input value
"What's your value? <br>",textfield(-name =>'name', -class =>'nm', -value =>$realV),

Parsing hash in perl to CSV format

I need to parse my text file (my output) to csv format, which contains just Names and Ips from devices. Somthing like:
Name, ip
LAB-W, 10.66.1.12
LAB-D, 10.66.1.13
I do not have experience with parsing in perl, maybe somebody can help me with this question.
use Net::Cisco::ISE;
use Data::Dumper;
use Text::CSV;
my $ise = Net::Cisco::ISE->new(hostname=>'hostname', username=>'user', password=>'user');
for my $name (keys %{$networkdevices}){
my $device = $ise->networkdevices("id" => $networkdevices->{$name}->id);
print Dumper $device->name;
print Dumper $device->NetworkDeviceIPList;
}
And I have this output:
$VAR1 = 'LAB-W';
$VAR1 = {
'NetworkDeviceIP' => {
'mask' => '32',
'ipaddress' => '10.66.1.12'
}
};
$VAR1 = 'LAB-D';
$VAR1 = {
'NetworkDeviceIP' => {
'mask' => '24',
'ipaddress' => '10.66.1.13'
}
};
I tried this script (from this post), but I do not see output, also no mistakes :
use DBI;
use strict;
use Data::Dumper;
use File::Slurp;
open (FILE, "<./my_output") or die "could not open file: $!";
undef $/;
my $contents = <FILE>;
close(FILE);
my $hash_of_arrays = eval $contents;
for my $key (keys %$hash_of_arrays) {
my $hash = $hash_of_arrays->{$key};
for my $key2 (keys %$hash) {
my $array = $hash->{$key2};
for my $i (0..$#$array) {
print "$i: $$array[$i]\n";
}
}
}
Since the data are just in a hash, you can access them directly inside your loop:
for my $name (keys %{$networkdevices}){
my $device = $ise->networkdevices("id" => $networkdevices->{$name}->id);
print join(',',
$device->name
$device->NetworkDeviceIPList->{NetworkDeviceIP}->{ipaddress}
) . "\n";
}

Perl: WWW:Mechanize, getting Facebook profile image?

#!/usr/bin/perl
#USE DECLARATIONS
use strict;
use warnings;
use WWW::Mechanize;
use Term::ANSIColor;
#VARIABLE DECLARATIONS
my $mech = WWW::Mechanize->new();
my $img;
my $title;
my $pic_page;
my $url;
my $count;
my #links;
#CONNECT TO FACEBOOK
$url = 'https://www.facebook.com/';
$mech = WWW::Mechanize->new();
$mech->agent_alias( 'Linux Mozilla' );
$mech->get( $url );
$title = $mech->title();
#LOGIN FORM
print "Connected to Facebook.\n";
print "Logging in...";
$mech->form_id("login_form");
$mech->field("email",'my#email.com');
$mech->field("pass",'mypass');
$mech->click();
print "done!\n";
#NAVIGATE TO USER PAGE
$mech->get("https://www.facebook.com/some.profile1234");
$title = $mech->title();
print "Finding $title 's profile pictue...\n";
#FIND PROFILE PICTURE
$img = $mech->find_image(url_regex => qr/s160x160/, );
print $img->url();
downloadImage($img->url(),$mech->title().".jpg");
sub downloadImage
{
my $local_file_name = $_[1];
my $b = WWW::Mechanize->new;
print "Downloading: $_[1]...";
$b->get( $_[0], ":content_file" => $local_file_name );
print "done!\n";
}
With this code I just want to download profile picture of a given person (#NAVIGATE TO USER PAGE) and save it. However, I get an error saying essentially that no images could be found! WHYYY? (I am using the $mech->find_image(url_regex => qr/s160x160/,) to find the image on the profile page.)
You are using new instance of Mechanize in your downloadImage sub. And this instance is not authorized by Facebook.
Try this:
downloadImage($img->url(),$mech->clone() );
sub downloadImage
{
my $mech = $_[1];
print "Downloading: $_[1]...";
$mech->get( $_[0], ":content_file" => $mech->title() . ".jpg" );
print "done!\n";
}

BUILD Problems: Connect class chat

I'm having problems with the BUILD method, I want to connect to an HTML-based chat. I wish this class would keep me logged in order to execute the action of sending and receiving messages.
I tried the way down, but it seems that causes a stress on the server while running.
package Shoutbox;
use common::sense;
use WWW::Mechanize;
use WWW::Mechanize::DecodedContent;
use JSON -support_by_pp;
use URI::Escape;
use Moose;
our $url = WWW::Mechanize->new();
$url->get("http://www.forum-invaders.com.br/vb/login.php");
$url->submit_form(
fields => {
vb_login_username => 'login',
vb_login_password => 'senha',
});
has 'msg' => (is => 'rw', isa => 'Str');
sub send_msg {
my $self = shift;
my $message = $self->msg;
my $content = $url->decoded_content;
$content =~ /SECURITYTOKEN = "(.*?)"/g ;
my $token = $1;
if($content =~ /Bem-vindo/gi) {
my $msg = uri_escape($message);
$url->post("http://www.forum-invaders.com.br/vb/vbshout.php",{
message => $msg, securitytoken => $token,
do => "ajax", action => "save", instanceid => "2"});
}
}
sub get_msg{
my $r = $url->get("http://www.forum-invaders.com.br/vb/vbshout.php?type=activeusers&do=ajax&action=fetch&instanceid=2");
my $json = JSON->new->relaxed;
my $s = $json->decode($r->decoded_content);
my $msg = $s->{"shouts"}->{0}->{"message_raw"};
my $user = $s->{"shouts"}->{0}->{"musername"};
my $name;
if ($user =~ />(.+)<\/span/gi) {$name = $1;}
else {$name = $user}
my $now = join(" => ", $name, $msg) . "\n";
return $now;
}
no Moose;
1;
Soon I received an advice to use the BUILD method, so I did so but did not work.
package Shoutbox;
use common::sense;
use WWW::Mechanize;
use WWW::Mechanize::DecodedContent;
use JSON -support_by_pp;
use URI::Escape;
use Moose;
has 'login' => (is => 'rw', isa => 'Str');
has 'password' => (is => 'rw', isa => 'Str');
our $url;
our $token;
sub BUILD{
my $self = shift;
$url = WWW::Mechanize->new();
$url->get("http://www.forum-invaders.com.br/vb/login.php");
$url->submit_form(
fields => {
vb_login_username => $self->login,
vb_login_password => $self->password,
});
my $content = $url->decoded_content;
$content =~ /SECURITYTOKEN = "(.*)"/g;
if ($1 eq "guest"){
print "Login Error\n";
exit;
}
else (print "Login OK!\n";}
$token = $1;
print $token . "\n";
}
has 'msg' => (is => 'rw', isa => 'Str');
sub send_msg {
BUILD;
my $self = shift;
my $message = $self->msg;
my $msg = uri_escape($message);
$url->post("http://www.forum-invaders.com.br/vb/vbshout.php",{
message => $msg, securitytoken => $token,
do => "ajax", action => "save", instanceid => "2"});
}
sub get_msg{
BUILD;
my $r = $url->get("http://www.forum-invaders.com.br/vb/vbshout.php?type=activeusers&do=ajax&action=fetch&instanceid=2");
my $json = JSON->new->relaxed;
my $s = $json->decode($r->decoded_content);
my $msg = $s->{"shouts"}->{0}->{"message_raw"};
my $user = $s->{"shouts"}->{0}->{"musername"};
my $name;
if ($user =~ />(.+)<\/span/gi) {$name = $1;}
else {$name = $user}
my $now = join(" => ", $name, $msg) . "\n";
return $now;
exit;
}
no Moose;
1;

Perl WWW::Mechanize JSESSION issue

I am having a problem getting/staying logged in with perl mechanize to a website
Looking at the headers, it appears that the JSESSIONID keeps changing. I am using a cookie jar, but I think it's getting overwritten somehow.
#!/usr/bin/perl
use strict;
use warnings;
use WWW::Mechanize;
use HTTP::Cookies;
use Crypt::SSLeay;
use LWP::UserAgent;
use Crypt::SSLeay::CTX;
use Crypt::SSLeay::Conn;
use Crypt::SSLeay::X509;
use LWP::Simple qw(get);
use LWP::Debug;
my $cookie_jar = HTTP::Cookies->new(ignore_discard => 1);
my $agent = WWW::Mechanize->new(cookie_jar => $cookie_jar, noproxy=>0);
$agent->agent_alias('Linux Mozilla');
$ENV{HTTPS_CA_DIR} = 'cert/';
my $user = 'xxxx';
my $pass = 'xxxx';
my $url = '';
print "\n\n=========================================================\nGOING TO LOGIN PAGE:\n";
my $res = $agent->get($url);
for my $key ( $res->header_field_names() ) {
print $key, " : ", $res->header( $key ), "\n";
}
print "cookie: ".$agent->cookie_jar->as_string();
$agent->form_name('loginForm');
$agent->set_fields(
userId => $user,
password => $pass
);
$agent->submit();
print "\n\n=========================================================\nREDIRECT:\n";
my $res = $agent->submit();
for my $key ( $res->header_field_names() ) {
print $key, " : ", $res->header( $key ), "\n";
}
print "cookie: ".$agent->cookie_jar->as_string();
my $cUrl = '';
$cookie_jar->revert;
print "\n\n=========================================================\nGOING TO CAMPAIGN PAGE:\n";
my $res = $agent->get($cUrl);
for my $key ( $res->header_field_names() ) {
print $key, " : ", $res->header( $key ), "\n";
}
print "cookie: ".$agent->cookie_jar->as_string();
I am not sure why this worked, but I was able to resolve this by utilizing LWP::ConnCache
$agent->conn_cache(LWP::ConnCache->new());