Pythonista - Remote Command Execution

Pythonista is a Python based IDE for iOS and has formed the basis for finally getting around to teaching myself Python. I’m still in the earliest stages of getting to grips with Python but I thought I’d share one of my most useful scripts thus far. One to execute a remote command on a server using SSH.

The Script

The script has four optional settings.

  • strComputer for the IP address or domain address of the server.
  • stUser for the user ID to connect to the server with.
  • strPwd for the password associated with the user ID.
  • strCommand for the command to execute.

If any of these settings are not set explicitly within the script (i.e. they are set as ‘’) they are prompted for when the script is run. Personally I never store the password and type it in each time, but you can of course configure the script however you need for your specific purposes.


print 'Importing modules...'
import paramiko
import console
print 'Modules imported.'

print 'Configuring parameters...'
strComputer = ''
strUser = 'myuserid'
strPwd = ''
strCommand = 'uptime'
print 'Parameters configured.'

print 'Verifying parameters...'
if not strComputer:
    strComputer = raw_input('Enter computer name/IP address:')
if not strUser:
    strUser = raw_input('Enter user name:')
if not strPwd:
    strPwd = console.secure_input('Enter password:')
if not strCommand:
    strCommand = raw_input('Enter command:')
print 'Parameters verified.'

# Initialise connection
print 'Initiating SSH connection...'
client = paramiko.SSHClient()
client.connect(hostname=strComputer, username=strUser, password=strPwd)
print 'SSH connection established with ' + strComputer + ' as user ' + strUser + '.'

print 'Executing command [' + strCommand + ']...'
stdin, stdout, stderr = client.exec_command(strCommand)
print 'Command execution complete.'

#Close the connection
print 'Closing SSH connection...'
print 'SSH connection closed.'


Example Commands

In many cases where you want to execute several commands I would suggest using a dedicated SSH client (e.g. Server Auditor), but there are occasions where logging in to run just one command (or script) is tedious in such a client. In these cases a dedicated Python script can be just the thing - even more so if you pair it up with something like Launch Center Pro.

Some examples of (BASH) commands I have preset to run on various servers are:

  • uptime ; reboot - display uptime and reboot server.
  • pmset sleepnow - put OS X machine to sleep (power saving).
  • last - user history (including logged in users).
  • df ; free - disk and memory utilisation.
Author: Stephen Millard
Tags: | python | mobile |

Buy me a coffeeBuy me a coffee

Related posts that you may also like to read