Perl and Python

August 22, 2008 3:06 PM by Rick Noelle

Today I converted a simple Perl script of mine to Python.  It was pretty easy to do and a good introduction to Python.  The script is meant to run on Linux.  It prompts the user for a command and then runs the command on a list of remote servers and displays the output (using ssh).  For example, if you have 3 remote servers and want to run "uptime" on all of them, it would be easy to do with this script.  I thought I would show the source for both here.  I personally think the Python version looks cleaner and it is easier to read.  I am intrigued by Python because it is a scripted language like Perl but also an object oriented language like Java.  Since I have developed with both Perl and Java, I thought it might be a good match for my skills.  The fact that many of the utilities that come with Red Hat Linux are written in Python is encouraging too.  So anyhow, here they are.

Perl Version

#!/usr/bin/perl
use strict;
use warnings;
use Term::ANSIColor qw(:constants);

print "Command to run remotely: ";
my $cmd = <STDIN>;
chomp($cmd);

my @servers = ('server1','server2','server3');

foreach my $server (@servers)
{
  print BOLD . "$server\$ $cmd\n" . RESET;
  my $out = qx(ssh $server '$cmd');
  print GREEN . $out . RESET;
  print "\n";
}

Python Version

#!/usr/bin/env python

import os

command = raw_input("Command to run remotely: ")

servers = ["server1","server2","server3"]

for server in servers:
  os.system('tput bold')
  print server + "$ " + command
  os.system('tput sgr0')
  os.system('tput setf 2')
  os.system("ssh " + server + " " + command)
  os.system('tput sgr0')</code>

print

Post a Comment