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

    • Indiana Jones and the Great Circle: The Order of Giants DLC launches this September by Pulasthi Ariyasinghe The Xbox Games Showcase gave a look at the next Indiana Jones adventure today. MachineGames showed up with a trailer for the first DLC pack coming to Indiana Jones and the Great Circle: The Order of Giants. Set in Italy, the fresh story will introduce new locations, puzzles, enemies and more. Watch the reveal trailer above. This Indy journey will be taking place during the main campaign and dive deeper into the tribe of giants, Nephilim Order, that players see in the base game. The story will kick off with Indiana Jones offering help to a young priest named Father Ricci, who is attempting to track down a mysterious artifact. The resulting journey expands into this separate storyline that takes the player beyond Vatican City to explore Rome's streets and the crypts beneath it. “One of the most satisfying parts of developing Indiana Jones and the Great Circle was the opportunity to create the Nephilim Order, the secret society of giants formed by descendants of fallen angels working to atone for their ancestral sins,” says Production Director John Jennings. “That story spans thousands of years and this DLC has given us the opportunity to develop further upon their lore and look at other aspects not covered in the initial story campaign. There’s something new and unexpected to tell here for fans of the game, and we can’t wait for people to be able to play it for themselves.” The Indiana Jones and the Great Circle: The Order of Giants DLC will be releasing on September 4, 2025. It will be available on PC, Xbox Series X|S, and PlayStation 5. Premium Edition, Premium Upgrade, Collector’s Edition, and Collector’s Bundle owners will be receiving the DLC for no extra charge at launch.
    • Could we have a desktop version of this lightweight bloat free Windows 11?
    • So they admit that Windows 11 is slow and bloated. Good to know!
    • Real handheld Xbox hardware was canceled, this is just a PC with a screen and controller built-in.
    • Amazon Deal: JBL BAR 1000 7.1.4, BAR 700 5.1 Dolby Atmos wireless subwoofer soundbars by Sayan Sen If you are in the market for an audio system and are after smaller bookshelf speakers delivering highly accurate sound, then take a look at KEF and Polk Audio's Q Concerto Meta and Reserve R200 speakers, respectively, as both of them are up for sale at their lowest ever prices. However, if you are more into shaking your house, which is not possible without a subwoofer, then Samsung has its Q900F, Q800F, and Q600F soundbar systems with wireless subwoofers at the lowest prices. These are the latest 2025 models, and you can take a look at them in this article here. JBL BAR 1000 For those looking for additional options, JBL's BAR 1000 and Bar 700 are also available. The former has hit its lowest ever price too, while the latter is back to its cheapest (purchase links down below). JBL claims that its BAR 1000 model goes as low as 33Hz which is crucial for movie-watching or even some genres of music. The 10-inch subwoofer is rated at 300 watts of RMS power. The total power output of the system is 880 watts at THD (total harmonic distortion) of 1%. JBL BAR 1000 rear view Unlike the 7.1.4 JBL BAR 1000, the BAR 700 is a 5.1 system which means it lacks true Dolby Atmos, but it should still provide an Atmos-like experience. DTS:X is also not supported. The BAR 700 is rated at 620 watts. It is good to see some power ratings, as companies like Samsung, Sonos, Bose, and more tend not to mention them all too often nowadays. Interestingly, both the BAR systems have similarly-specced subwoofers so if bass is what you are looking for and do not care about the Atmos experience so much, you can opt for the BAR 700 too. Get them at the links below: JBL Bar 1000: 7.1.4-Channel soundbar with Detachable Surround Speakers, MultiBeam™, True Dolby Atmos®, and DTS:X®, Black: $799.95 (Shipped and Sold by Amazon US) JBL Bar 700: 5.1-Channel soundbar with Detachable Surround Speakers and Dolby Atmos®, Black: $549.95 (Amazon US) + you also get free 90-day Amazon Music This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
  • Recent Achievements

    • Dedicated
      Epaminombas earned a badge
      Dedicated
    • Veteran
      Yonah went up a rank
      Veteran
    • First Post
      viraltui earned a badge
      First Post
    • Reacting Well
      viraltui earned a badge
      Reacting Well
    • Week One Done
      LunaFerret earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      475
    2. 2
      +FloatingFatMan
      264
    3. 3
      ATLien_0
      236
    4. 4
      snowy owl
      228
    5. 5
      Edouard
      174
  • Tell a friend

    Love Neowin? Tell a friend!