Tuesday, 29 January 2013

How To Run A Command On A Remote Unix Machine From Windows

I recently had to create a script under Windows that could kick off a task under Unix. The user of the Windows machine had no knowledge of Unix so I wanted a script or application that I could put on the desktop of the windows machine, that the user could just double click to execute.

I decided to use Strawberry Perl (http://strawberryperl.com/) to execute a script under Windows. After installing Strawberry Perl I installed the perl module Net::SSH2 using the command :
$cpan Net::SSH2
Then I executed the following script :


#!/usr/local/bin/perl

#use strict;
#use warnings;
#use 5.010;  #if you are using version 5.10 or higher

use Net::SSH2;

my $host = "ipaddress";
my $user_id = "username";
my $password = "password";

my ($len, $buf); # Buffer for reading SSH2 output

my $ssh2 = Net::SSH2->new();
$ssh2->connect($host) or die "Unable to connect $host $@ \n";
$ssh2->auth_password($user_id,$password) or die "Unable to login $@ \n";
my $chan = $ssh2->channel();

#Initialize and execute Unix command remotely
$linuxCommand = "ls > output.tmp";
$chan->exec($linuxCommand) or die "Unable to execute the command $@ \n";

sleep (5);


In order to use this script in your application all you need to do is cut and paste the code above into an empty file with the extension .pl (e.g. remoteCommand.pl). Having done this, modify these lines :
my $host = "ipaddress";
my $user_id = "username";
my $password = "password";
(Do not remove the quotation marks)
Then modify this line to change the commande to execute on the remote machine :
$linuxCommand = "ls > output.tmp";
(Put your command between the quotation marks).

Now all you need to do is double click the Perl file and it will execute the command on the remote machine.

Finally, if you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

No comments:

Post a Comment