3

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

这行得通,虽然不是我想要的工作方式。建立连接后,./profile 不会加载,只是 usingexec('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);
?>

到目前为止我没有运气,谁能告诉我我是否在这里忘记了什么?我究竟做错了什么?我在这里忽略了什么吗?

4

1 回答 1

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

我得到的输出:

[galymzhan@dinohost ~]$ ./test.php 
Output:
Got env var foobar
于 2012-03-24T07:50:59.383 回答