How Can I Run a Command on a Remote Machine with Perl?

How Can I Run a Command on a Remote Machine with Perl?

I'm using following code to connect to a remote machine and try to execute one simple command on remote machine.

#!/usr/bin/perl
#use strict;
use warnings;
use Net::Telnet;

$telnet = new Net::Telnet ( Timeout=>2, Errmode=>'die');
$telnet->open('172.168.12.58');
$telnet->waitfor('/login:\s*/');
$telnet->print('admin');
$telnet->waitfor('/password:\s*/');
$telnet->print('Blue');

#$telnet->cmd('ver > C:\\log.txt');
$telnet->cmd('mkdir gy');

But when I'm executing this script it is throwing error messages

[root@localhost]# perl tt.pl
command timed-out at tt.pl line 12
1

2 Answers

From your code it seems that you have *nix. Use of perl module Net::SSH::Perl make it more easy

Sample Code:

#!/usr/bin/perl -w
use strict;
use Net::SSH::Perl
my $cmd = 'command';
my $ssh = Net::SSH::Perl->new("hostname", debug=>0);
$ssh->login("username","password");
my ($stdout,$stderr,$exit) = $ssh->cmd("$cmd");
print $stdout;

And sample code for Net::Telnet

use Net::Telnet ();
    my $t = new Net::Telnet (Timeout => 10,
                          Prompt => '/bash\$ $/');
    $t->open("sparky");
    $t->login($username, $passwd);
    my @lines = $t->cmd("who");
    print @lines;

You can look at more example for Net Telnet Examples

You might need to provide a "prompt" constructor parameter - see this thread

The example they gave:

my $telnet = new Net::Telnet (
    Timeout=>10, 
    Prompt=>'/Bilbo>$/i',   #### <<<==============
    Errmode=>'die', 
    Dump_Log=>'dump.txt', 
    Input_log=>'input.txt', 
    Output_log=>'output.txt', 
); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.