1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| my %DataSSH = (
host => "IP serveur ou Host serveur",
login => "login",
password => "xxxxxx",
cmd => ["perl /home/toto/test.pl", "ls /usr"],
verbose => 1, # ou 0
);
CommandSSH( \%DataSSH);
#==================================================================
# But : Connection SSH + commandes
# Args :
# Retourne : rien
# Besoin : modules Net::SSH2 sous win
# Net::SSH::Perl sous linux
#=================================================================
sub CommandSSH {
unless( scalar(@_) == 1) {
my $usage = <<'FIN_USAGE';
Usage:
my %DataSSH = (
host => "IP serveur ou Host serveur",
login => "login",
password => "xxxxxx",
cmd => ["perl /home/toto/test.pl", "ls /usr"],
verbose => 1, # ou 0
);
CommandSSH( \%DataSSH);
FIN_USAGE
die($usage);
}
my ( $RefDataConnection ) = @_;
# parameters
my ($host, $login, $password, $Refcmd, $Verbose) = (
$RefDataConnection->{host},
$RefDataConnection->{login},
$RefDataConnection->{password},
$RefDataConnection->{cmd},
$RefDataConnection->{verbose},
);
my $OS = $^O;
if ( defined $Verbose and $Verbose == 1 ) {
$Verbose = 1;
}
else {
$Verbose = 0;
}
# Linux
if ( $OS eq "linux" ) {
# A faire
}
# Windows
elsif ( $OS =~ /^mswin32$/i ) {
require Net::SSH2;
my $ssh2 = Net::SSH2->new();
$ssh2->connect($host);
my ( $code, $error_name, $error_string ) = $ssh2->error();
if ( $code ) {
print "[WARNING] Unable to connect to host : $host\n\n";
return;
}
unless ( $ssh2->auth_password($login, $password) ) {
$ssh2->disconnect();
print "[WARNING] Unable to login.\nCheck your login ($login) or your password\n\n";
return;
}
foreach my $cmd ( @{$Refcmd} ) {
if ( $Verbose == 1 ) {
print " - $cmd\n";
}
my $channel = $ssh2->channel();
$channel->blocking(1);
$channel->exec($cmd);
while( $channel->read(my $buffer, 1024) ) {
if ( $Verbose == 1 ) {
print $buffer;
}
}
$channel->close;
}
}
return;
} |
Partager