controlVMnetworkstate.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/python
  2. import os
  3. import sys
  4. import time
  5. import subprocess
  6. import random
  7. bindir='/usr/bin'
  8. sys.path.append(bindir)
  9. def input_sel(prompt,max_,selectionoption):
  10. # let the user choose the VM and verify selection
  11. while True:
  12. try:
  13. print ('Please select from the list of running VMs\n\n'+'\n'.join(selectionoption))
  14. userin = int(raw_input(prompt))
  15. except ValueError:
  16. print('\nThat was not a number\n\n')
  17. continue
  18. if userin > max_:
  19. print('\nInput must be less than or equal to {0}.\n\n'.format(max_))
  20. elif userin < 1:
  21. print('\nInput must be greater than or equal to 1\n\n')
  22. else:
  23. return userin
  24. def statustext(result):
  25. if result == 0:
  26. status = 'OK'
  27. else:
  28. status = 'Failed'
  29. return status
  30. def controlvmnetworkstate():
  31. try:
  32. offtime = 600
  33. ontime = 14
  34. vmdict={}
  35. vmlist=[]
  36. executable = os.path.join(bindir, 'VBoxManage')
  37. #retrieve a list of all running VMs
  38. runningvms= subprocess.check_output('%s list runningvms' %executable,shell=True).splitlines()
  39. if len(runningvms) != 0:
  40. for n in range(0, len(runningvms)):
  41. vmlist.append('%s: %s' %(n+1,runningvms[n].rsplit(' ',1)[0].strip('"')))
  42. vmdict[n+1]=runningvms[n].rsplit(' ',1)[-1]
  43. usersel=input_sel('\nEnter the number of the VM: ',len(runningvms),vmlist)
  44. else:
  45. print('Can not retrieve list of running VMs')
  46. sys.exit()
  47. vmuuid=vmdict[usersel]
  48. while True:
  49. offtime = random.randint(60, 90)
  50. ontime = random.randint(10, 90)
  51. timenow = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
  52. on = subprocess.call('%s controlvm %s setlinkstate1 on' %(executable,vmuuid),
  53. shell=True)
  54. status=statustext(on)
  55. print ('%s: Plug Network cable into VM %s for %ds: %s' % (timenow, runningvms[usersel-1].rsplit(' ',1)[0].strip('"'),ontime, str(status)))
  56. time.sleep(ontime)
  57. timenow = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
  58. off = subprocess.call('%s controlvm %s setlinkstate1 off' %(executable,vmuuid),
  59. shell=True)
  60. status = statustext(off)
  61. print ('%s: Unplug Network cable from VM %s for %ds: %s' % (timenow, runningvms[usersel-1].rsplit(' ',1)[0].strip('"'),offtime, str(status)))
  62. time.sleep(offtime)
  63. except KeyboardInterrupt:
  64. sys.exit('\nUser Interrupt')
  65. except Exception as e:
  66. print("Error in %s in function %s: %s" % (__name__, sys._getframe().f_code.co_name, e.message))
  67. if __name__ == "__main__":
  68. sys.exit(controlvmnetworkstate())