Pythonista - Remote Command Execution21 Jul 2013
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 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 '== RCE SCRIPT INITIATED ==' print 'Importing modules...' import paramiko import console print 'Modules imported.' print 'Configuring parameters...' strComputer = 'myserver.somedomain.org' 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.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 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 stdout.read() print 'Command execution complete.' #Close the connection print 'Closing SSH connection...' client.close() print 'SSH connection closed.' print '== RCE SCRIPT COMPLETE =='
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.