Skip to content
Advertisement

Execute a command on Remote Machine in Python

I am writing a program in python on Ubuntu, to execute a command ls -l on RaspberryPi, connect with Network.

Can anybody guide me on how do I do that?

Advertisement

Answer

Sure, there are several ways to do it!

Let’s say you’ve got a Raspberry Pi on a raspberry.lan host and your username is irfan.

subprocess

It’s the default Python library that runs commands.
You can make it run ssh and do whatever you need on a remote server.

scrat has it covered in his answer. You definitely should do this if you don’t want to use any third-party libraries.

You can also automate the password/passphrase entering using pexpect.

paramiko

paramiko is a third-party library that adds SSH-protocol support, so it can work like an SSH-client.

The example code that would connect to the server, execute and grab the results of the ls -l command would look like that:

JavaScript

fabric

You can also achieve it using fabric.
Fabric is a deployment tool which executes various commands on remote servers.

It’s often used to run stuff on a remote server, so you could easily put your latest version of the web application, restart a web-server and whatnot with a single command. Actually, you can run the same command on multiple servers, which is awesome!

Though it was made as a deploying and remote management tool, you still can use it to execute basic commands.

JavaScript

It’s like typing cd / and ls -l in the remote server, so you’ll get the list of directories in your root folder.

Then run in the shell:

JavaScript

It will prompt for an server address:

JavaScript

A quick note: You can also assign a username and a host right in a fab command:

JavaScript

Or you could put a host into the env.hosts variable in your fabfile. Here’s how to do it.


Then you’ll be prompted for a SSH password:

JavaScript

And then the command will be ran successfully.

JavaScript
Advertisement