Run some Linux command in PHP trail together

By : mahdi
Source: Stackoverflow.com
Question!

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?

By : mahdi


Answers

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


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');


If you have to pass multiple parameter please use class object:

public class PortalClass
{
    public ApplicationModel applicationModel { get; set; }
    public string user_id { get; set; }
    public string id { get; set; }
    public object pageCollection { get; set; }
}

public object GetApplication(PortalClass data)
{
    JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, PreserveReferencesHandling = PreserveReferencesHandling.None };
    var myObject=JsonConvert.DeserializeObject<PageCollection>(data.pageCollection.ToString(), settings)
    return null;
}

Client Side:

var data = {
    user_id: userId,
    id: id
};

http.post(url, data).then(
   function (response) {

}, function (err) {
   callback.reject(err);
});


This video can help you solving your question :)
By: admin