- 1 year ago
User input PC name inserted into Windows CMD shutdown command via Python
To insert the user input PC name into a Windows CMD shutdown command using Python, you can use the subprocess
module to execute the command. Here's a step-by-step guide to achieve this:
- Use the
input()
function to get the PC name from the user:
pythonpc_name = input("Enter the PC name: ")
- Construct the shutdown command with the user-provided PC name:
pythonshutdown_cmd = f"shutdown /s /m \\\\{pc_name}"
In this example, we're using the /s
flag for the shutdown operation and the /m
flag to specify the remote computer. The \\
is used to escape the backslash character in the computer name.
- Execute the shutdown command using
subprocess.run()
:
pythonimport subprocess
try:
subprocess.run(shutdown_cmd, check=True)
except subprocess.CalledProcessError as e:
print(f"Error executing the shutdown command: {e}")
else:
print(f"Shutdown command for {pc_name} sent successfully.")
The subprocess.run()
function runs the shutdown command in the Windows CMD and waits for it to complete. The check=True
parameter will raise an exception if the command returns a non-zero exit code (indicating an error).
Now, when you run the Python script, it will prompt you to enter the PC name, and then it will execute the shutdown command on the specified PC.
Please note that this code assumes you have the necessary permissions to shut down remote computers. If you encounter any permission issues, make sure you have the appropriate privileges to perform remote shutdowns on the target PC.