Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to control PC from anywhere using Python?

  • Difficulty Level : Easy
  • Last Updated : 12 Jul, 2021

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:

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:

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 (server)and another is (client), using we can control the system having program. To control the pc from anywhere using python please the follow the step mentioned below:

Step 1: Create and Execute the “” in one terminal


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
# accepting the incoming connections
conn, addr = s.accept()
print(addr, "is connected to server")
# take command as input
command = input(str("Enter Command :"))
print("Command has been sent successfully.")
# receive the confirmation
data = conn.recv(1024)
if data:
    print("command received and executed successfully.")

Step 2: Create and Execute the “” is another terminal


import time
import socket
import sys
import os
# Initialize s to socket
s = socket.socket()
# Initialize the host
host = ""
# 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


server terminal

terminal running

client terminal

terminal running

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!