2013-10-18 169 views
3

我似乎無法得到一個變量傳遞給我的bash腳本從PHP。無論我嘗試什麼,$ uaddress和$ upassword都是空的。傳遞一個變量從PHP到bash

** * ** * ** * ** * ** * ** * ** *慶典* ** * ** * ** * ** * ***

#!/bin/bash -x 
useraddress=$uaddress 
upassword=$upassword 
ssh -p 222 -6 2400:8900::f03c:91f:fe69:8af "/var/www/localhost/htdocs/postfixadmin/scripts/postfixadmin-cli mailbox add" $useraddress --password $upassword --password2 $upassword .ssh 

** * ** * ** * * PHP * ** * ** * * * * ** * ***

<?php 
$upassword = 'test1234'; $uaddress = '[email protected]'; 
$addr = shell_exec('sudo /home/tpccmedia/cgi-bin/member_add_postfixadmin 2>&1'); echo $uaddress; echo $upassword; 
//$addr = shell_exec('ssh -p 222 -6 2400:8900::f03c:91f:fe69:8af /var/www/localhost/htdocs/postfixadmin/scripts/postfixadmin-cli mailbox add; echo $useraddress; --password; echo $upassword; --password2; echo $upassword; .ssh'); 
echo "<pre>$addr</pre>"; 
var_dump($addr); 
?> 

** * ** * ** * ** 輸出和調試 ** * ** * ** * * * *

[email protected] 

+ useraddress= 
+ upassword= 
+ ssh -p 2222 -6 2400:8900::f03c:91ff:fe69:8aaf '/var/www/localhost/htdocs/postfixadmin/scripts/postfixadmin-cli mailbox add' --password --password2 .ssh 

Welcome to Postfixadmin-CLI v0.2 
--------------------------------------------------------------- 
Path: /var/www/localhost/htdocs/postfixadmin 
--------------------------------------------------------------- 

Username: 
> 

string(404) "+ useraddress= + upassword= + ssh -p 2222 -6 2400:8900::f03c:91ff:fe69:8aaf '/var/www/localhost/htdocs/postfixadmin/scripts/postfixadmin-cli mailbox add' --password --password2 .ssh Welcome to Postfixadmin-CLI v0.2 --------------------------------------------------------------- Path: /var/www/localhost/htdocs/postfixadmin --------------------------------------------------------------- Username: > " 

回答

8

您需要將變量作爲參數傳遞給shell腳本,並且shell腳本必須讀取其參數。

所以在PHP中:

$useraddress = escapeshellarg('[email protected]'); 
$upassword = escapeshellarg('test1234'); 
$addr = shell_exec("sudo /home/tpccmedia/cgi-bin/member_add_postfixadmin $useraddress $upassword 2>&1"); 

,並在shell腳本:

useraddress=$1 
upassword=$2 
+0

你也肯定想逃避參數[escapeshellarg](http://www.php.net/manual/en/function.escapeshellarg.php) - 尤其是可能的密碼字段包含特殊字符。 – tangrs

+0

@tangrs謝謝。我也忘了將字符串的單引號改爲雙引號,這樣插值就可以工作。 – Barmar

+0

@Barmar no sir,$ useraddress = escapeshellarg($ useraddress);給出一個未定義的變量,escapeshellarg('$ useraddress')實際上會傳遞給BASH,但是作爲一個字符串。 http://paste.ee/p/arOIF http://bpaste.net/show/141824/ – brad

2

明白了。

<?php 
$upassword = 'test1234'; $uaddress = '[email protected]'; 
$uaddress = escapeshellarg($uaddress); 
$upassword = escapeshellarg($upassword); 
$addr = shell_exec("sudo /home/tpcmedia/cgi-bin/member_add_postfixadmin $uaddress $upassword 2>&1"); 
?> 


#!/bin/bash -x 
uaddress=$1 
upassword=$2 
ssh -p 2222 -6 2400:8900::f03c:91ff:fe69:8aaf "/var/www/localhost/htdocs/postfixadmin/scripts/postfixadmin-cli mailbox add" $uaddress --password $upassword --password2 $upassword