Automated Nightly Reboot of Windows Domain Computers: Script Solutions in PHP, JavaScript, and Bash


2 views

Maintaining a fleet of Windows domain computers often requires scheduled reboots for updates or maintenance. Without built-in domain controller services, we need script-based solutions that can:

  • Target specific machines by hostname
  • Execute clean restart commands
  • Optionally gather live host lists from DHCP

Here's a robust PHP script that handles both static host lists and DHCP queries:


<?php
// Define hosts (either static list or from DHCP)
$hosts = [
    'ws-001.domain.local',
    'ws-002.domain.local',
    // ... add more
];

// Alternative: Query DHCP (Windows Server 2008)
function getDHCPClients() {
    exec('netsh dhcp server scope 192.168.1.0 show clients', $output);
    $hosts = [];
    foreach ($output as $line) {
        if (preg_match('/^(\d+\.\d+\.\d+\.\d+)\s+(\S+)\s+/', $line, $matches)) {
            $hosts[] = $matches[2];
        }
    }
    return array_filter($hosts);
}

// Main reboot logic
foreach ($hosts as $host) {
    $command = "shutdown /r /m \\\\{$host} /t 30 /c \"Scheduled nightly reboot\" /f";
    exec($command, $output, $return);
    
    if ($return === 0) {
        echo "Successfully initiated reboot for {$host}\n";
    } else {
        echo "Failed to reboot {$host}. Check permissions and connectivity.\n";
    }
}
?>

For environments where Node.js is available:


const { exec } = require('child_process');

const hosts = [
    'ws-001.domain.local',
    'ws-002.domain.local'
];

hosts.forEach(host => {
    exec(shutdown /r /m \\\\${host} /t 30 /c "Nightly reboot" /f, 
        (error, stdout, stderr) => {
            if (error) {
                console.error(Error rebooting ${host}: ${error.message});
                return;
            }
            console.log(Reboot command sent to ${host});
        });
});

When working with Windows Subsystem for Linux or hybrid environments:


#!/bin/bash

# Static host list or parse from DHCP
HOSTS=("ws-001.domain.local" "ws-002.domain.local")

for host in "${HOSTS[@]}"; do
    if net rpc shutdown -r -f -I "$host" -U 'domainadmin%password'; then
        echo "Successfully rebooted $host"
    else
        echo "Failed to reboot $host" >&2
    fi
done
  • Permissions: The account running the script needs admin privileges on target machines
  • Timing: Schedule during off-hours using Windows Task Scheduler or cron
  • Error Handling: Implement logging to track successful/failed reboots
  • Wake-on-LAN: Consider adding WOL packets if machines are powered off

For those willing to use Python despite limited knowledge:


import subprocess

hosts = ['ws-001.domain.local', 'ws-002.domain.local']

for host in hosts:
    try:
        subprocess.run(
            ['shutdown', '/r', '/m', f'\\\\{host}', '/t', '30', '/c', 
             'Scheduled reboot', '/f'],
            check=True
        )
        print(f"Successfully initiated reboot for {host}")
    except subprocess.CalledProcessError as e:
        print(f"Failed to reboot {host}: {e}")

For system administrators managing Windows domains, automating nightly reboots can significantly improve maintenance efficiency. Here's a comprehensive approach using your preferred scripting languages.

PHP's exec() function can execute Windows commands remotely:


<?php
$computers = ['PC01', 'PC02', 'WS03']; // Your computer list

foreach ($computers as $host) {
    $command = "shutdown /r /m \\\\$host /t 60 /c \"Scheduled nightly reboot\"";
    exec($command, $output, $return);
    
    if ($return === 0) {
        echo "Reboot command sent to $host successfully\n";
    } else {
        echo "Failed to reboot $host. Error code: $return\n";
    }
}
?>

For a more modern approach using Node.js:


const { exec } = require('child_process');
const computers = require('./computers.json'); // JSON file with hostnames

computers.forEach(host => {
    exec(shutdown /r /m \\\\${host} /t 60 /c "Automated reboot", 
        (error, stdout, stderr) => {
            if (error) {
                console.error(Error rebooting ${host}: ${error.message});
                return;
            }
            console.log(${host}: ${stdout});
        });
});

If you're using Windows Subsystem for Linux:


#!/bin/bash
readarray -t computers < computers.txt

for host in "${computers[@]}"
do
    net rpc shutdown -r -f -I $host -U 'DOMAIN\adminuser%password' && \
    echo "Successfully rebooted $host" || \
    echo "Failed to reboot $host"
done

To fetch computers from a Windows 2008 DHCP server:


# PowerShell command to export DHCP leases
Get-DhcpServerv4Lease -ComputerName dhcpserver.domain.com -ScopeId 192.168.1.0 | 
Where-Object {$_.AddressState -eq 'Active'} | 
Select-Object HostName | 
Export-Csv -Path C:\temp\active_clients.csv -NoTypeInformation

Create a scheduled task that runs your script nightly:


schtasks /create /tn "Nightly Reboot" /tr "C:\scripts\reboot.php" /sc daily /st 02:00 /ru "DOMAIN\adminaccount"
  • Implement logging for successful/failed reboots
  • Add ping checks before attempting reboot
  • Consider staggered reboots for large domains
  • Handle cases where computers are offline

Always:

  • Use dedicated service accounts with minimal privileges
  • Store credentials securely (not in scripts)
  • Validate all hostnames before processing
  • Implement proper error logging