32. Perl 脚本实战-rssh

    xiaoxiao2022-07-04  145

    rssh 用于向远程服务器发送一条linux 命令,并捕获命令结果. 免交互.

    1. 用法示例

    当系统环境变量中有expect 时, 可以直接执行rssh 命令, 如果采用源码安装的expect,且expect没有添加到环境变量中,那么可指定expect所在路径

    1.1 使用系统默认expect 环境

    $ ./rssh 127.0.0.1 zongf 123456 'ls /home/zongf' Desktop Documents Downloads Music Pictures Public Videos

    1.2 自定义expect 命令路径

    $ ./rssh 127.0.0.1 zongf 123456 'ls /home/zongf' /usr/bin/expect Desktop Documents Downloads Music Pictures Public Videos

    2. 命令源码

    #!/usr/bin/perl #Desc 向远程服务器发送一条命令, 返回命令执行的结果. 此脚本依赖于expect 环境, 请先安装expect环境 #Args: 远程服务器ip, 用户名, 密码, 命令, [expect 命令绝对路径] #Auth: zonggf #Date: 2017-07-11 use warnings; use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; #检查是否是查询帮助 sub check_help{ my $param = $ARGV[0]; if("-h" eq $param || "--help" eq $param){ print BOLD BLUE "Desc: "; print "向远处服务器发送一条命令,返回命令执行的结果.此脚本依赖expect 环境, 需要先安装expect\n"; print BOLD BLUE "Args: "; print "参数列表: 远处ip, 远处用户名, 远处密码, 需要执行的命令, [expect 命令绝对路径]\n"; print BOLD BLUE "Exam: "; print "./rssh root root \"ls /tmp \"\n\t\b\b./rssh root root \"ls /tmp\" /usr/bin/expect\n"; print BOLD BLUE "Auth: "; print "zonggf\n"; print BOLD BLUE "Date: "; print "2017-07-11\n"; exit; } #判断传入参数个数 if(@ARGV < 4){ print "[error] the param cannot less 4\n"; exit; }elsif(@ARGV > 4){ $expect = pop @ARGV; } } #################### 主程序 #################### #校验帮助 &check_help; #设置默认命令 $expect = "expect"; #获取脚本传入的ip, 用户名, 密码 ($ip, $user, $password, $cmd) = @ARGV; #拼接命令 $cmd = "$expect -c 'spawn ssh $user\@$ip \"$cmd\" \n" ."expect {\n" .'"*yes/no*" { send "yes\r"; exp_continue }' . "\n" ."\"*password:*\" { send \"$password\\r\" } \n" ."}\n" ."interact\n" ."exit\n" ."'"; # 执行命令 @files = `$cmd`; # 处理返回结果 $flag = 0; for my $el (@files){ if( $el =~ /password:/ ){ $flag = 1; }elsif ($flag == 1){ #返回换行符为crlf, 即/r/n $el =~ s/\r\n/\n/g; #去除两侧空格 $el =~ s/^\s+|\s+$//g; push (@results, $el); } } #输出返回结果 print "$_\n" foreach @results;
    最新回复(0)