首页 > 解决方案 > Ajax 调用中的 shell_exec 导致无限循环

问题描述

我有这个 Ajax 调用:

$('#directory_select_form').submit(function(e) {
        $('#loader').show();
        $('#order_number_submit_btn').prop('disabled', true);
        e.preventDefault();
       $.ajax({
           url: 'includes/confirmation_emails/process_directory_request.php',
           type: 'POST',
           dataType: 'json',
           data: $(this).serialize(),
           success: function(data) {
               console.log(data);
               $('#loader').hide();
               $('#order_number_submit_btn').prop('disabled', false);
           },
           error: function(jqXHR, textStatus, errorThrown) {
               $('#loader').hide();
               $('#order_number_submit_btn').prop('disabled', false);
           }
       })
    });

process_directory_request.php包含一个shell_exec命令:

<?php

$selected_directory = $_POST['selected']; //<-- This will be used later. Hard coded for now
$order_number = $_POST['orderId']; //<-- This will be used later. Hard coded for now.


$command = shell_exec('ssh remoteServer grep -o "Order Number 1234567" /mnt/tank/TECH/"MySQL\\ Data\\ Archives"/path/to/the/file');

echo json_encode($command);

它崩溃了,因为由于某种原因它进入了无限循环。如果我从命令行运行命令,它会按预期运行。

因为一开始我不能使用这个答案ssh。我正在远程运行命令。

是什么导致了这个无限循环?我不明白。我正在将 ajax 响应数据打印到控制台,并且一遍又一遍地是同一行。

编辑 这是我的开发控制台中的输出,但实际上是很多倍:

/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order
/mnt/tank/TECH/MySQL Data Archives/path/to/the/file:Order

标签: phpajaxsshshell-exec

解决方案


这不是一个无限循环,它只是比您预期的更多输出。

问题是报价没有被发送到远程服务器。ssh简单地将所有参数连接到一个命令中,因此远程命令是:

grep -o Order Number 1234567 /mnt/tank/TECH/MySQL\ Data\ Archives/path/to/the/file

它只是搜索单词Order,并将Number1234567视为要搜索的文件。

您需要转义双引号,以便按字面意思发送它们。

$command = shell_exec('ssh remoteServer grep -o \\"Order Number 1234567\\" /mnt/tank/TECH/\\"MySQL Data Archives\\"/path/to/the/file');

此外,您不需要在带有空格的目录名称中同时使用双引号和转义空格。


推荐阅读