AWS CLI 命令适用于 Bash,但不适用于 PHP shell_exec()

AWS CLI command works on Bash, but not with PHP shell_exec()

我想触发以下命令:

aws route53 change-resource-record-sets --hosted-zone-id XXX
 --change-batch '{ "Comment": "2018-06-19-11:31", "Changes":
[ { "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com",
"Type": "TXT", "TTL": 60, "ResourceRecords":
[ { "Value": "\"something\"" } ] } } ] }'

当我在 bash 触发它时有效,但当我 运行 在 PHP 触发它时无效:

$json = trim(shell_exec($cmd_aws_submit));
// or:
$json = trim(shell_exec("{$cmd_aws_submit}"));

AWS 期望引用 TXT 记录的值 ("\"something\"")。我试着这样引用它:

$value = "\\"" . $textvalue . "\\"";
$value = "\"" . $textvalue . "\"";
$value = "\'" . $textvalue . "\'";
$value = "'" . $textvalue . "'";

None 有效,我总是收到以下错误:

Error parsing parameter '--change-batch': Invalid JSON: Invalid \escape: line 12 column 23 (char 246) JSON received: { "Comment": "2018-06-19-11:54", "Changes": [ { "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com", "Type": "TXT", "TTL": 60, "ResourceRecords": [ { "Value": "\"something\"" } ] } } ] }

对于其他 aws UNQUOTED dns 记录值,PHP shell_exec() 工作完美。

如果我在 Bash 上触发它,它使用 "\"something\"" 可以完美工作 - 为什么它不能使用 PHP shell_exec()

您应该使用本机 escapeshellarg 方法来转义传递给命令行的参数。如果您决定在某个阶段在 JSON 字符串中包含可能不安全的数据,这也将保护您免受参数注入攻击。

$json = '{ "Comment": "2018-06-19-11:31", "Changes":
[ { "Action": "CREATE", "ResourceRecordSet": { "Name": "example.com",
"Type": "TXT", "TTL": 60, "ResourceRecords":
[ { "Value": "\"something\"" } ] } } ] }';

$command = "aws route53 change-resource-record-sets --hosted-zone-id XXX
 --change-batch " . escapeshellarg($json);

$result = trim(shell_exec($command));

您也可以选择将 JSON 字符串构建为数组,然后使用 json_encode() 为您构建字符串。