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


phpseclib-SSH2 -> Create an environment variable with the exec-command

我正在开发一个PHP应用程序,我可以通过phpseclib的SSH2连接到RaspberryPI(运行Linux)。连接到设备并通过"ls"- oder "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一起使用吗?

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

问候西蒙

$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