Reply
Member
Posts: 152
Registered: ‎08-19-2009
Kudos: 28

Automate CLI commands in Perl via HTTP(s)

I've been wanting to automate tasks via Perl and have found the SSH pretty slow (20 seconds to run 'uname' over ssh...), so I wrote a Perl library to use the HTTPS interface (1.7 seconds) or HTTP (.7 seconds).

Example script:

#!/usr/bin/perl

require('LWP-to-ubnt.ph');
my $response = &doUbntHTTP('10.255.255.250', 'MySekret', 'uname -a', 'https');
print $response, "\n";


The library that does the LWP stuff...

#### perl header file ####
# LWP-to-ubnt.ph
#
# Use the HTTP interface to run CLI on ubiquiti antennas.
# Tue Jan 11 00:33:50 PST 2011, rudy
#
# EXAMPLE in 2 lines of Perl
# require('LWP-to-ubnt.ph');
# print &doUbntHTTP('10.255.255.250', 'MySekret', 'uname -a', 'https');
#
# Benchmark of running 'uname' over various protocols:
# HTTP time: 0:00.71
# HTTPS time: 0:01.67
# SSH time: 0:19.72

# Found out about the admin.cgi from here: http://www.ubnt.com/forum/showthread.php?t=21962

use strict;
use HTTP::Request::Common;
use HTTP::Cookies;
use LWP::UserAgent;
our $DEBUG = undef; # set to 1 if you want cookie info

sub doUbntHTTP {
my ($ip, $pass, $cmd, $proto) = @_;
$proto ||= 'http';
my $cookie_jar = HTTP::Cookies->new();
$cookie_jar->clear;
$ENV{HTTPS_VERSION} = 3;
my $action = GET "$proto://$ip/login.cgi";

my $ua = LWP::UserAgent->new;
$ua->cookie_jar($cookie_jar);
$ua->agent('Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.11pre) Gecko/20100928 RudyScript/1.0 Firefox/3.6.11pre)');
$ua->timeout(15);

my $www = $ua->request( $action );
print "Initial Cookies: ". $cookie_jar->as_string ."\n" if $DEBUG;

$action = POST "$proto://$ip/login.cgi",
Content_Type => 'form-data',
Content => ;

$www = $ua->request( $action );
print "Logged On Cookies: ". $cookie_jar->as_string ."\n" if $DEBUG;
print $www->content;

$action = POST "$proto://$ip/admin.cgi",
Content_Type => 'form-data',
Content => ;
$www = $ua->request( $action );
print "\n\nCookies: ". $cookie_jar->as_string ."\n" if $DEBUG;
print $www->content if $DEBUG;
$www->content =~ /.*
\s+(.*?)\s+<\/pre>.*/s;
return $1;
}

1;
Reply