如何使用Perl在远程计算机上运行命令?

1 perl

我正在使用以下代码连接到远程计算机并尝试在远程计算机上执行一个简单的命令.

#!/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');
Run Code Online (Sandbox Code Playgroud)

但是当我执行这个脚本时,它会抛出错误消息

[root@localhost]# perl tt.pl
command timed-out at tt.pl line 12
Run Code Online (Sandbox Code Playgroud)

Spa*_*ace 5

你的代码似乎有*nix.使用perl模块Net :: SSH :: Perl使它更容易

示例代码:

#!/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;
Run Code Online (Sandbox Code Playgroud)

以及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;
Run Code Online (Sandbox Code Playgroud)

您可以查看Net Telnet示例的更多示例