Putting a Windows 10/11 computer to sleep over the network using SSH.


Recommended Posts

With the help of Chat GPT and my own troubleshooting of the code .. I now have an app for that written in python!

Works great! Woot!

image.png.899bd3f15c5ded04b3e44c451cb7f379.png

 

image.png.d69f18592f7ed179b93704684e457d83.png

 

here is the code if anyone else wants it. You just have to enter the SSH IP / username and password as well as the wake on lan IP and mac address .Just keep the " " around the info.

import tkinter as tk
import paramiko
import socket
import binascii
import threading

# Specify the computer name here
computer_name = "Computer Name"

def ssh_connect():
    def ssh_worker():
        host = "IP address"
        port = 22  # SSH port (e.g., 22)
        username = "Username"
        password = "Password"

        try:
            # Create an SSH client instance
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

            # Connect to the SSH server
            ssh.connect(host, port, username, password)

            # Execute a custom command on the remote machine
            command = "RUNDLL32.EXE powrprof.dll,SetSuspendState"  # Replace with your desired command
            stdin, stdout, stderr = ssh.exec_command(command)
            
            # Show an SSH command execution success message on the GUI
            update_success_message("SSH command sent successfully")


            # Handle the result as needed
            result = stdout.read().decode()

            # Close the SSH connection when you're done
            ssh.close()

            print("SSH command result:")
            print(result)

        except paramiko.AuthenticationException:
            # Show an error message on the GUI
            update_error_message("Authentication failed")
        except paramiko.SSHException as e:
            # Show an error message on the GUI
            update_error_message(f"SSH connection failed: {e}")
        except Exception as e:
            # Show a generic error message on the GUI
            update_error_message(f"An error occurred: {e}")

    # Create and start a separate thread for SSH operations
    ssh_thread = threading.Thread(target=ssh_worker)
    ssh_thread.start()

def wake_on_lan():
    def wol_worker():
        mac_address = "MAC Address"  # Replace with your target MAC address
        broadcast_address = "IP Address"  # Replace with your network's broadcast address
        port = 9  # WoL port (default is 9)

        try:
            # Create a socket to send the WoL magic packet
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

            # Prepare the WoL magic packet
            mac_bytes = mac_address.replace(":", "").replace("-", "")
            if len(mac_bytes) != 12:
                # Show an error message on the GUI
                update_error_message("Invalid MAC address for WoL")
                return

            magic_packet = b'FF' * 6 + (mac_bytes * 16).encode()

            # Send the WoL magic packet
            s.sendto(binascii.unhexlify(magic_packet), (broadcast_address, port))
            s.close()

            # Show a WoL packet sent success message on the GUI
            update_success_message("WoL packet sent successfully")

        except socket.error as e:
            # Show an error message on the GUI
            update_error_message(f"Error sending WoL packet: {e}")

    # Create and start a separate thread for WoL operation
    wol_thread = threading.Thread(target=wol_worker)
    wol_thread.start()

# Create the main application window
app = tk.Tk()
app.title("SSHand Executor and WoL")

# Create a label with the specified computer name in big, bold letters
computer_name_label = tk.Label(app, text=computer_name, font=("Helvetica", 20, "bold"))
computer_name_label.pack()

# Create a label to display success messages
success_label = tk.Label(app, text="", font=("Helvetica", 14))
success_label.pack()

# Create a label to display error messages in red
error_label = tk.Label(app, text="", font=("Helvetica", 14), fg="red")
error_label.pack()

# Function to update the success message on the GUI
def update_success_message(message):
    success_label.config(text=message)
    app.after(5000, lambda: success_label.config(text=""))

# Function to update the error message on the GUI
def update_error_message(message):
    error_label.config(text=message)
    app.after(5000, lambda: error_label.config(text=""))

# Create buttons
execute_button = tk.Button(app, text="Put to Sleep", command=ssh_connect)
execute_button.pack()

sleep_button = tk.Button(app, text="Wakeup", command=wake_on_lan)
sleep_button.pack()

# Start the GUI application
app.mainloop()

Then used pyinstall to compile it to an exe

 

  • Like 2
  • Love 1
  On 23/09/2023 at 07:14, binaryzero said:

You should probably learn PoweShell…

Expand  

Dunno, i'm having a BLAST making these apps. It's addicting.

If anything i'd like to learn Python.

Should try and port it to other languages :).

