john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

subprocess supress output errors devnull vmrun

import sys
import os
import subprocess
import tempfile

def get_remote_vm_ip( datastore ):
  VMPATH = '[' + DATACENTER + '/' + datastore + '] ' + VM + '/' + VM + '.vmx'   # list2cmdline forces a " if there's a space
  COMMAND_BASE = 'vmrun -T vc -h http://' + HOST + '/sdk -u root -p mypassword'


  params = COMMAND_BASE + ' start'
  cmd = params.split()
  cmd.append( VMPATH )
  with open( os.devnull, 'w' ) as fnull:
    result = subprocess.call( cmd, stdout = fnull, stderr = fnull )  # suppress output and errors

#  result = subprocess.check_call( cmd )  # if non zero return code raise CalledProcessError
 # print subprocess.list2cmdline( cmd )  # preview the command
#  p = subprocess.Popen( cmd, shell = False, stdout = subprocess.PIPE, stderr = subprocess.PIPE )
#  p = subprocess.Popen( cmd, shell = False, stdout =  )
#  out, err = p.communicate()
#  errcode = p.returncode
  # print out


  params= COMMAND_BASE + ' -gu admin -gp mypassword runScriptInGuest '
  cmd = params.split()
  cmd += [ VMPATH, '/bin/sh', '/sbin/ifconfig eth0 > ' + STAGEFILE ]
  with open( os.devnull, 'w' ) as fnull:
    result = subprocess.call( cmd, stdout = fnull, stderr = fnull )


  params= COMMAND_BASE + ' -gu admin -gp mypassword copyFileFromGuestToHost'
  cmd = params.split()
  cmd += [ VMPATH, STAGEFILE, STAGEFILE ]
  with open( os.devnull, 'w' ) as fnull:
    result = subprocess.call( cmd, stdout = fnull, stderr = fnull )


  content = None
  with open( STAGEFILE ) as f:
    content = f.read()

  os.unlink( STAGEFILE )  # clean up the temporary file

  if content:
    contents = content.split()
    for item in contents:
      if item.startswith( 'addr:' ):
        temp = item.split( ':' )
        ip = temp[1]     # addr:1.2.3.4 became [ 'addr:', '1.2.3.4' ]
        return  ip.strip()

  return None



if __name__ == '__main__':

  SCRIPTNAME = sys.argv[0]
  if len( sys.argv ) < 2:
    print "ERROR: wrong number of arguments, correct usage: python " + SCRIPTNAME + " vmname"
    sys.exit( 1 )

  VM = sys.argv[1]
  STAGEFILE = '/tmp/' + str( os.getpid() ) + '.myip'
  HOST = 'vc0.example.com'
  DATACENTER = 'datacenter-2'


  # params = COMMAND_BASE + ' list'
  # cmd = params.split()
  # print subprocess.list2cmdline( cmd )  # preview the command
  # result = subprocess.check_call( cmd )  # if non zero return code raise CalledProcessError

  # DATASTORE = 'localtb0'
  try:
    print get_remote_vm_ip( 'localtb0' )

  except Exception as error:
#    print 'ERROR, maybe unable to find ' + VM + ' on localtb0', error
    print get_remote_vm_ip( 'datastore1' )

  • « phpunit json file kohana example
  • Rm replacement trash cli »

Published

Sep 27, 2013

Category

python

~270 words

Tags

  • devnull 1
  • errors 6
  • output 3
  • python 180
  • subprocess 2
  • supress 1
  • vmrun 3