Refactor code to add sudo prefix for certain commands

This commit is contained in:
Andras Bacsai 2024-04-16 21:22:57 +02:00
parent 41f4b36593
commit 58523b0000
2 changed files with 30 additions and 2 deletions

View File

@ -34,7 +34,14 @@ public function execute_remote_command(...$commands)
$ignore_errors = data_get($single_command, 'ignore_errors', false);
$append = data_get($single_command, 'append', true);
$this->save = data_get($single_command, 'save');
if ($this->server->isNonRoot()) {
if (str($command)->startsWith('docker exec')) {
$command = str($command)->replace('docker exec', 'sudo docker exec');
} else {
$command = parseLineForSudo($command, $this->server);
}
}
ray($command);
$remote_command = generateSshCommand($this->server, $command);
$process = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
$output = Str::of($output)->trim();

View File

@ -1951,7 +1951,8 @@ function check_domain_usage(ServiceApplication|Application|null $resource = null
}
}
function parseCommandsByLineForSudo(Collection $commands, Server $server): array {
function parseCommandsByLineForSudo(Collection $commands, Server $server): array
{
$commands = $commands->map(function ($line) {
if (!str($line)->startSwith('cd') && !str($line)->startSwith('command')) {
return "sudo $line";
@ -1979,3 +1980,23 @@ function parseCommandsByLineForSudo(Collection $commands, Server $server): array
return $commands->toArray();
}
function parseLineForSudo(string $command, Server $server): string
{
if (!str($command)->startSwith('cd') && !str($command)->startSwith('command')) {
$command = "sudo $command";
}
if (Str::startsWith($command, 'sudo mkdir -p')) {
$command = "$command && sudo chown -R $server->user:$server->user " . Str::after($command, 'sudo mkdir -p') . ' && sudo chmod -R o-rwx ' . Str::after($command, 'sudo mkdir -p');
}
if (str($command)->contains('$(') || str($command)->contains('`')) {
$command = str($command)->replace('$(', '$(sudo ')->replace('`', '`sudo ')->value();
}
if (str($command)->contains('||')) {
$command = str($command)->replace('||', '|| sudo ')->value();
}
if (str($command)->contains('&&')) {
$command = str($command)->replace('&&', '&& sudo ')->value();
}
return $command;
}