ChatGPT is actually really powerful in assisting in programing though I'll give it that.

@WarwagonI would ignore @binaryzeroand his comment. You started with a .bat file, you branched out to make an application that uses Python. If it works for you, it works. I appreciate that you shared your experience so that others can use what you learned along the way if they want to do a similar thing.

  On 23/09/2023 at 19:56, Nick H. said:

@WarwagonI would ignore @binaryzeroand his comment. You started with a .bat file, you branched out to make an application that uses Python. If it works for you, it works. I appreciate that you shared your experience so that others can use what you learned along the way if they want to do a similar thing.

Expand  

There isn’t really anything wrong with his comment. PowerShell is ideal for this stuff and is built into Windows.  To each their own of course. 

  On 23/09/2023 at 20:13, adrynalyne said:

There isn’t really anything wrong with his comment. PowerShell is ideal for this stuff and is built into Windows. 

Expand  

I agree, nothing wrong with going through Powershell. But he brought it up back in February, we (binaryzero and myself) provided links to do it via Powershell. Warwagon went with Python, and it works.

Rehashing the same comment from several months ago just seems a bit useless, and not productive.

  On 23/09/2023 at 20:17, Nick H. said:

I agree, nothing wrong with going through Powershell. But he brought it up back in February, we (binaryzero and myself) provided links to do it via Powershell. Warwagon went with Python, and it works.

Rehashing the same comment from several months ago just seems a bit useless, and not productive.

Expand  

Gotcha. I didn’t check the date. 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Nice! My $100 refurbished iPad 8 that I bought last year for a small project (and still runs like new cuz it's been mostly in storage the past several months) will get this v26 upgrade. I'm definitely gonna scope out OS26 on this device before upgrading my also-supported refurbished iPhone SE 3rd Gen (only got it for the 5G UW support).
    • Hello, The separate discussion about VLC has been moved to its own thread at  Regards, Aryeh Goretsky  
    • Hello, I am guessing this is the result of using a third-party tweaking tool instead of changing things within Windows settings. Windows 11 has a decent set of configuration options for the display, but they tend to be scattered throughout the operating system due to fragmentation of product ownership/inconsistent standards being applied by Microsoft. There are a few places in Windows 11 where you can modify the various display settings in order to get them to your liking: Under Settings → System → Display you can stroll down to the Scale & layout section and change the Scale and Display resolution settings to whatever you prefer.  For the Scale option, you can click on the text box to choose between the various pre-populated settings.  If none of those are exactly what you are looking for, click on the caret ("") caret to open the Custom scaling setting (also available under Settings → Display → Custom scaling).  I would recommend this as an option of last resort as this can cause display issues in various programs. I strongly recommend using the screen's native Display resolution here; it should show up as the "(Recommended)" resolution.  If it does not, you may need to install your monitor's profile information file (basically, a device driver for your monitor) to get the correct setting. Another place to look at making changes to fonts is under Accessiblity → Text size.  There is a slider bar for changing the text size from 100% to 225% there. You can try making changes to the ClearType settings.  It's a little bit finer-grained than the others, but it may make the text easier to view on the display.  Run the ClearType Text Tuner (filename: CTTUNE.EXE) and go through the wizard. You may want to do this several times under different lighting conditions or times of the day to figure out what works best for you overall. Lastly, you may want to look into using a dedicated assistive screen technology program from a third-party.  Microsoft provides a Screen Magnifier and a Narrator for text-to-speech, but they provide only basic functionality, and you may find that a third-party program works a lot better.  The pros of this is that third-party assistive technology programs tend to work quite well under Windows; Microsoft has historically worked closely with third-party developers of assistive technologies.  The cons of this are that such tools tend to be on the expensive side, since they are often sold to schools, businesses, or paid for by insurance companies, not individuals. Regards, Aryeh Goretsky  
    • Totally agree with you. I think people, especially on tech sites, need to realize that they’re the minority. Microsoft isn’t going to waste time on things that, in the big picture, don’t matter to the majority.
    • I think a lot of people here are too young to even remember Aqua.
  • Recent Achievements

    • Dedicated
      MadMung0 earned a badge
      Dedicated
    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
    • Week One Done
      VicByrd earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      506
    2. 2
      ATLien_0
      267
    3. 3
      +FloatingFatMan
      257
    4. 4
      Edouard
      203
    5. 5
      snowy owl
      178
  • Tell a friend

    Love Neowin? Tell a friend!