rudimentary ssh cmd wrapper with 1 small (and hopefully obvious) bug

John Hunter jdhunter at
Mon Mar 3 04:59:03 CET 2003

1) payload = string.join(sys.argv[1:])

   Strings have methods, so you can do ' '.join(sys.argv[1:]) and not
   have to 'import string'

       while 1:
          line = output.readlines()
          if not line: break                            <<<<<<<    is this
   This is confusing to me.  The typical idiom is

   while 1:
      line = output.readline()   #reads only one line, not all
      on_some_condition(): break

   But in your case, you just want to return all the output, so is probably what you want.

3) To test against the empty string, you may want to consider

   if len(line.strip())==0

  strip removes spaces and newlines

4) command_response = string.join(line[:]).  See 1

5) node_in_caps = string.upper(machine)

   node_in_caps = machine.upper()

6) if listening_status == 1:

  can be simplified to 'if listening_status:'

Here, then, is a version of the script with these changes:

  import os, sys
  def the_command():
      payload = ' '.join(sys.argv[1:])
      sshcmd = 'ssh -1 -o StrictHostKeyChecking=no -l root ' + payload
      output = os.popen('{ ' + sshcmd + '; } 2>&1', 'r')

  machine = sys.argv[1]
  node_in_caps = machine.upper()

  print node_in_caps, the_command()

Note if you are feeling exceptionally pithy, you are perfectly welcome
to shorten 'the_command' to the one-liner

def the_command():
    return os.popen('{ ssh -1 -o StrictHostKeyChecking=no -l root %s; } 2>&1' %
		    ' '.join(sys.argv[1:])).read()

Whether this is readable and good python style is debatable.


More information about the Python-list mailing list