如何发送多个命令

时间:2011-12-12 22:58:15

标签: perl

我在Windows上运行此脚本。我需要帮助如何将辅助命令添加到当前仅在一个设备上工作的cisco设备。另外我如何在文件而不是屏幕上打印出结果。

#!\usr\bin\Perl\bin\perl
use warnings;
use strict;
use NET::SSH2;

my $host = "switchA"; # use the ip host to connect
my $user = "XXX"; # your account
my $pass = "XXXX"; # your password
my $ssh2 = Net::SSH2->new();
$ssh2->debug(0);
$ssh2->connect($host) or die "Unable to connect host $@ \n";
$ssh2->auth_password($user,$pass);

#shell use

my $chan = $ssh2->channel();

$chan->exec('sh int desc');
my $buflen = 3000;
my $buf1 = '0' x $buflen;
$chan->read($buf1, $buflen);
print "CMD1:\n", $buf1,"\n";

# run another command  still not working
$chan->exec('sh ver');
my $buflen2 = 3000;
my $buf2 = '0' x $buflen2;
$chan->read($buf2, $buflen2);
print "CMD2:\n", $buf2,"\n";

1 个答案:

答案 0 :(得分:1)

如果你问我认为你在问什么,只需在自己的线程中运行每个$chan->exec命令(警告:未经测试):

use warnings;
use strict;
use NET::SSH2;
use threads;
use threads::shared;

#We'll be making a Net::SSH2 object in each thread, 
#so these parameters will need to be shared between the threads.
my $host :shared = "switchA"; # use the ip host to connect
my $user :shared = "XXX"; # your account
my $pass :shared= "XXXX"; # your password

#NOTE:  The shell use (via $ssh2 and $chan) has been passed
#to the subroutines foo and bar.

#Create two threads,
#one which will perform the subroutine foo,
#and the other which will perform the subroutine bar.
my $thread1=threads->create(\&foo);
my $thread2=threads->create(\&bar);

#Wait for the threads to finish.
$thread1->join;
$thread2->join;

sub foo
{
    my $ssh2 = Net::SSH2->new();
    $ssh2->debug(0);
    $ssh2->connect($host) or die "Unable to connect host $@ \n";
    $ssh2->auth_password($user,$pass);

    my $chan = $ssh2->channel();

    $chan->exec('sh int desc');
    my $buflen = 3000;
    my $buf1 = '0' x $buflen;
    $chan->read($buf1, $buflen);

    open(my $write,">","/output/file/foo") or die $!;

    print $write "CMD1:\n", $buf1,"\n";

    close($write);
}

sub bar
{
    my $ssh2 = Net::SSH2->new();
    $ssh2->debug(0);
    $ssh2->connect($host) or die "Unable to connect host $@ \n";
    $ssh2->auth_password($user,$pass);

    my $chan = $ssh2->channel();
    $chan->exec('sh ver');
    my $buflen2 = 3000;
    my $buf2 = '0' x $buflen2;
    $chan->read($buf2, $buflen2);

    open(my $write,">","/output/file/bar") or die $!;

    print $write "CMD2:\n", $buf2,"\n";

    close($write);
}

请查看perldoc perlthrtut了解有关线程的更多信息。

编辑添加:上述方法的缺点是您启动了两个SSH连接(每个线程一个)而不是一个。通过在线程外部启动一个连接(并将$ssh2作为shared变量)然后使用信号量(甚至是lock),可以在此添加额外的复杂层确保远程终端不会被一个线程的命令混淆,试图踩到另一个线程的命令。