How to Execute Shell Commands in a Remote Machine in Python?
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.
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.
- Create Mater 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:
Slave machine script:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course