#!/usr/local/bin/perl
use CGI::Ajax;
use CGI qw(:standard);
use Net::LDAP;
use Expect;
use Switch;
$debug = 1;
sub debug { print STDERR "@_" if $debug; }
#$site_url = '/cgi-bin/add_printer.cgi';
$site_url = '/cgi-bin/ap.cgi';
$site_name = 'Add a new printer';
# Create the CGI object
my $query = new CGI;
$ajax_called = $query->param("fname");
$submit_called = $query->param("submit");
#######################################################################################################################################################
#
## User inputs
#
$printer_name = param('printer_name');
$printer_type = param('printer_type');
$printer_ip = param('printer_ip');
$user = param('user');
$password = param('password');
$chkbox_print1 = $query->param('chkbox_print1');
$chkbox_print2 = $query->param('chkbox_print2');
debug "Executing add_printer.cgi as $ENV{REMOTE_USER}\n";
#######################################################################################################################################################
#
## Process form if submitted; execute ajax as needed or simply display the form
#
if ( $submit_called ) {
my $form_is_valid = &validate_form();
if ( $form_is_valid ) {
debug "validated - now starting ajax for the first time\n";
&do_ajax();
exit 0;
} else {
debug "Form not validated - re-displaying\n";
my $error_message = '*** Please fill in all fields ***';
## the extra ,1 below is a flag which clears the password field
&display_form($error_message,1);
}
} elsif ( $ajax_called ) {
debug "Running ajax function: $ajax_called\n";
&do_ajax();
exit 0;
} else {
# Output the HTTP header for NON-Ajax operations
print $query->header();
&display_form();
}
exit 0;
#######################################################################################################################################################
#
## start of AJAX subs
#
#######################################################################################################################################################
sub do_ajax {
my $pjx = CGI::Ajax->new( 'spinner' => \&spinner, 'addprintertoserver' => \&addprintertoserver, 'addprintertoldap' => \&addprintertoldap);
print $pjx->build_html($query,\&Show_HTML);
}
sub spinner {
my($printer,$server) = @_;
debug "spinner - printer: $printer, server: $server\n";
return($server,qq~<img src="/images/small-arrow-sppiner.gif"> Adding $printer to $server...~);
}
sub Show_HTML {
my $html = '';
$html .= <<EOT;
<html>
<head><title>Eric's CGI::Ajax Example</title>
<script type="text/javascript" language="javascript">
var p = '$printer_name';
var t = '$printer_type';
var ip = '$printer_ip';
var u = '$user';
var pw = '$password';
var np5 = '$chkbox_print1';
var np6 = '$chkbox_print2';
loc = new Array('ldap_host', 'ldap_printer', 'print1', 'print2', 'info');
doit = function(){
document.getElementById('info').innerHTML = '<font face=arial size=3><strong>Please wait while the print system is being updated ...</strong>';
sendjob(0,loc[0],'');
}
function notifyuser(l,m) {
// alert('notifyuser - Location: ' + l + ', Message: ' + m);
document.getElementById(l).innerHTML = m;
}
function sendjob(s,l,r) {
// alert('sendjob - step: ' + s + ', Location: ' + l + ', Response: ' + r);
document.getElementById(l).innerHTML = r;
if (s < (fa.length - 1) ) {
spinner( ['args__' + p, 'args__' + loc[s] ], [notifyuser] );
}
fa[s](loc[s],s);
}
function addtoldap(loc,step){
// alert('made it to addtoLDAP js function- Step: ' + step + ', Location: ' + loc);
addprintertoldap(['args__' + p, 'args__' + t, 'args__' + ip, 'args__'+loc, 'args__' + step],[sendjob]);
}
function addtoserver(loc,step){
// alert('made it to addtoSERVER js function- Step: ' + step + ', Location: ' + loc);
addprintertoserver(['args__' + p, 'args__' + t, 'args__' + u, 'args__' + pw, 'args__' + np5, 'args__' + np6, 'args__'+loc,'args__' + step],[sendjob]);
}
function iamdone(){
document.getElementById('info').innerHTML = '<font face=arial size=3><strong>Print System Updates COMPLETED!</strong>';
return true;
}
fa = new Array(addtoldap, addtoldap, addtoserver, addtoserver, iamdone);
</script>
</head>
<BODY onLoad="doit();">
<br>
<hr>
<div id="info"></div>
<div id="ldap_host"></div>
<div id="ldap_printer"></div>
<div id="print1"></div>
<div id="print2"></div>
<hr>
</body>
</html>
EOT
return $html;
}
#######################################################################################################################################################
#
## start of PERL subs
#
#######################################################################################################################################################
sub skipmsg {
my($printer,$server,$type) = @_;
debug "skipmsg - printer: $printer, server: $server, type: $type\n";
return(qq~<img src="/images/info_small.gif"> Adding $printer to $type server $server... <b style="color:#0000ff">Skipped!</b>~);
}
sub errormsg {
my($printer,$server,$type) = @_;
return(qq~<img src="/images/error_small.gif"> Adding $printer to $type server $server... <b style="color:#ff0000">FAILED!</b>~);
}
sub successmsg {
my($printer,$server,$type) = @_;
return(qq~<img src="/images/info_small.gif"> Adding $printer to $type server $server... <b style="color:#00ff00">Success!</b>~);
}
sub addprintertoserver {
local($printer_name, $printer_type, $u, $pw, $print1, $print2, $function, $step) = @_;
debug "\n\naddprintertoserver - name: $printer_name, Type: $printer_type, user: $u, Function: $function, print1: $print1, print2: $print2, Step: $step\n";
debug "\n\n*** print1: $print1, print2: $print2, Function: $function, Value: $$function\n";
$step ++;
sleep 3;
return($step,$function,&skipmsg($printer_name,$function,'Print')) unless $$function;
debug "Passed skip test for $function\n";
### Construct printer info
#
my %db;
$db{'class'}{'prefix'} = '_1';
$db{'class'}{'desc'} = 'Printer Class';
$db{'hppi'}{'desc'} = 'HP Printer';
$db{'odcs'}{'desc'} = 'Optio Printer (Old)';
$db{'oeci'}{'desc'} = 'Optio Printer (New)';
$db{'netk'}{'desc'} = 'Solaris Network Printer';
$db{'toeci'}{'desc'} = 'Itcha Printer';
return($step,$function,&errormsg($printer_name,$function,'Print')) unless $db{$printer_type}{desc};
debug "Passed DESC test for $printer_type\n";
$print_information = &genprint($printer_name, $printer_type,$db{$printer_type}{prefix});
debug "Passed genprint ($print_information)\n";
## comment out below line when ready to test expect sequence
return($step,$function,&successmsg($printer_name,$function,'Print'));
### Execute expect to run commands as this user on remote host
#
my $exp = Expect->spawn("/bin/ssh -l $user $host")
or return($step,$function,&errormsg($printer_name,$function,'Print'));
# prevent the program's output from being shown on our STDOUT
$exp->log_stdout(0);
$exp->expect(10, -re => '[Pp]assword: ?');
$exp->send("$password\n");
$exp->expect(2, -re => '[$#>] ?');
$exp->send("/usr/local/bin/sudo -k\n");
$exp->send("/usr/local/bin/sudo /bin/echo $print_information >> /spool/printers.conf\n");
$exp->expect(10, -re => '[Pp]assword:?');
$exp->send("$password\n");
$exp->expect(2, -re => '[$#>] ?');
$exp->send("/usr/local/bin/sudo /spool/start_printers.pl -v -p $printer_name\n");
# if the program will terminate by itself, finish up with
#$exp->soft_close();
$exp->expect(4, -re => '[$#>] ?');
$exp->hard_close();
return($step,$function,&successmsg($printer_name,$function,'Print'));
}
sub genprint {
my($name,$type,$prefix) = @_;
return qq~$type $name$prefix /dev/$name~;
}
#
########################################################################################################################
#
sub validate_form {
my @EmptyFields = qw( printer_name printer_ip user password );
foreach $field (@EmptyFields) {
my $value = $query->param($field);
$emptyfields++ unless $value;
}
debug "Number of empty fields is $emptyfields\n";
my @EmptyChkFields = qw( chkbox_print1 chkbox_print2 );
foreach $chkfield (@EmptyChkFields) {
$chkfield = $query->param($chkfield);
if ($chkfield){
$checkedqty++;
}
}
debug "Number of checked fields is $checkedqty\n";
if ($emptyfields or not $checkedqty) {
## Re-display form
debug "Failed form validation\n";
return 0;
} else {
## Proceed to Ajax
debug "Passed validation\n";
return 1;
}
}
########################################################################################################################
sub display_form {
my($error_message,$pwflag) = @_;
undef $password if $pwflag;
my %checked;
$checked{np5} = 'checked' if $chkbox_print1;
$checked{np6} = 'checked' if $chkbox_print2;
my %selected;
my @selected = qw( hppi odcs oeci toeci netk class );
foreach $key (@selected) {
$selected{$key} = ($printer_type eq $key) ? 'selected' : '';
}
# Display the form
print <<"END_HTML";
<html>
<head><title>Add a Printer</title></head>
<body>
<body>
<h1><font face=arial size=4>Create a new printer.</font></h1>
<form action="$site_url" method="post">
<tr><td><font face=arial size=-1>Select a printer type....</font><br>
<select name="printer_type" size=1>
<option $selected{hppi} value="hppi">HP Printer (hppi)
<option $selected{odcs} value="odcs">Old Optio Printer (odcs)
<option $selected{oeci} value="oeci">New Optio Printer (oeci)
<option $selected{toeci} value="toeci">Itach Printer (toeci)
<option $selected{netk} value="netk">Raw Network Printer (netk)
<option $selected{class} value="class">Printer Class (class) Not-Working-yet
</select>
</td>
</tr><br><p>
<tr><td><font face=arial size=-1>Select a Print Server to deploy to:</font><br>
<table bgcolor="#11A12E" border="0"><TR><TD>
<font face=arial size=-1><strong>print1</strong>
<input type="checkbox" $checked{np5} Name="chkbox_print1">
<font face=arial size=-1><strong>print2</strong>
<input type="checkbox" $checked{np6} Name="chkbox_print2">
<font face=arial size=-1><strong>print1</strong>
<input type="checkbox" disabled Name="chkbox_print1">
<font face=arial size=-1><strong>print2</strong>
<input type="checkbox" disabled Name="chkbox_print2">
<font face=arial size=-1><strong>dpsprint1</strong>
<input type="checkbox" disabled Name="chkbox_dpsprint1">
</td></tr></table>
</td>
</tr><br>
<tr><td><font face=arial size=-1>Printer Name:</font><br>
<input type="text" name="printer_name" value="$printer_name" SIZE=30></TR><p>
<tr><td><font face=arial size=-1>Printer IP Addresss:</font><br>
<input type="text" size=15 name="printer_ip" value="$printer_ip"><p>
<tr><font face=verdana, sans-serif size=2><b>In order to cretae the printer please provide your credentials.</font></b><br><p>
<tr><td><font face=arial size=-1>User Name:</font><br>
<input type="text" name="user" value="$user" SIZE=15><br></tr>
<tr><td><font face=arial size=-1>Password:</font><br>
<input type="password" name="password" value="$password" SIZE=8></TR><p>
<tr><td colspan=2> </td></tr>
<TR>
<td><input type="submit" name="submit" value="Add Printer">
</td>
</tr>
<h2 style="color: #ff0000">$error_message</h2>
<hr>
<a target="main" style="text-decoration:none" href="http://www.devtech101.com/welcome.html">Main menu</a>
</form>
</body></html>
END_HTML
}
########################################################################################################################
sub addprintertoldap {
my($printer_name, $printer_type, $printer_ip, $function, $step) = @_;
debug "\n\naddprintertoldap - name: $printer_name, Type: $printer_type, IP: $printer_ip, Function: $function, Step: $step\n";
$step ++;
sleep 3;
if ( $function =~ "ldap_host" ) {
$base_string = q~ou=hosts,o=devtech101.com,dc=devtech101,dc=com~;
$filter_string = qq~cn=$printer_name~;
@attributes = qw( dn ipHostNumber cn );
}
if ( $function =~ "ldap_printer" ) {
$base_string = q~ou=printers,o=devtech101.com,dc=devtech101,dc=com~; ;
$filter_string = qq~printer-uri=$printer_name~;
@attributes = qw( dn printer-name );
}
$admindn = "uid=password_reset,o=devtech101.com,dc=devtech101,dc=com";
$adminpw = "password";
$ldapserverone = "ldapnyc3.devtech101.com";
$ldapservertwo = "ldapnyc4.devtech101.com";
debug "Phase 1\n";
unless ( $ldap =
Net::LDAP->new($ldapserverone,
port=>389,timeout=>5) )
{
$ldap = Net::LDAP->new($ldapservertwo,
port=>389,timeout=>20) or
warn "Can't connect to $ldapserverone or $ldapservertwo via LDAP: $@";
}
$mesg = $ldap->bind(dn => $admindn,password => $adminpw, version=>3);
$mesg = $ldap->search( # perform a search
base => "$base_string",
filter => "$filter_string",
attrs => [ @attributes ]
);
$mesg->code && warn $mesg->error;
debug "Phase 2\n";
@entries = $mesg->entries;
foreach $entry (@entries) {
$dn = $entry->dn;
$cn = $entry->get_value("cn");
$ipHostNumber = $entry->get_value("ipHostNumber");
$printername = $entry->get_value('printer-name');
}
debug "Phase 3\n";
#Define undifned varbles
$dn = "Not_Found" unless ($dn);
$printername = "Not Defined" unless ($printername);
$ipHostNumber = "Not Defined" unless ($ipHostNumber);
$cn = "Not Defined" unless ($cn);
if ( $function =~ "ldap_host" ) {
debug "Phase 4 - ldpahost\n";
if (("$cn" =~ "$printer_name") && ("$ipHostNumber" =~ "$printer_ip")) {
#print "No need to do any thing as IP is the same\n","-------------\n";
} elsif (("$cn" =~ "$printer_name") && ! ("$ipHostNumber" =~ "$printer_ip")) {
#print "Host OR IP is not the same removing host\n";
###$mesg = $ldap->delete($dn);
#print "Adding host\n","----------------\n";
#Update LDAP with new Host
###LdapHostUpdate();
} else {
#print "Host dose not exsist adding to ldap\n","-----------------\n";
#Update LDAP with new Host
###LdapHostUpdate();
}
}
if ( $function =~ "ldap_printer" ) {
debug "Phase 5 - ldapprinter\n";
if ( "$printername" =~ "$printer_name" ) {
#print "No need to do any thing as the printer exsist\n","-------------\n";
} else {
#print "adding printer as it dose not exsist\n","-------------\n";
#Update LDAP with new Printer
###LdapPrinterUpdate();
}
}
debug "Phase 6\n";
$mesg = $ldap->unbind; # take down session
if ( $mesg->code ) {
$errstr = $mesg->code;
#print "An error has ocuerd the error code is $errstr";
debug "step: $step,$function,'ldap failed'\n";
return($step,$function,&errormsg($printer_name,$function,'LDAP'));
} else {
debug "step: $step,$function,'ldap success'\n";
return($step,$function,&successmsg($printer_name,$function,'LDAP'));
}
}
sub LdapPrinterUpdate {
$mesg = $ldap->add("printer-uri=$printer_name,ou=printers,o=devtech101.com,dc=devtech101,dc=com",
attr => [ 'printer-uri' => $printer_name,
'sun-printer-kvp' => "printer-uri-supported=lpd\\://print.devtech101.com/printers/$printer_name#Solaris",
'printer-name' => $printer_name,
'sun-printer-bsdaddr' => "print,$printer_name,Solaris",
'objectclass' => [ 'top', 'printerService', 'printerAbstract', 'sunPrinter' ]
]
);
if ( $mesg->code ) {
$errstr = $mesg->code;
#print "An error has ocuerd the error code is $errstr\n";
} else {
}
}
sub LdapHostUpdate {
$mesg = $ldap->add("cn=$printer_name\+ipHostNumber=$printer_ip,ou=Hosts,o=devtech101.com,dc=devtech101,dc=com",
attr => [ 'cn' => $printer_name,
'ipHostNumber' => $printer_ip,
'objectclass' => [ 'top', 'ipHost', 'device' ]
]
);
$mesg->code;
if ( $mesg->code ) {
$errstr = $mesg->code;
#print "An error has ocuerd the error code is $errstr\n";
} else {
}
}
#
########################################################################################################################
#
## EOF
#