class PrepareIso(QtWidgets.QDialog): """ Class to manage the prepare_iso dialog... @author: Roy Nielsen """ def __init__(self, conf, parent=None): """ Initialization method... @author: Roy Nielsen """ super(PrepareIso, self).__init__(parent) self.ui = Ui_PrepareMacosImage() self.ui.setupUi(self) ##### # initialization of class variables. self.conf = conf self.conf.loggerSelf() self.logger = self.conf.getLogger() #self.logger = self.conf.get_logger() self.logger.log(lp.DEBUG, str(self.logger)) self.runWith = RunWith(self.logger) self.libc = getLibc(self.logger) ##### # Handle button box self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.reject) self.ui.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.accept) ##### # Handle other buttons self.ui.bOpenInstallerApp.clicked.connect(self.openInstallerApp) self.ui.bPrepareIso.clicked.connect(self.prepareIso) ##### # Set up collection of administrator credentials self.adminCreds = AdministratorCredentials(self.conf) self.adminCreds.creds.connect(self.setUserAndPass) ##### # Instanciate a PackerJsonHandler self.pjh = PackerJsonHandler(self.logger) def setUserAndPass(self, user="", password=""): ''' ''' self.username = user.strip() self.password = password.strip() def openInstallerApp(self): ''' ''' self.installerApp = "" fname, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', "/Applications", "Install*.app") if not os.path.isdir(fname) or not re.match(".*\.app$", fname): ##### # Throw an error QtWidgets.QMessageBox.critical(self, "Error", "...Not a valid installer Application...", QtWidgets.QMessageBox.Ok) else: self.ui.leInstallAppLocation.setText(fname) self.installerApp = re.sub(" ", "\\\\\ ", fname.strip()) #self.installerApp = fname.strip() self.logger.log(lp.DEBUG, "installerApp: " + str(self.installerApp)) def prepareIso(self): ''' The commands to create the disk image packer can use are: cd ~boxcutter/macos sudo prepare_iso/prepare_iso.sh /Applications/Install\ OS\ X\ El\ Capitan.app dmg "do shell script \"/Applications/stonix4mac.app/Contents/Resources/stonix.app/Contents/MacOS/stonix > /dev/null 2>&1 &\" with administrator privileges" ''' adminCredsReturns = self.adminCreds.exec_() self.adminCreds.raise_() returnDir = os.getcwd() os.chdir(self.conf.getRepoRoot() + "/macos") print os.getcwd() scriptPath = self.conf.getRepoRoot() + "/macos/prepare_iso/prepare_iso.sh" installerApp = re.sub(r"\\", r"", self.installerApp) dmgPath = "/Contents/SharedSupport/InstallESD.dmg" subcmd = "%s %s%s dmg"%(scriptPath, self.installerApp, dmgPath) self.logger.log(lp.DEBUG, "Subcmd: " + str(subcmd)) #subcmd = re.sub(r"\\", r"", subcmd) #self.logger.log(lp.DEBUG, "Subcmd: " + str(subcmd)) cmd = ["/usr/bin/osascript", "-e", "do shell script \"{0}\" user name \"{1}\" password \"{2}\" with administrator privileges".format(subcmd, self.username, self.password)] self.runWith.setCommand(cmd, myshell=False) output, error, retcode = self.runWith.waitNpassThruStdout() self.logger.log(lp.DEBUG, "out: " + str(output)) self.logger.log(lp.DEBUG, "err: " + str(error)) self.logger.log(lp.DEBUG, "retcode: " + str(ord(retcode))) dmgName = "" ##### # Get the (\w+_InstallESD_\w+\.dmg) name out of the output to write it # into the appropriate varfile compile_dmg_name = re.compile(".*(OSX_InstallESD_[\d+\.]+_\w+\.dmg).*") #dmgName = "" if not re.search("\n", output): matcher = "\r" else: matcher = "\n" for line in output.split(matcher): try: if not line: continue self.logger.log(lp.DEBUG, str(line)) search = compile_dmg_name.search(line) dmgName = search.group(1) break except (AttributeError, KeyError), err: pass # self.logger.log(lp.DEBUG, traceback.format_exc(err)) if not dmgName: compile_dmg_name = re.compile(".*_(InstallESD_[\d+\.]+_\w+\.dmg).*") if not re.search("\n", error): matcher = "\r" else: matcher = "\n" for line in error.split(matcher): try: print str(line) if not line: continue self.logger.log(lp.DEBUG, str(line)) search = compile_dmg_name.search(line) dmgName = search.group(1) break except (AttributeError, KeyError), err: print "Could not grok, Jim..." pass
myout, myerr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=None).communicate() except OSError, err: print traceback.format_exc(err) print str(err) else: sys.stdout.flush() print "myout: " + str(myout) print "\n" print "myerr: " + str(myerr) logger = CyLogger(debug_mode=True) logger.initializeLogs() rw = RunWith(logger) cmd = [ "/usr/bin/osascript", "-e", '\'do shell script "{0}" user name "{1}" password "{2}" with administrator privileges\'' .format(subcmd, user, userpass) ] rw.setCommand(cmd) rw.waitNpassThruStdout() for line in rw.getStdout().split("\n"): print line + "\n"
class test_run_commands(unittest.TestCase): """ """ @classmethod def setUpClass(self): """ """ ##### # Set up logging self.logger = CyLogger(debug_mode=True) self.logger.initializeLogs() self.rw = RunWith(self.logger) ##### # Start timer in miliseconds self.test_start_time = datetime.now() @classmethod def tearDownClass(self): """ """ pass def test_RunCommunicateWithBlankCommand(self): self.rw.__init__(self.logger) self.assertRaises(SetCommandTypeError, self.rw.setCommand, "") self.assertRaises(SetCommandTypeError, self.rw.setCommand, []) self.assertRaises(SetCommandTypeError, self.rw.setCommand, None) self.assertRaises(SetCommandTypeError, self.rw.setCommand, True) self.assertRaises(SetCommandTypeError, self.rw.setCommand, {}) def test_setCommand(self): self.rw.__init__(self.logger) command = ['/bin/ls', 1, '.'] self.assertRaises(SetCommandTypeError, self.rw.setCommand, [command]) def test_communicate(self): """ """ self.rw.__init__(self.logger) self.logger.log(lp.DEBUG, "=============== Starting test_communicate...") self.rw.setCommand('/bin/ls /var/spool', myshell=True) _, _, retval = self.rw.communicate(silent=False) self.assertEquals( retval, 0, "Valid [] command execution failed: " + '/bin/ls /var/spool --- retval: ' + str(retval)) self.rw.setCommand(['/bin/ls', '-l', '/usr/local']) _, _, retval = self.rw.communicate(silent=False) self.assertEquals( retval, 0, "Valid [] command execution failed: " + '/bin/ls /var/spool --- retval: ' + str(retval)) self.logger.log(lp.DEBUG, "=============== Ending test_communicate...") def test_wait(self): """ """ self.rw.__init__(self.logger) self.logger.log(lp.DEBUG, "=============== Starting test_wait...") self.rw.setCommand('/bin/ls /var/spool') _, _, retval = self.rw.communicate(silent=False) self.assertEquals( retval, 0, "Valid [] command execution failed: " + '/bin/ls /var/spool --- retval: ' + str(retval)) self.rw.setCommand(['/bin/ls', '-l', '/usr/local']) _, _, retval = self.rw.communicate(silent=False) self.assertEquals( retval, 0, "Valid [] command execution failed: " + '/bin/ls /var/spool --- retval: ' + str(retval)) self.rw.setCommand(['/bin/ls', '/1', '/']) _, _, retcode = self.rw.wait() self.logger.log(lp.WARNING, "retcode: " + str(retcode)) if sys.platform == 'darwin': self.assertEquals(retcode, 1, "Returncode Test failed...") else: self.assertEquals(retcode, 2, "Returncode Test failed...") def test_waitNpassThruStdout(self): """ """ self.rw.__init__(self.logger) self.rw.setCommand(['/bin/ls', '-l', '/usr/local']) _, _, retval = self.rw.waitNpassThruStdout() self.assertEquals( retval, 0, "Valid [] command execution failed: " + '/bin/ls /var/spool --- retval: ' + str(retval)) self.rw.setCommand(['/bin/ls', '/1', '/']) _, _, retval = self.rw.waitNpassThruStdout() if sys.platform == 'darwin': self.assertEquals(retval, 1, "Returncode Test failed...") else: self.assertEquals(retval, 2, "Returncode Test failed...") def test_timeout(self): """ """ self.rw.__init__(self.logger) if os.path.exists("/sbin/ping"): ping = "/sbin/ping" elif os.path.exists('/bin/ping'): ping = "/bin/ping" self.rw.setCommand([ping, '8.8.8.8']) startTime = time.time() self.rw.timeout(3) elapsed = (time.time() - startTime) self.assertTrue(elapsed < 4, "Elapsed time is greater than it should be...") def test_runAs(self): """ """ pass def test_liftDown(self): """ """ pass def test_runAsWithSudo(self): """ """ pass def test_runWithSudo(self): """ """ pass def test_getecho(self): """ """ pass def test_waitnoecho(self): """ """ pass def test_RunThread(self): """ """ pass def test_runMyThreadCommand(self): """ """ pass