How can PHP be used to automate the process of checking and monitoring service status on a root server?

To automate the process of checking and monitoring service status on a root server using PHP, you can create a script that connects to the server via SSH and runs commands to check the status of the services. You can then set up a cron job to run this script at regular intervals to monitor the services and send alerts if any issues are detected.

<?php
// Define server credentials
$server = 'your_server_ip';
$username = 'your_username';
$password = 'your_password';

// Connect to server via SSH
$connection = ssh2_connect($server);
ssh2_auth_password($connection, $username, $password);

// Run command to check service status
$command = 'systemctl status apache2';
$stream = ssh2_exec($connection, $command);
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);

// Check output for service status
if (strpos($output, 'active (running)') !== false) {
    echo 'Apache service is running';
} else {
    echo 'Apache service is not running';
}

// Close SSH connection
ssh2_exec($connection, 'exit');
?>