How to control PC from anywhere using Python?
Prerequisite – Socket programming in Python
In this solution, we use the concept of Socket Programming for establishing communication between two computers.
Socket Programming in Python
Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the endpoints built for sending and receiving data and it is a combination of IP address and port. We will import the socket module to use Socket Programming in Python. The following are the methods required to build the solution:
Methods in Socket Module:
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. |
Other Socket Methods:
Method |
Description |
s.recv() |
It receives TCP message |
s.send() |
It sends TCP message |
socket.gethostname() |
It returns hostname |
So we have to develop two python programs one is master.py (server)and another is slave.py (client), using master.py we can control the system having slave.py program. To control the pc from anywhere using python please the follow the step mentioned below:
Step 1: Create and Execute the “master.py” in one terminal
Python3
import time
import socket
import sys
import os
s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind(('', port))
print ( "waiting for connections..." )
s.listen()
conn, addr = s.accept()
print (addr, "is connected to server" )
command = input ( str ( "Enter Command :" ))
conn.send(command.encode())
print ( "Command has been sent successfully." )
data = conn.recv( 1024 )
if data:
print ( "command received and executed successfully." )
|
Step 2: Create and Execute the “slave.py” is another terminal
Python3
import time
import socket
import sys
import os
s = socket.socket()
host = "127.0.0.1"
port = 8080
s.connect((host, port))
print ( "Connected to Server." )
command = s.recv( 1024 )
command = command.decode()
if command = = "open" :
print ( "Command is :" , command)
s.send( "Command received" .encode())
os.system( 'ls' )
|
Output:
terminal running master.py
terminal running slave.py
Last Updated :
12 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...