在 php 中运行 shell 脚本并打开 shell 文件
php 允许我们使用 shell_exec();
处理 shell 文件的函数。然而,如果你的操作系统是 windows,你应该考虑使用 popen()
和 pclose()
函数,因为管道是在文本模式下执行的,这通常会阻止它的二进制输出。
我们将在我们的 shell.php
文件中实现两个脚本。首先,我们将使用 shell_exec();
打开 .sh
文件功能。
然后,我们将使用 shell_exec()
打开 cmd 界面并运行一些 windows 命令。
使用 shell_exec()
在文本模式下运行 shell 文件
函数语法和参数:shell_exec(string $cmd);
。此函数以字符串格式返回 shell 输出。
我们在本教程中创建了一个演示 demo.sh
文件。
代码(demo.sh
):
#!/bin/sh
echo "hello world";
echo "this is a shell .sh file for demo";
// your shell commands go here
你可以使用任何文本编辑器创建一个 .sh
文件并使用 .sh
文件扩展名保存它。之后,请运行以下 php 脚本(shell.php
)在记事本中打开它,因为它会在文本模式下抛出字符串格式。
<head>
<title>
run shell file in php and open cli (shell) to run shell scripts
title>
head>
head>
<form action="shell.php" method ="post" align="center">
<input type="submit" value="open .sh file using shell_exec() in php" name="openshellfile" />
<input type="submit" value="run cmd/shell on windows using shell_exec() in php" name="opencmd" />
form>
body>
html>
php
// when user submits the form
if(isset($_post['openshellfile'])){
echo $res=shell_exec('path to the file/demo.sh');
}
?>
输出:
在 cli 中使用 shell_exec()
返回二进制格式
shell_exec()
函数可用于多种功能。我们的方法是使用 shell_exec()
的绝佳方式,无需在后台运行函数。
你也不需要使用 popen()
或 pclose()
。
php
// ping facebook cmd (shell)
// open cmd shell
if (isset($_post['opencmd']))
{
//you do not need to use popen() or pclose() either to run this shell command
// you can add any command here, it will work!
//for example, you can control your windows (cli)
//you will only change the command after cmd.ex /k "your command"
$open = shell_exec('start cmd.exe /k ping "facebook.com"');
echo $open;
//function shell($open) {
//check your php version
}
?>
虽然我们可以使用我们的脚本运行任何命令,但我们只 ping 了 facebook.com
。例如,如果你想通过此功能打开一个计算器,请输入 calc
而不是 ping "facebook.com"
。
在你的 php 脚本中添加上述代码之前,你首先需要更改 html 中输入字段的名称。然后将上面的代码添加到我们之前运行的 shell.php
文件中。
命令的范围可以是任何东西,你可以键入任何 windows 命令并将其分配给 $open
变量。该脚本会将你的命令直接运行到 windows shell(本示例中为 cli)。
输出:
我们使用 shell_exec();
执行了一个 cmd 命令来 ping facebook.com
在上面的代码中。但是,你可以在函数参数中键入任何命令,它将起作用。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
如何在 php 中获取时间差的分钟数
发布时间:2023/03/29 浏览次数:204 分类:php
-
本文介绍了如何在 php 中获取时间差的分钟数,包括 date_diff()函数和数学公式。它包括 date_diff()函数和数学公式。
发布时间:2023/03/29 浏览次数:156 分类:php
-
本教程演示了如何将用户从页面重定向到 php 中的其他页面