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. 命令源码
 
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, $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){
      
      $el =~ s/\r\n/\n/g;
      
      $el =~ s/^\s+|\s+$//g;
      push 
(@results, $el);
   }
}
print "$_\n" foreach @results;