phpseclib-SSH2 - >使用exec-command创建环境变量

时间:2016-02-01 17:29:37

标签: php phpseclib ssh2-exec

我正在开发一个PHP应用程序,通过它可以通过phpseclib的SSH2连接到RaspberryPI(运行Linux)。 连接到设备并通过" ls" - oder" pwd" -commands获取信息正常。

但是现在我正在尝试创建一个新的环境变量 - 让我们在设备上说TEST_VAR - 但这似乎不起作用。

按照我的php代码尝试:

$ssh = new Net_SSH2($host, $port, 10);
if (!$ssh->login($user, $pass)) {
    exit("Login Failed");
}

// Test->Show the working directory
echo $ssh->exec("pwd");
// Create an environment variable "TEST_VAR" with the value "Test"
echo $ssh->exec("export TEST_VAR=Test");
// Give the content of the above created variable out
echo $ssh->exec("echo \$TEST_VAR");

变量的创建不起作用 我无法弄清楚为什么 - 因为没有错误。 这对phpseclib来说是否可能?

我会非常感谢任何帮助和提示。

此致 西蒙

1 个答案:

答案 0 :(得分:3)

$ssh->exec不保留状态。所以,类似地,你不能$ssh->exec('cd /some/random/path'); echo $ssh->exec('pwd')并期望它输出/some/random/path

您有几个选择。

  1. 链接命令。例如。 $ssh->exec("pwd; export TEST_VAR=Test; echo \$TEST_VAR");

  2. 使用交互模式。例如。 $ssh->read('[prompt]'); $ssh->write("pwd\n"); $ssh->read('[prompt]'); $ssh->write("export TEST_VAR=Test\n");

  3. 将您要运行的所有命令放入shell脚本中,然后运行shell脚本。

  4. 更多信息:

    http://phpseclib.sourceforge.net/ssh/examples.html#chdir