'How to avoid executing commands as root using phpseclib's library?

Currently I'm executing all commands as root, which is a very bad idea and unsafe as I read. I want to execute the commands in a secure way.

An example of currently using command:

use \phpseclib3\Net\SSH2;
   
// connect function using root user...

function ssh_connect(){
$connect = new SSH2('localhost', '22');
        if (!$connect->login('root', 'pass')) {
            throw new \Exception('Login failed');
        }
return $connect;
}

// execute function

function ssh_exec($cmd){
        $ssh = ssh_connect();
        $stream = $ssh->exec($cmd);
        return $stream;
    }

So I call it like

ssh_exec("mkdir -p /home/username/test; cp -r /home/test/*.jpg");

I read that it will be more secure if I'm using sudo... but how can I make an user-group which can

  1. Allow to copy files from only specified folders
  2. Disallow to go outside from their folders
  3. Using screen command, useradd/userdel command but restrict making/deleting users in this group which I want to add

And they can make/delete files and folders only under their homes right?

Or there is any other&easier way to achieve these but still secure?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source