cbrunner9
cbrunner9

Reputation: 23

Putty command from Perl

I am trying to run a couple of commands in putty from perl. Right now my code gets me into putty but I am unsure of how to execute commands from there.

my $PUTTY = 'C:\Users\Desktop\putty.exe';
my $dacPutty = "$PUTTY, -ssh username@server - l username -pw password";
system ($dacPutty);

system (ls);

Upvotes: 2

Views: 3058

Answers (2)

slim
slim

Reputation: 41261

Usually in Perl it's better to use a Perl module, where one exists, than to shell out.

Using a module is more portable, and often gives you more control. system introduces many opportunities for security bugs, so it's good to avoid it where possible.

In this case, use Net::SSH::Perl http://search.cpan.org/~turnstep/Net-SSH-Perl-1.38/lib/Net/SSH/Perl.pm

Once installed:

use Net::SSH::Perl;
my $ssh = Net::SSH::Perl->new("host1");
$ssh->login("user1", "pass1");

$ssh->cmd("cd /some/dir");
$ssh->cmd("foo");

For reliability, you should actually check the result of each cmd:

my ($stdout, $stderr, $exit) = $ssh->cmd("cd /some/dir");
unless ($exit == 0) {
     // Handle failed cd
}

The document notes that with SSH-1, each cmd reconnects, so the above would not work -- you would cd in one shell, then foo in a completely new shell. If you have to use SSH-1, then you'd need to do:

$ssh->cmd("cd /some/dir; foo");

(And you can use a similar trick even if you're making a system call to plink)

Upvotes: 1

michael501
michael501

Reputation: 1482

use plink instead. ( http://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter7.html ) plink is in the same directory as putty.

Upvotes: 3

Related Questions