2012-08-07 57 views
1

我想在PHP运行这一点,但它并没有因为行情的工作....我需要使用单引号两次 - 如何逃脱?

$cmd="sudo -u postgres sh -c 'psql -c \"alter user edumate with encrypted password \'BLAH_BLAH\';\" template1 2>&1' "; 
    $shellOutput = exec($cmd, $output); 

psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1作为Postgres的用户运行时执行确定。

我试过了,但它对我不起作用。

sudo -u postgres sh -c 'psql -c \"alter user edumate with encrypted password \'BLAH_BLAH\';\" template1 2>&1' 
sudo -u postgres sh -c 'psql -c "alter user edumate with encrypted password \'BLAH_BLAH\';" template1 2>&1' 

我该如何逃避$ cmd才能执行它?

更新我

$subcommand="alter user edumate with encrypted password 'BLAH_BLAH';"; 
    $sub = escapeshellarg($subcommand); 
    $cmd="sudo -u postgres sh -c 'psql -c \"".$sub."\" template1 2>&1'"; 
    $shellOutput = exec($cmd, $output); 
    echo "<pre>Output = " . print_r($output,1) . "</pre>"; 

回报

Output = Array 
(
) 

更新II

感谢@Hawili的工作代码。我想知道如何使用sh -c命令来运行,他省略了。

$shellOutput=`sudo -u postgres psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1`; 
+0

不需要\'当用字符串“ – Teson 2012-08-07 06:16:34

+0

@ user247245封装:您能详细说明还是提供确切的语法? – Radek 2012-08-07 06:20:28

回答

1

可以使用反引号`这是使用PHP执行命令直接进入外壳

例如:

$output = `ls -l`; 

你的情况可能是这样的:

$shellOutput=`sudo -u postgres psql -c "alter user edumate with encrypted password 'BLAH_BLAH';" template1 2>&1`; 
+0

它什么都没有返回。没有错误,没有输出。 – Radek 2012-08-07 06:42:45

+0

?检查我在'ls -l'之前发布的简单示例是否适合您? – Hawili 2012-08-07 06:44:10

+0

是的,一些简单的作品。 – Radek 2012-08-07 06:47:10

2
+0

escapeshellarg也可能工作得很好。所以$ sub = escapeshellarg($ subcommand); $ cmd =“sudo -u postgres sh -c $ sub”; – EPB 2012-08-07 06:19:07

+0

@EPB:在我的问题中查看'更新I'。 – Radek 2012-08-07 07:03:23

+0

$ subcommand ='psql -c“使用加密密码更改用户edumate \'BLAH_BLAH \';” template1 2> &1'; $ sub = escapeshellarg($ subcommand); $ cmd =“sudo -u postgres sh -c $ sub”;因为整个psql命令基本上是sh的一个参数。 – EPB 2012-08-07 16:26:20