PHP执行shell脚本或者Bash脚本文件实例。

systemexec函数可能被配置文件禁用,可以通过修改php配置文件删除被禁用的函数。

1.通过system函数执行

使用实例:

<?php
$shell = "dig www.afengblog.com";
echo "<pre>";
system($shell, $status);
echo "</pre>";
//shell命令执行结果和执行返回的状态值的对应关系
$shell = "<font color='red'>$shell</font>";
if ($status) {
    echo "shell命令{$shell}执行失败";
} else {
    echo "shell命令{$shell}成功执行";
}
?>

运行结果:

2.批量执行Shell命令

为了方便管理,可以将所需执行的命令写入至sh文件,然后通过system执行即可。

sh文件以#!/bin/bash开头,指示命令解释器,需要执行的命令每行一个,以;结尾,内容结尾可不带换行,否则status获取的是换行执行的结果(即空),if判断为空值则会输出命令执行失败,但实际上结尾换行符以上的命令是实际执行成功的。

#!/bin/bash
dig www.afengblog.com;
dig afengblog.com;
dig cdn.afengblog.com;

可以将shell 值改为:bash dig.sh

dig.sh改为以上sh文件的相对或绝对路径

如下:

<?php
$shell = "bash dig.sh";
echo "<pre>";
system($shell, $status);
echo "</pre>";
//注意shell命令的执行结果和执行返回的状态值的对应关系
$shell = "<font color='red'>$shell</font>";
if ($status) {
    echo "shell命令{$shell}执行失败";
} else {
    echo "shell命令{$shell}成功执行";
}
?>

执行效果如下:

3.通过exec函数执行

shell执行的命令可以根据以上方法自行diy。

使用实例:

<?php
  $shell = "bash dig.sh";
  exec($shell, $result, $status);
  $shell = "<font color='red'>$shell</font>";
  echo "<pre>";
  if( $status ){
    echo "shell命令{$shell}执行失败";
  } else {
    echo "shell命令{$shell}成功执行, 结果如下<hr>";
    print_r( $result );
  }
  echo "</pre>";
?>

执行效果如下:

原文地址:https://www.afengblog.com/php-executes-shell-script-or-bash-script.html

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/afengblogs/p/16838069.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程