🐍 Keep Your PC Awake with Python (Perfect for RDP Users!)

Nayana AgarwalNayana Agarwal
4 min read

Ever been deep into a remote session or running a long task when suddenly… 💥 your system decides to nap?

If you’re using RDP (Remote Desktop Protocol)—Windows’ built-in way to connect to a remote computer — you know how frustrating it is when your remote machine times out due to inactivity. RDP sessions can drop if Windows thinks you're idle, even though your job is still running.

Let’s fix that. Here's a Python script that: ✅ Prevents Windows from sleeping ✅ Keeps the display active ✅ Simulates keypresses to fake user activity ✅ Keeps your RDP session alive

We'll break this script down line by line so you know exactly what it’s doing.

📦 Step 1: Import Required Libraries

import ctypes
import time
import pyautogui

ctypes : Calls Windows API functions to control power state.

time: Adds pauses between keypresses.

Pyautogui: Simulates keyboard/mouse input (as if you're still at the keyboard).

⚙️ Step 2: Define Windows Power Flags

ES_CONTINUOUS = 0x80000000
ES_AWAYMODE_REQUIRED = 0x00000040
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED = 0x00000002

These constants are passed to the Windows API to tell it:

Constant    Meaning
ES_CONTINUOUS    Keep the settings active continuously
ES_AWAYMODE_REQUIRED    Prevent idle sleep (even if background)
ES_SYSTEM_REQUIRED    Don't let the system sleep
ES_DISPLAY_REQUIRED    Keep the screen turned on

🛑 Step 3: Disable Fail-Safe for Automation

pyautogui.FAILSAFE = False

PyAutoGUI stops scripts if the mouse moves to the top-left corner.

This disables that behavior — useful when running scripts in headless or remote sessions (like RDP).

💻 Step 4: Prevent Sleep Function

def prevent_sleep():
    ctypes.windll.kernel32.SetThreadExecutionState(
        ES_CONTINUOUS | ES_AWAYMODE_REQUIRED | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
    )

This function tells Windows:

“Do not sleep. Keep the display on. Keep the system active — indefinitely.”

💤 Step 5: Allow Sleep Again (On Exit)

def allow_sleep():
    ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)

Resets the system back to its normal sleep behavior. We’ll call this when the user stops the script.

🧑‍💻 Step 6: Keep Your RDP Session Active

def keep_rdp_alive():
    print("Keeping RDP session alive... Press Ctrl+C to stop.")
    prevent_sleep()
    while True:
        pyautogui.press('shift')  # Simulate a Shift keypress
        time.sleep(240)           # Wait 4 minutes before repeating

This:

Calls prevent_sleep() to block system sleep

Then loops forever, pressing Shift every 4 minutes to trick Windows into thinking you’re still active

Helps prevent RDP session timeouts (Windows assumes you’re idle if there's no input)

▶️ Step 7: Run the Script

try:
    print("Preventing system sleep. Press Ctrl+C to stop.")
    keep_rdp_alive()
    while True:
        time.sleep(60)  # Keep script running

Starts the magic and keeps the script alive. Ctrl+C stops it.

🧹 Step 8: Clean Exit

except KeyboardInterrupt:
    print("Restoring sleep settings...")
    allow_sleep()

When you hit Ctrl+C, this block catches the interruption and restores sleep settings properly.

🧠 What Is RDP? RDP (Remote Desktop Protocol) is a Microsoft protocol that lets you connect to and control a remote Windows machine — as if you were sitting in front of it.

It’s used by developers, sysadmins, and IT teams to:

Manage remote servers

Access desktops from anywhere

Perform long-running tasks like builds, downloads, etc.

Problem is, RDP sessions time out if Windows thinks you’re inactive. Even if your script is running, the system may go to sleep or lock the session. That’s why simulating user input is so useful.

✅ TL;DR: What This Script Does Prevents system and display sleep via Windows API

Simulates Shift keypress every 4 minutes

Keeps RDP sessions alive and stable

Cleanly exits and restores sleep behavior

🔧 Want to Customize It? Adjust the time.sleep(240) interval if your RDP session times out faster.

Simulate different keys or mouse movements.

Add a tray icon or system service wrapper if running long-term.

🧪 Copy the Full Script

import ctypes
import time
import pyautogui

# Prevent sleep (Keeps system & display active)
ES_CONTINUOUS = 0x80000000
ES_AWAYMODE_REQUIRED = 0x00000040
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED = 0x00000002
pyautogui.FAILSAFE = False

def prevent_sleep():
    ctypes.windll.kernel32.SetThreadExecutionState(
        ES_CONTINUOUS | ES_AWAYMODE_REQUIRED | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED
    )

def allow_sleep():
    ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)

def keep_rdp_alive():
    print("Keeping RDP session alive... Press Ctrl+C to stop.")
    prevent_sleep()
    while True:
        pyautogui.press('shift')
        time.sleep(240)

try:
    print("Preventing system sleep. Press Ctrl+C to stop.")
    keep_rdp_alive()
    while True:
        time.sleep(60)
except KeyboardInterrupt:
    print("Restoring sleep settings...")
    allow_sleep()

Let me know if you'd like a version for macOS/Linux or a version that includes a GUI!

2
Subscribe to my newsletter

Read articles from Nayana Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nayana Agarwal
Nayana Agarwal