2

我正在开发一个 PHP 应用程序,我可以通过 phpseclib 的 SSH2 连接到 RaspberryPI(运行 Linux)。连接到设备并通过“ls”-或“pwd”-命令获取信息工作正常。

但是现在我正在尝试在设备上创建一个新的环境变量 - 比如说 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 吗?

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

问候西蒙

4

1 回答 1

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 脚本。

更多信息:

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

于 2016-02-06T15:48:37.960 回答