2012-03-23 32 views
3

以下是这种情况:我编写了一个后端应用程序,它运行在某个服务器上。在这台服务器上,有一个脚本可以通过ssh从前端服务器执行。然后,我的脚本将检查它所需的环境变量是否正确加载,因为我在脚本本身中严重依赖它们。使用proc_open()加载.profile

这有效,但不是我想要的东西工作的方式。当连接建立时,./profile不会仅仅使用exec('source /home/user/.profile');加载,当然不起作用。由于该脚本已在运行。 这就是为什么在脚本开始这样的:

#!/to/php/bin/php -n 
<?php 
    if (!$_SERVER['VAR_FROM_PROFILE']) 
    { 
     exec('/absolute/path/to/helperscript '.implode(' ',$argv),$r,$s); 
     if ($s !== 0) 
     { 
      die('helper script fails: '.$s); 
     } 
     exit($r[0]); 
    } 

该助手脚本是一个KSH脚本:

#!/path/ksh 
source /.profile 
$* 

加载配置文件,并再次调用第一个脚本。 我想要第二个脚本消失了,我发现它很愚蠢......需要第二个脚本来运行第一个脚本。我知道可以使用proc_open设置环境值,但将.profile重写为一个数组甚至更糟糕。 我也尝试过proc_open一个shell,加载配置文件并从本身再次运行脚本。只有发现脚本不断调用自己,导致我相信该配置文件根本没有加载。

这里是我的尝试至今:

#!/to/php/bin/php -n 
<?php 
    if (!$_SERVER['VAR_FROM_PROFILE'] && $argv[1] !== 'fromself') 
    { 
     $res = proc_open('ksh',array(array('pipe','r'),array('pipe','w'),array('pipe','w')),$pipes); 
     usleep(5); 
     fwrite($pipes[0],'source /home/user/.profile & '.$argv[0].' fromself'); 
     fclose($pipes[0]);//tried using fflush and a second fwrite. It failed, too 
     usleep(1); 
     echo stream_get_contents($pipes[1]); 
     fclose($pipes[1]); 
     proc_close($res); 
     exit(); 
    } 
    var_dump($_SERVER); 
?> 

我有这个至今没有运气,谁能告诉我,如果我在这里忘了什么东西?我究竟做错了什么?我在这里忽略了什么吗?

+0

你真的需要从'.profile'加载环境变量吗?我的意思是,为什么不把这些变量硬编码到PHP脚本中?你如何在PHP脚本中使用这些变量? – galymzhan 2012-03-23 18:29:08

+1

是的,我喜欢。 '.profile'包含100多个变量和别名。给你一个想法:我的脚本调用另外两个脚本,这两个脚本都依赖于环境变量。他们需要的环境变量取决于他们正在处理的数据。我可以预处理这些数据并相应加载适当的变量,但这需要我很长时间才能进行调试。该脚本也应该能够在我们公司的任何服务器上运行。硬编码意味着要为每个环境编写一个脚本。这似乎比使用我现在使用的korn shell脚本方法更笨拙。 – 2012-03-24 01:53:45

回答

4

我没有ksh,但我设法使用bash来完成。

/home/galymzhan/.bash_profile

export VAR_FROM_PROFILE="foobar" 

/home/galymzhan/test.php

#!/usr/bin/php -n 
<?php 
if (!isset($_SERVER['VAR_FROM_PROFILE'])) { 
    $descriptors = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w')); 
    $process = proc_open('bash', $descriptors, $pipes); 
    fwrite($pipes[0], escapeshellcmd('source /home/galymzhan/.bash_profile') . "\n"); 
    fwrite($pipes[0], escapeshellcmd('/home/galymzhan/test.php') . "\n"); 
    fclose($pipes[0]); 
    echo "Output:\n"; 
    echo stream_get_contents($pipes[1]); 
    echo "\n"; 
    fclose($pipes[1]); 
    proc_close($process); 
    exit; 
} 
print "Got env var {$_SERVER['VAR_FROM_PROFILE']}\n"; 
// Useful part of the script begins 

输出我有:

[[email protected] ~]$ ./test.php 
Output: 
Got env var foobar 
+0

谢谢,同样的规则似乎适用于科恩斯内尔,因为这工作就像我想要的。 – 2012-03-24 10:58:54