SoFunction
Updated on 2024-11-10

Summary of Python remote control methods for Windows servers

I. Preparatory work

opening short story

The story begins with a cat.
Ming is a Python developer who has a smart kitten named Pippi. One day, Ming is deploying a project on his server when he suddenly remembers that he forgot to feed Pippi. But he doesn't want to leave his computer to feed the cat, so he has an idea: how nice it would be if he could remotely control the automatic feeder at home!

So he decided to use Python to remotely control a Windows server at home, connected to an automatic feeder. After some hard work, Ming not only succeeded in achieving this goal, but also discovered the infinite possibilities of Python remote control of Windows servers.

preliminary

Before we officially begin, we need to do some preparation. First, make sure that your Windows server has Remote Desktop Services (RDP) enabled. Next, we need to install some necessary libraries:

pip install pywinrm paramiko pypsexec

Each of these libraries is used for different remote control methods, and we'll cover them one by one in subsequent examples.

II. Programming Examples

Example 1: Using PyWinRM to Execute Commands Remotely

PyWinRM is a powerful library that allows us to execute commands remotely via the WinRM (Windows Remote Management) protocol. Let's see how to use it to execute a simple command on a remote server:

import winrm

# Connect to a remote Windows server
session = ('http://<your server IP>:5985/wsman', auth=('username', 'password'))

# Execute commands
result = session.run_cmd('ipconfig')

# Printout
print(result.std_out.decode('utf-8'))

This example is very simple, but actually very powerful. We set up a session with a remote server and then used the run_cmd method to run the ipconfig command on the server and print the output. You can try a different command and see what happens.

Github project address:

/diyan/pywinrm

Example 2: SSH Connection with Paramiko

Although Windows does not have an SSH service by default, you can install OpenSSH Server to enable SSH connections. Once installed, we can use Paramiko for remote control:

import paramiko

# Create an SSH client
client = ()
client.set_missing_host_key_policy(())

# Connect to the remote server
('Your server IP', username='Username', password='Password')

# Execute commands
stdin, stdout, stderr = client.exec_command('ipconfig')

# Printout
print(().decode())

# Close the connection
()

With this example, we can see that SSH connections with Paramiko are also very simple. Simply create an SSH client, connect to the remote server, and then execute the command and get the output. This method is especially useful for developers who are used to using SSH.

Github project address:

/paramiko/paramiko

Example 3: Using PsExec to Perform Advanced Tasks

PsExec is a command-line tool that lets you execute processes on a remote computer and interact with them. The pypsexec library makes it easy to use PsExec in Python:

from  import Client

# Create a PsExec client
client = Client('Your server IP', username='Username', password='Password')

# Connect to the remote server
()

# Start the service
client.create_service()

# Execute commands
stdout, stderr, rc = client.run_executable('', arguments='/c ipconfig')

# Printout
print(())

# Shut down the service and disconnect
client.remove_service()
()

This example shows how to execute commands on a remote server and get the output via PsExec. PsExec can not only execute simple commands, but also run complex scripts and applications.

Github project address:

/jborean93/pypsexec

Example 4: Timed Tasks and Automation

If you want to perform certain tasks on a remote server at regular intervals, such as cleaning up log files or backing up data, you can combine Python's sched module with the previous remote execution methods to implement automated scripts:

import time
import sched
import winrm

# Create schedulers
scheduler = (, )

# Define tasks
def clear_logs():
    session = ('http://<your server IP>:5985/wsman', auth=('username', 'password'))
    result = session.run_cmd('del C:\\logs\\*.log')
    print(result.std_out.decode('utf-8'))

# Scheduled tasks to be performed every other day
(86400, 1, clear_logs)

# Start running the scheduler
()

This example shows how to schedule a timed task using a scheduler. We define a clear_logs function that deletes log files on a remote server and use the scheduler to perform this task every other day.

Example 5: File transfer and management

Remote control is not only about executing commands, but file transfer is also a very important part of it. We can use Paramiko for uploading and downloading files:

import paramiko
from scp import SCPClient

# Create an SSH client
client = ()
client.set_missing_host_key_policy(())

# Connect to the remote server
('Your server IP', username='Username', password='Password')

# Create SCP clients
scp = SCPClient(client.get_transport())

# Upload files
('local_file.txt', 'remote_file.txt')

# Download file
('remote_file.txt', 'local_file.txt')

# Close the connection
()
()

With this example, we can see that it is very convenient to use SCP (Secure Copy Protocol) for file transfer. We can upload local files to the remote server and also download remote files locally.

Example 6: Graphical interface and remote desktop control

If you wish to implement remote desktop functionality in Python, you can use the pyautogui library to control the remote server's graphical interface:

import pyautogui

# Analog keys
('Hello World!')
('enter')

# Simulate mouse clicks
(100, 100)

# Screenshots
screenshot = ()
('')

This example shows how to use PyAutoGUI to simulate keyboard and mouse operations, as well as taking screenshots. Although this method is not really remote desktop control, it can be used to implement some simple GUI operations.

III. Summary

With these few examples, we can see that there are various ways to remotely control a Windows server with Python. From simple command execution to complex GUI operations, there are tools and methods for whatever your needs are.

I hope this article has inspired you to find more interesting applications in the world of Python. Whether it's automating a task or solving an everyday problem, Python will always surprise you.

Finally, back to our story. Xiaoming successfully controlled the automatic feeder in his house through Python, which not only solved Pippi's feeding problem, but also allowed him to take an important step forward in the path of programming. Maybe in the near future, he will use Python to realize more whimsical ideas.

The above is a summary of the method of Python remote control Windows server details, more information about Python remote control Windows please pay attention to my other related articles!