Posts

Showing posts with the label Perl

Fix error "Invalid data set: 0" in Perl module GD::Graph

Image
Error Message: Invalid data set: 0 at D:\New\TOOL\graph.pl line 24. Problem Code: my @a1 ; my @a2 = [-9,8,0,1,-2,-5,6,-4,3,7]; foreach my $i (1..10) {     push @a1 , $i; } my @data = (     @a1 ,     @a2 ); Solution: my @a1 ; my @a2 = [-9,8,0,1,-2,-5,6,-4,3,7]; foreach my $i (1..10) {     push @a1 , $i; } my @data = (     [@a1],     @a2 );

Fix error "Not a valid source data structure" in Perl module GD::Graph

Image
Error Message: Not a valid source data structure at D:\New\TOOL\graph.pl line 24. Problem Code: my $gd = $graph->plot( @data ) or die $graph->error; Solution: my $gd = $graph->plot( \@data ) or die $graph->error; Complete working code: #!/usr/bin/env perl use strict; use warnings; use GD::Graph; use GD::Graph::bars;

Getting started with SQLite database in Perl

Image
SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. SQLite is the most widely deployed database in the world with more applications than we can count, including several high-profile projects. [ https://www.sqlite.org/about.html ] Following program demonstrates how to Create a new SQLite database, how to connect to a database with credentials, how to create a table, how to insert values and how to select values. #!/usr/bin/perl use DBI; use strict; use warnings; my $dsn = "DBI:SQLite:test.db"; my $userid = ""; my $password = ""; my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1, AutoCommit => 0})    or die $DBI::errstr; print "Opened database successfully\n";

Create HTML dashboard of Jenkins jobs status

Image
Perl script to fetch live jobs' status from Jenkins server and generate and display HTML dashboard from it. use strict; use warnings; use autodie; use REST::Client; use MIME::Base64; use JSON; my $api_proto = 'http';               #HTTP/HTTPS my $api_url = 'localhost';       #Server IP my $api_port = '8080';                #Port number my $api_user = 'admin';           #Jenkins account username my $api_pass = 'password';          #Jenkins account password my $client = REST::Client->new();    #Perl Rest Client Object $client->addHeader('Authorization', 'Basic '.encode_base64($api_user . ':' . $api_pass)); $client->GET($api_proto.'://'.$api_url.':'.$api_port.'/api/json?tree=jobs[name,color,url]'); my $html = ""; $html = $ht...

Build Jenkins Job Remotely | Fix: Error 403 No valid crumb was included in the request

Image
In case you are a newbie with Jenkins read through this article: http://com.puter.tips/2017/09/getting-up-and-running-with-jenkins.html Build Jenkins Job Remotely I have found two ways in which you can trigger a build on job remotely via scripting. Both methods are simple HTTP Get/Post requests, nothing fancy here. Along with these Requests we need to pass login credentials. Method 0: No protection enabled => This is the case when you are in a secure environment and have disabled all additional protection mechanism like CSRF (Method 1) and Authentication Token (Method 2). If this is the case then you can simply trigger a HTTP Request like this: 'http://username:password@jenkins_url:port/job/job_name/build' e.g. http://admin:pass@localhost:8080/job/job1/build

Jenkins: Trigger build remotely via script using Authentication Token

Image
Powershell: $acctname = "admin" $password = "password" $server = "localhost" $port = "8080" $jobName = "test02" $jobToken = "test02_authentication_token" $params = @{uri = "http://${server}:${port}/job/${jobName}/build?token=${jobToken}";             Method = 'Get';             Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${acctname}):$(${password})"));}} Invoke-RestMethod @params

Jenkins: Trigger build remotely via script using crumb

Image
Python: import requests api_proto = 'http' api_url = 'localhost' api_port = '8080' api_job = 'test01' api_user = 'admin' api_pass = 'password' api_crumb = requests.get(api_proto + '://' + api_user + ':' + api_pass + '@' + api_url + ':' + api_port + '/crumbIssuer/api/json') if api_crumb.status_code == 200 :     api_crumb = api_crumb.json()['crumb'] resp = requests.post(api_proto + '://' + api_url + ':' + api_port + '/job/' + api_job + '/build', auth=(api_user, api_pass), headers={"Jenkins-Crumb":api_crumb}) if resp.status_code == 201:     print(api_job + ' was triggered successfuly..')

Perl Subroutine Arguments

Image
Subroutines:- 1. Retrieving arguments to a subroutine with shift: A subroutine's arguments come in via the special @_ array. The shift without an argument defaults to @_ .     sub volume {         my $height = shift ;         my $width = shift ;         my $depth = shift ;         return $height * $width * $depth ;     }

Find difference between two text files in Perl

Image
#!/usr/bin/env perl use strict; use warnings; use Text::Diff; my $file1 = $ARGV[0]; my $file2 = $ARGV[1]; my $diffs = diff $file1,$file2; my @strings = split("\n",$diffs); foreach(@strings) {     print $_."\n"; } This Perl script compares two text files and prints their differences using the Text::Diff module. You pass the two file paths as arguments and it reports the changed lines, much like the Unix diff command. Doing this in code is useful inside larger pipelines, for example checking generated output against an expected baseline or flagging configuration drift between environments.

Create JSON from HTML in Perl

Image
Assumption: Your HTML file is not pretty-encoded i.e. all content is contained in a single line. Code: #!/usr/bin/perl use strict; use warnings; use utf8; use JSON; use autodie; open my $fh1, '<files.html' or die "Cannot open files.html: $!\n"; my $html = <$fh1>; $html =~ s/<html><head><title>JSON Viewer<\/title><\/head><body><table border="1"><thead><tr><th width="300">Keys<\/th><th width="500">Values<\/th><\/tr><\/thead><tbody>//g; $html =~ s/<\/tbody><\/table><\/body><\/html>//g; my @rows = split("<\/tr>", $html); my %data; foreach my $row (@rows) {     my @cols = split("<\/td>", $row);     my $key;         foreach my $col (@cols)     {         if (not $col =~ /<br\/>/)       ...

Create HTML from JSON in Perl

Image
#!/usr/bin/perl use strict; use warnings; use utf8; use JSON; use autodie; use HTML::TreeBuilder; my $string; {     local $/;     open my $fh1,"<files.json" or die "open failed <files.json>: $!\n";     $string = <$fh1>;     close $fh1 or die "close failed <files.json>: $!\n"; } # Parse JSON in PERL my $data = decode_json($string); # Initialize HTML my $html = "<html><head><title>JSON Viewer</title></head><body><table border=\"1\"><thead><tr><th width=\"300\">Keys</th><th width=\"500\">Values</th></tr></thead><tbody>"; # Update HTML foreach my $key (keys(%$data)) {     $html = $html."<tr><td>".$key."</td><td>";     my $values = $data->{$key};     foreach my $value (@{$values})     {  ...

Send email from Perl in Windows 10

Image
In this program I am using Gmail to send an email from Strawberry Perl on my Windows 10 system. You can install Perl from here: http://strawberryperl.com/ I installed latest Strawberry Perl 5.24.0.1 (64bit) msi and it works fine on Windows 10 Pro 1607. Next install few modules that are required to send email. Open start menu and type CPAN Client that was installed on your PC by Strawberry Perl. Open CPAN Client and type following commands to install: install Email::Send install Email::Send::Gmail install Email::Simple::Creator As we are using gmail for sending email you need to authenticate your account against gmail's smtp server with your gmail credentials and make sure you have enables POP and IMAP email forwarding on from gmail settings. Change your credentials in following program: