PHP 执行服务器命令的类

为了方便管理服务,我定义了请多命令的别名,但是还是没有图形界面操作方便呀,于是想到PHP可以执行系统命令,就封装了一个简单的类。说实话,我做程序这么多年,也没啥大的追求,就只是喜欢写一些提高效率工具代码,因为我懒,哈哈。

先看一下与之相关的几个函数,说实话,真的醉了,官方有必要搞这么多函数么。。

exec( string $command[, array &$output[, int &$status]] ) : string
执行外部程序,有状态,保存结果,返回最后一行

passthru( string $command[, int &$status] ) : void
执行外部程序,有状态,输出结果

shell_exec( string $cmd) : string
shell 环境执行命令,原样返回结果

system( string $command[, int &$status] ) : string
执行外部程序,有状态,输出结果,返回最后一行


总结:exec 完美,shell_exec 简单。system 与 passthru 差不多,都会输出结果,只是 passthru 没的返回。

看下效果图

 1 <?php
 2 
 3 p(work::sudo('root')->stop('apachectl'));
 4 p(work::sudo('root')->service('mysql')->start());
 5 
 6 
 7 class work {
 8 
 9     public $password = '';
10     public $program = '';
11 
12     public $command = '';
13     public $output = '';
14     public $status = 0;
15 
16 
17     public function __construct($password = null){
18 
19         $this->password = $password;
20     }
21 
22     public static function sudo($password = null){
23 
24         return new static($password);
25     }
26 
27     public function exec($command = null){
28 
29         if(empty($command)) throw new Exception('命令为空!');
30 
31         $this->command = empty($this->password)? $command : 'echo "'. $this->password .'" | sudo -S ' . $command;
32 
33         exec($this->command, $this->output, $this->status);
34 
35     }
36 
37     public function service($program){
38 
39         if(empty($program)) throw new Exception('服务为空!');
40         $this->program = 'service ' . $program;
41         return $this;
42     }
43 
44     public function start($program = null){
45 
46         if(!is_null($program)){
47             $this->program = $program;
48         }
49 
50         $this->exec($this->program . ' start');
51         return $this;
52     }
53 
54     public function stop($program = null){
55 
56         if(!is_null($program)){
57             $this->program = $program;
58         }
59 
60         $this->exec($this->program . ' stop');
61         return $this;
62 
63     }
64 
65     public function restart($program = null){
66 
67         if(!is_null($program)){
68             $this->program = $program;
69         }
70 
71         $this->exec($this->program . ' restart');
72         return $this;
73 
74     }
75 
76 
77 }
原文地址:https://www.cnblogs.com/zbseoag/p/12729824.html