RexCommandsRun 执行一个远程命令

RexCommandsRun   执行一个远程命令:


使用这个模块 你可以运行一个命令:

 task "ppm", group=>"myservers", sub {
   my $output = run "pwd;ls -l";
    say $output;
  
 };


[root@node01 Rex]# rex ppm
[2017-05-01 11:52:46] INFO - Running task ppm on 192.168.137.3
/root

导出的函数:

这个格式 会执行 $command  使用给定的参数$arguments. 

参数必须是一个数组引用,参数

run($command_description, command => $command, %options)


run($command_description, command => $command, %options)

此函数会执行给定的命令和返回输出,在标量上下文 它返回原始输出,

在一个列表上下文 他返回列表输出  命令的退出值是存在$?变量

 task "uptime", group=>"myservers", sub {
   say run "uptime";
   run "uptime", sub {
     my ($stdout, $stderr) = @_;
     my $server = Rex::get_current_connection()->{server};
     say "[$server] $stdout
";
   };
   print "---------------
";
   print $?;
   print "---------------
";

 };



[root@node01 Rex]# rex uptime
[2017-05-01 12:00:28] INFO - Running task uptime on 192.168.137.3
 03:02:48 up 2 days, 23:30,  2 users,  load average: 0.00, 0.00, 0.00
[192.168.137.3]  03:02:48 up 2 days, 23:30,  2 users,  load average: 0.00, 0.00, 0.00

---------------
0---------------
[2017-05-01 12:00:39] INFO - All tasks successful on all hosts





 task "uptime", group=>"myservers", sub {
   say run "uptime";
   run "xx", sub {
     my ($stdout, $stderr) = @_;
     my $server = Rex::get_current_connection()->{server};
     say "[$server] $stdout
";
   };
   print "---------------
";
   print $?;
   print "---------------
";

 };



[root@node01 Rex]# rex uptime
[2017-05-01 12:01:15] INFO - Running task uptime on 192.168.137.3
 03:03:35 up 2 days, 23:30,  2 users,  load average: 0.00, 0.00, 0.00
[192.168.137.3] 

---------------
127---------------
[2017-05-01 12:01:26] INFO - All tasks successful on all hosts


例子:


如果你要运行一个命令在指定的情况下, 你可以队列命令行 当你需要运行它时通知它

如果你要运行一个命令如果另外的命令成功或者失败,

你可以使用only_if或者unless 选项:

 task "ppm", group=>"myservers", sub {
 my $count=  run "ps -ef | grep -i mysql | wc -l";
 say $count;
  
 };

[root@node01 Rex]# rex ppm
[2017-05-01 12:15:19] INFO - Running task ppm on 192.168.137.3
4
[2017-05-01 12:15:30] INFO - All tasks successful on all hosts
[root@node01 Rex]# 

can_run($command)

这个函数检查如果一个命令行在一个path是可用的,你可以指定多个命令行,第一个找到的命令会被返回;

 task "uptime",group=>"myservers",  sub {
   if( my $cmd = can_run("xx", "uname -a") ) {
     say run $cmd;
   }
 };
[root@node01 Rex]# rex uptime
[2017-05-01 12:22:05] INFO - Running task uptime on 192.168.137.3
Linux
[2017-05-01 12:22:16] INFO - All tasks successful on all hosts
[root@node01 Rex]# 

原文地址:https://www.cnblogs.com/hzcya1995/p/13349735.html