Simon
Simon

Reputation: 23

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

I am working on a PHP-application, with which I can connect to a RaspberryPI (running Linux) via SSH2 of the phpseclib. Connecting to a device and getting information over the "ls"- oder "pwd"-commands is working fine.

But now I am trying to create a new environment variable - let's say TEST_VAR - on a device, but this seems not to work.

Following my php-code to try that:

$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");

The creation of the variable does not work and I can not figure out why - because there are no errors. Is this even possible with the phpseclib?

I would be very thankful for any help and hints.

Regards Simon

Upvotes: 2

Views: 1376

Answers (1)

neubert
neubert

Reputation: 16802

$ssh->exec doesn't preserve state. So, similarily, you can't do $ssh->exec('cd /some/random/path'); echo $ssh->exec('pwd') and expect it to output /some/random/path.

You have a few options.

  1. Chain the commands. eg. $ssh->exec("pwd; export TEST_VAR=Test; echo \$TEST_VAR");

  2. Use interactive mode. eg. $ssh->read('[prompt]'); $ssh->write("pwd\n"); $ssh->read('[prompt]'); $ssh->write("export TEST_VAR=Test\n");

  3. Put all the commands you want to run into a shell script and then run the shell script.

More info:

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

Upvotes: 3

Related Questions