#!/usr/bin/perl
################################################################################
# poeOffOnSwitch.pl
#
# (c) s4c
#
# v2021-10-22
#
# get it running,install necessary perl libs:
# - open CPAN eshell: perl -MCPAN -eshell
# - run command in CPAN shell: install Net::SSH::Expect
#
# Changes
# -2020-10-22: version 1
#
################################################################################
use strict;
use Net::SSH::Expect;

my $timeout_login =3;
my $usage = "usage: poeOffOnSwitch.pl \"<switch-user;switch-pwd;switch-ip;switch-port>\"\n";
my $user='';
my $pwd='';
my $ip='';
my $port='';


if ($ARGV[0] eq ''){
print "$usage\n";
exit(1);
}else{
my $input=$ARGV[0];
#print "$input\n";
$input=~s/^\s*//;
$input=~s/\s*$//;
if ($input=~/^(.*);(.*);(.*);(.*)$/){
$user=$1;
$pwd=$2;
$ip=$3;
$port=$4;
}else{
print "$usage\n";
exit(1);
}
}



my $ts=`date '+%m-%d'`;
chomp($ts);

write2log("turn poe off -on for ip:$ip, port=$port.");
my ($ret,$retmsg)=setPoe($user,$pwd,$ip,$port);

if ($ret == 0){
write2log("Poe off / on for ip:$ip, port=$port success.");
}else{
write2log("Poe off / on for ip:$ip, port=$port failed.");
}


sub setPoe($$$$){
my $user=$_[0];
my $pwd=$_[1];
my $ip=$_[2];
my $port=$_[3];
my $type="procurve";

my $debug=0;

print "getConfig for: $user,$pwd,$ip,$port\n" if $debug;
my $ssh = Net::SSH::Expect->new ( host => $ip,
user => $user,
password=> $pwd,
raw_pty => 1,
no_terminal => 0,
timeout => $timeout_login,
ssh_option => '-o StrictHostKeyChecking=no'
);

my $login_output;
eval { $login_output = $ssh->login(); };

return(1,"Login has failed: $login_output") if($@);

my $out= $ssh->exec(" ");
#use enable mode when we don't see the # in the prompt
if( $out !~ /\>\s*\z|\#\s*/ ){
$ssh->close();
return(2,"Login has failed. No prompt as expected");
}

if ($type =~ /procurve/i){
my $paging= $ssh->exec("terminal length 1000"); #wo don't like prompts when showing the config
if ( $paging =~ /\s?%\s/ ){
$ssh->close();
return( 3, "Unable to set terminal to length 1000");
}

my $cmd=$ssh->exec("configure");
#write2log("cmd=$cmd.");
sleep(1);

$cmd=$ssh->exec("interface $port");
#write2log("cmd=$cmd.");
sleep(1);

write2log("poe off - port $port");
$cmd=$ssh->exec("no power-over-ethernet");
#write2log("cmd=$cmd.");
sleep(5);

write2log("poe on - port $port");
$cmd=$ssh->exec("power-over-ethernet");
#write2log("cmd=$cmd.");
sleep(5);


$ssh->close();
}else{
$ssh->close();
return (6, "unknown switch type");
}

return(0,'success');
}



sub error($){
print "Error: $_[0]\n";
exit;
}

sub write2log($){
my $dt = `date`;
chomp($dt);
print "$dt $_[0]\n";
}

computer2know :: thank you for your visit :: have a nice day :: © 2022