#!/usr/bin/perl # run shell commands remotely over an SSH connection use strict; use warnings ; use Net::SSH2 ; use constant HOST => "YOURHOST" ; use constant USER => "YOURLOGIN" ; use constant HOSTKEY => "Path to your known_hosts keys file" ; ## To enable the public key login, append your 'pub' key file to the ## authorized_keys file in ~/.ssh on the server use constant PUBLICKEY => "Path to your public key" ; use constant PRIVATEKEY => "path to your private key" ; # Set up the SSH connection my $ssh2 = Net::SSH2->new() ; $ssh2->connect(HOST) or $ssh2->die_with_error ; $ssh2->check_hostkey(tofu => HOSTKEY) or $ssh2->die_with_error ; $ssh2->auth_publickey(USER, PUBLICKEY, PRIVATEKEY) or $ssh2->die_with_error ; $ssh2->auth_ok() ; # Logged in -- now you can execute commands print docmd("cd bin; ls") ; $ssh2->disconnect() ; exit ; # do the command and return the output ## NB: you can only do one command on a channel so we get a channel ## do the command, collect the output and close the channel ## The command must be a fully "punctuated and escaped" shell command. sub docmd { my $chan = $ssh2->channel() or $ssh2->die_with_error ; $chan->exec("($_[0]) 2>&1") ; my $out = ""; while (!$chan->eof) { my $buffer = ""; if (not defined ($chan->read($buffer, 100))) { $ssh2->die_with_error() ; } $out .= $buffer ; } return $out ; }