PHP&&执行shell命令&&控制服务器
如何通过PHP控制服务器呢?
第一种:使用PHP本身的功能实现
PHP提供了许多控制服务器的命令。缺点是需要保持PHP对文件具备执行权限。
文件删除
<?php
//采用utf-8的编码方式,否则输出的提示信息是乱码
header("Content-Type: text/html; charset=utf-8");
//定义一个删除服务器端录像文件的function,通过传入录像名称,删除默认路径下的相应文件
function deleteVideo ($videoName){
//删除文件
//unlink($videoName);
if(unlink($videoName)){
echo "删除成功";
}else{
echo "删除失败";
}
echo "录像文件".$videoName."已经从服务器删除";
//return 返回值
}
deleteVideo(qwe);
?>
文件重命名
<?php
header("Content-Type: text/html; charset=utf-8");
$recordOriginName = utf8_decode($_GET["recordOriginName"]); //GET接收旧文件名称(*.mkv)
$recordCustomName = utf8_decode($_GET["recordCustomName"]); //GET接收新文件名称(*)
$dir = '/var/www/html/videos/';
if(is_dir($dir)){
if($db=opendir($dir)){
while(($file=readdir($db))!==false){
if($file == $recordOriginName){
rename(($dir.$recordOriginName),($dir.$recordCustomName.".mkv"));
echo "file found!";
}
}
closedir($db);
}
else {
echo "文件打开失败";
}
}else {
echo "$dir不是一个目录的形式";
}
?>
使用shell_exec命令
$output = shell_exec('cat /sys/class/dmi/id/product_uuid');
$output=trim($output);
$output1 = shell_exec('ifconfig -a | awk "/eth0/{ print $1 }" ');
$output1=trim($output1);
第二种:借助ssh2_connect服务
<?php
header("Content-Type: text/html; charset=utf-8");
$cameraIp=$_POST["cameraIp"];
$host='192.168.1.93';
$user='root';
$passwd='123456';
$connection = ssh2_connect($host, 22);
if (!$connection) die('connection to '.$host.':22 failed');
$auth_methods = ssh2_auth_none($connection, $user);
if (in_array('password', $auth_methods ))
if (ssh2_auth_password($connection, $user, $passwd)){
$stream = ssh2_exec($connection, "kill -9 `netstat -alp | grep $cameraIp | awk '{print $7}'| awk -F/ '{print $1}'`");
stream_set_blocking($stream, true);
if ($stream === FALSE) die("pwd failed");{
echo ''.stream_get_contents($stream).'';}
else {
die( $user.' login Failed<br/>');} }
?>
该方法需要在服务器上安装一个ssh2服务。