34. Perl 脚本实战-rscpup

    xiaoxiao2022-07-05  140

    rscpdown 用于免交互从远程服务器上下载文件, 不能下载多个文件。 命令使用说明:

    命令依赖expect 环境命令携带用户名和密码, 无须交互文件名支持通配符方式批量下载多个文件命令只能下载文件, 不能下载目录命令最多只能包含5个参数, 不支持多个目标文件参数

    1. 用法示例

    1.1 查询单个进程

    $ rscpdown 127.0.0.1 zongf 123456 . /etc/group group

    1.2 查询多个关键字

    $ rscpdown 127.0.0.1 zongf 123456 . /etc/pass* /usr/bin/expect passwd 100% 2488 4.5MB/s 00:00 ETA

    2. 命令源码

    #!/usr/bin/perl #Desc: 从远程服务器批量下载文件. 此脚本依赖于expect 环境, 请先安装expect环境 #Args: 远程服务器ip, 用户名, 密码, 本地文件夹, 远程文件名列表, [expect 命令绝对路径] #Auth: zonggf #Date: 2017-07-11 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 "./rscpdown root root . /tmp/hello*.txt ." \"\n\t\b\b./rscpdown root root . /tmp/hello*.txt /usr/bin/expect\n"; print BOLD BLUE "Auth: "; print "zonggf\n"; print BOLD BLUE "Date: "; print "2017-07-11\n"; exit; } #判断传入参数个数 if(@ARGV < 5){ print "[error] the param cannot less 5\n"; exit; }elsif(@ARGV > 5){ $expect = pop @ARGV; } } #################### 主程序 #################### #校验帮助 &check_help; #设置默认命令 $expect = "expect"; #获取脚本传入的ip, 用户名, 密码 ($ip, $user, $password, $local_dir, $remote_files) = @ARGV; #拼接expect命令 $cmd = "$expect -c 'spawn scp $user\@$ip:$remote_files $local_dir \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); } } #处理返回结果 unless($#results == 0 && $results[0] =~ /cannot access/){ for my $el (@results){ unless($el =~ /^\s*$|:$/){ print "$el\n"; } } }
    最新回复(0)