How to Execute Shell Commands in a Remote Machine in Python?
Last Updated :
28 Sep, 2022
Running shell commands on a Remote machine is nothing but executing shell commands on another machine and as another user across a computer network. There will be a master machine from which command can be sent and one or more slave machines that execute the received commands.
Getting Started
We will be using Websocket protocol to send shell commands to the slave machine and receive the output of commands. Websocket offers full-duplex communication over a single TCP connection in real-time. The Python provides a subprocess library an in-built library, that allows a new process to start and connect to their input, output, and error pipes. getoutput method in the subprocess library executes the command and returns the output, if an error occurs it also returns the errors.
You will easily understand its working with approach and implementation. So let’s begin.
Approach:
- Create Master machine script.
- Create a socket connection and listen for the slave machine socket.
- Accept the connection once the connection request is made.
- Use the input method to get a command from the user and encode it.
- Then use the socket connection to send the shell command.
- Then receive the output of the command.
- Create a Slave machine script.
- Create a Socket and connect it to the Master machine socket.
- Receive the command from the master.
- Execute the command with the get output method from the subprocess module.
- getoutput method returns the output of the executed command.
- Encode the output and send it to the master machine.
Master machine script:
Python3
import socket
master = socket.socket()
host = "0.0.0.0"
port = 8080
master.bind((host, port))
master.listen( 1 )
slave, address = master.accept()
while True :
print ( ">" , end = " " )
command = input ()
slave.send(command.encode())
if command = = "exit" :
break
output = slave.recv( 5000 )
print (output.decode())
master.close()
|
Output:
Slave machine script:
Python3
import socket
import subprocess
slave = socket.socket()
host = "192.168.43.160"
port = 8080
slave.connect((host, port))
while True :
command = slave.recv( 1024 ).decode()
print (command)
if command = = "exit" :
break
output = "output:\n"
output + = subprocess.getoutput(command)
slave.send(output.encode())
slave.close()
|
Output:
Share your thoughts in the comments
Please Login to comment...