如何使用Python从任何地方控制 PC?
先决条件 - Python中的套接字编程
在这个解决方案中,我们使用套接字编程的概念来建立两台计算机之间的通信。
使用Python进行套接字编程
套接字编程是一种连接网络上的两个系统以相互通信的方式。套接字是为发送和接收数据而构建的端点,它是 IP 地址和端口的组合。我们将导入 socket 模块以在Python中使用 Socket Programming。以下是构建解决方案所需的方法:
Socket 模块中的方法:Method Description socket.socket(). Create sockets. socket.bind() This method bind hostname and portname to socket. socket.listen() This method starts the TCP listener. socket.accept() Accept client connection and wait until the connection arrives. socket.connect() Initiate TCP connection. socket.close() Close the socket.
其他套接字方法:Method Description s.recv() It receives TCP message s.send() It sends TCP message socket.gethostname() It returns hostname
所以我们要开发两个Python程序,一个是master.py (服务器),另一个是slave.py (客户端),使用master.py我们可以控制有slave.py程序的系统。要使用Python从任何地方控制电脑,请按照下面提到的步骤操作:
第一步:在一个终端中创建并执行“master.py”
Python3
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = socket.gethostname()
# Initialize the port
port = 8080
# Bind the socket with port and host
s.bind(('', port))
print("waiting for connections...")
# listening for connections
s.listen()
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
conn.send(command.encode())
print("Command has been sent successfully.")
# receive the confirmation
data = conn.recv(1024)
if data:
print("command received and executed successfully.")
Python3
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initialize the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# receive the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command received".encode())
# you can give batch file as input here
os.system('ls')
第二步:创建并执行“slave.py”是另一个终端
蟒蛇3
import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = "127.0.0.1"
# Initialize the port
port = 8080
# bind the socket with port and host
s.connect((host, port))
print("Connected to Server.")
# receive the command from master program
command = s.recv(1024)
command = command.decode()
# match the command and execute it on slave system
if command == "open":
print("Command is :", command)
s.send("Command received".encode())
# you can give batch file as input here
os.system('ls')
输出: