0

I wrote some php code that connected to vps through ssh

I know ssh2_exec can do it, but if I want run many command like:

ssh2_exec($connection, 'cd /home/ubuntu/');
ssh2_exec($connection, 'mkdir folder');
ssh2_exec($connection, 'cd folder');
ssh2_exec($connection, 'touch test.txt');
.
.
.

It doesn't work and only do first command. how can I run some many command trail together?

mahdi
  • 31
  • 6

2 Answers2

1

you can write multiple command on one line separated by ; or && So you can follow below code

ssh2_exec($connection, 'cd /home/ubuntu/; mkdir folder; cd folder; touch test.txt');

OR

ssh2_exec($connection, 'cd /home/ubuntu/ && mkdir folder && cd folder &&touch test.txt');
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42
0

Every time you call the function ssh2_exec you are creating a new shell and executing a single command.

If you want to run a series of commands within the same shell, you can try separating them with semicolons or newlines within the same string. For example:

$commands = <<<'EOD'
cd /home/ubuntu
mkdir folder
cd folder
touch test.txt
EOD;

ssh2_exec($connection, $commands);
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141