学习模块的最快方法就是学习实例,下面介绍Perl的Net::OpenSSH模块的使用实例,详细的说明可以参考CPAN上的介绍。
本机通过key登陆远程服务器,所以要先安装openssh,关于使用ssh公私密钥可以参考man手册。
1、连接一台远程服务器并执行命令或者脚本
#!/usr/bin/perl -w
use strict;
use Net::OpenSSH;
my $hostname = 'puppet.ygfs.com'; my $ssh = Net::OpenSSH->new( $hostname, user => 'root' );
my $cmd = 'ls -l /';
my $svn_cmd = 'bash /data/ygfs_ctrl/db_convert.sh'; #这里是在远程执行一个bash shell脚本
open LOG,">> perl_exec.log"; #记录执行日志
select LOG;
my @out = $ssh->capture( $cmd );
print "@out";
my @db_out = $ssh->capture( $svn_cmd );
print "@db_out";
close LOG;
select STDIN;
2、连接多台远程服务器,并执行命令或者脚本
#!/usr/bin/perl -w
use strict;
use Net::OpenSSH;
my @hostname = qw( #建立一个服务器列表
puppet1.ygfs.com
puppet2.ygfs.com
);
my $cmd1 = 'ls -l';
my $cmd2 = 'df -i';
for my $host ( @hostname ) {
my $ssh = Net::OpenSSH -> new( $host, timeout => 600 );
my @out = $ssh -> capture( $cmd1 );
my @space = $ssh -> capture( $cmd2 );
print @out;
print @space;
}
print "@hostname\n";
3、从参数列表读取要连接的远程服务器和要执行的命令
#!/usr/bin/perl -w
use strict;
use Net::OpenSSH;
my $hostname = $ARGV[0 || 'puppet.ygfs.com';
my $remote_cmd = $ARGV[1 || 'hostname && uname -p';
my $ssh = Net::OpenSSH -> new( $hostname );
my @exec_log = $ssh -> capture( $remote_cmd );
print @exec_log;
4、使用管道
#!/usr/bin/perl -w
use strict;
use Net::OpenSSH;
my $hostname = $ARGV[0 || '127.0.0.1';
my $ssh = Net::OpenSSH -> new( $hostname );
my @lists = $ssh -> capture( 'ls' );
print @lists;
my @lists_format = $ssh -> capture2( 'ls -hl' );
print @lists_format;
#通过pipe_out方法获取远程主机上指定文件的内容,保存到$rout句柄,并打印输出,这里可以不使用pid变量
my ( $rout,$pid ) = $ssh -> pipe_out( "cat install.log" )
#my $rout = $ssh -> pipe_out( "cat install.log" )
or die "pipe_out method failed:".$ssh -> error;
while( <$rout> ) { print }
close $rout;
#写内容到远程服务器的指定文件
my $rin = $ssh -> pipe_in( "cat >> nginx.conf" )
or die "pipe_in method failed:".$ssh -> error;
print $rin <<EOF;
server{
listen 8088;
root /data/private_web;
index index.html;
server_name private.yuanfang.com;
auto_index on;
access_log /dev/null;
error_log /dev/null;
}
EOF
close $rin;
这里只是简单的介绍了Net::OpenSSH模块怎么使用,它还有很多方法和参数,读者可以参考手册。
从上面的例子可以看到,这个模块不是并发连接到远程主机和执行命令的,所以对于要连接的对象很多的时候,耗时很长,效率很低,所以就有了Net::OpenSSH: arallel模块,支持指定工作进程数和并发数量。下篇博文将会介绍。
|