Example of running the Linux command in PHP and starting the SSH service

  • 2021-06-29 10:32:20
  • OfStack

After upgrading VPS, the sshd service did not start automatically due to compatibility issues between upstart and OpenVZ of Ubuntu, which could not be resolved after attempting console and file manager of vePortal and submitting technical support.

It's up to you, but the general idea is to do the su command in PHP to execute the sshd service because WordPress is still alive and you can edit the PHP scripts related to the theme directly in the background.Simply insert the prepared snippet into header.php and visit the home page under 1 in your browser.

Related code logic
1. proc_using PHPopen opens a process, redirects stdin, stdout, stderr, where an python program is executed.
2. Open an pty in this python program and run an sh.
3. Use the redirected stdin pipe in step 1 to send su commands to the python program. python writes command data from stdin to ptmx, while sh's stdin, stdout, and stderr are redirected to pts paired with ptmx opened by python.That is, the su command is ultimately transferred to the sh process for processing.
4. The sh process naturally executes the su command, and then the stdin, stdout, and stderr of the su process are redirected to that pts.
5. After sleep 1 period of time (mainly until su really runs), write the password again, and the data flow process is consistent with steps 3 and 41.

Related code snippets:


<?php
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr
  );
  $process = proc_open("python -c 'import pty; pty.spawn(\"/bin/sh\")'", $descriptorspec, $pipes);
  if (is_resource($process)) {
    fwrite($pipes[0], "su -c 'service ssh start' root\n");
    fflush($pipes[0]);
    sleep(3);
    fwrite($pipes[0], "PASSWORD\n");
    fflush($pipes[0]);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);
  } 
?>


Related articles: