예제 #1
0
    def __init__(self, args, message_level="debug", parent=None) :
        """
        Initialization method
        
        @author: Roy Nielsen
        """
        super(AdministratorCredentials, self).__init__(parent)
        self.ui = Ui_AdministratorCredentials()
        self.ui.setupUi(self)
        self.args = args
        
        self.message_level = message_level
        self.username = ""
        self.password = ""
        self.cmd = ""
        self.tmpDir = ""

        self.progress_bar = QProgressDialog()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(0)
        self.progress_bar.setLabelText("Checking Password...")

        #####
        # Set up signals and slots
        self.connect(self.ui.authUserButton, SIGNAL("clicked()"), self.isPassValid)
        self.connect(self.ui.cancelButton, SIGNAL("clicked()"), self.rejectApp)

        #####
        # Commented out putting in the current logged in user as the default
        # user - to make more Mac-like
        #user = getpass.getuser()
        #self.ui.adminName.setText(user)

        log_message("Finished initializing AdministratorCredentials Class...", "debug", self.message_level)
예제 #2
0
def runWithTimeout(command, timout_sec, message_level="normal") :
    """
    Run a command with a timeout - return:
    Returncode of the process
    stdout of the process
    stderr of the process
    timout - True if the command timed out
             False if the command completed successfully
    
    inspiration from: http://stackoverflow.com/questions/1191374/subprocess-with-timeout
    
    @author: Roy Nielsen
    """
    if isinstance(command, list) :
        if not command :
            log_message("Cannot run a command with a command list that is empty...", "normal", message_level)
            return False, False, False, False
    elif isinstance(command, basestring) :
        if re.match("^\s*$", command) :
            log_message("Cannot run a command with a command that is an empty string...", "normal", message_level)
            return False, False, False, False

    proc = Popen(command, stdout=PIPE, stderr=PIPE)
    
    timeout = {"value" : False}
    timer = threading.Timer(timout_sec, kill_proc, [proc, timeout])
    timer.start()
    stdout, stderr = proc.communicate()
    timer.cancel()

    return proc.returncode, stdout, stderr, timeout["value"]
예제 #3
0
 def __partition(self):
     """
     Not implemented on the Mac
     
     """
     success = False
     size = int(self.diskSize) / (2 * 1024)
     cmd = [
         self.diskutil, "partitionDisk", self.myRamdiskDev,
         str(1), "MBR", "HFS+", "ramdisk",
         str(size) + "M"
     ]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("retval: \"\"\"" + str(retval).strip() + "\"\"\"", "debug",
                 self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug",
                 self.message_level)
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("Success: " + str(success) + " in __format", "debug",
                 self.message_level)
     return success
예제 #4
0
def detach(device=" ", message_level="normal"):
    """
    Eject the ramdisk
    Detach (on the mac) is a better solution than unmount and eject 
    separately.. Besides unmounting the disk, it also stops any processes 
    related to the mntPoint

    @author: Roy Nielsen
    """
    success = False
    if not re.match("^\s*$", device):
        cmd = ["/usr/bin/hdiutil", "detach", device]
        retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
        if not reterr:
            success = True

        log_message("*******************************************", "debug",
                    message_level)
        log_message("retval: " + re.escape(str(retval).strip("\"")), "debug",
                    message_level)
        log_message("reterr: " + re.escape(str(reterr).strip("\"")), "debug",
                    message_level)
        log_message("*******************************************", "debug",
                    message_level)
        log_message("Success: " + str(success) + " in eject", "debug",
                    message_level)
    else:
        raise Exception("Cannot eject a device with an empty name..")
    return success
예제 #5
0
def checkIfUserIsLocalAdmin(user="", message_level="normal") :
    """
    Check the local directory and see if a user is a local admin on the system.

    command:
    dscl . read /Groups/admin GroupMembership
    
    above command returns:
    GroupMembership: root rsn
    
    Author: Roy Nielsen
    """

    userFound = False

    if not re.match("^\s*$", username) :

        dsclCommand = ["/usr/bin/dscl", ".", "read", "/Groups/admin", "GroupMembership"]

        log_message("About to run command: " + " ".join(dsclCommand), "debug", message_level)

        (retval, reterr) = system_call_retval(dsclCommand, message_level)
        
        #print "Retval: \"" + retval + "\""
        
        if retval :
            users = retval.split()[1:]
            #print str(users)
            for user in users :
                if re.match("^%s$"%user, username) :
                    userFound = True
                    break

    return userFound
예제 #6
0
def doesRestorePartitionExist(message_level="normal") :
    """
    Checks for the existence of the restore partition
    
    Author: Roy Nielsen
    """
    log_message("Start checking for restore partition...", "debug", message_level)
    doesItExist = False
    
    #####
    # Get valid users on the system, put them in a list
    cmd = ["/usr/sbin/diskutil", "list", "/dev/disk0"]
    
    (retval, reterr) = system_call_retval(cmd, message_level)
    
    partitions = retval.split("\n")
    
    for partition in partitions :
        print partition
        if re.match("^\s+\S+\s+\S+\s+Recovery HD\s+\S+\s+\S+\s+\S+", partition) :
            doesItExist = True
            break
        else :
            continue
    log_message("Finishing check for restore parition with: " + str(doesItExist), "debug", message_level)
    return doesItExist
예제 #7
0
def getResourcesDir() :
    """ 
    Get the full path to the Resources directory of the current app 
    
    Author: Roy Nielsen
    """
    # Gets the <app-path>/Contents/MacOS full path
    selfdir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0])))
    resource_dir = ""

    parents = selfdir.split("/")

    # Remove the "MacOS" dir from the list
    parents.pop()

    # Append "Contents" & "cmu" to the end of the list
    #parents.append("Contents")
    
    # Append "Resources" & "cmu" to the end of the list
    parents.append("Resources")
    
    # Join up the directory with slashes
    resource_dir = "/".join(parents)

    log_message("resources dir: " + str(resource_dir))

    return resource_dir
예제 #8
0
 def detachRamdisk(self, device, message_level="normal"):
     if detach(device, message_level):
         log_message("Successfully detached disk: " + str(device).strip(),
                     "verbose", message_level)
     else:
         log_message("Couldn't detach disk: " + str(device).strip())
         raise Exception("Cannot eject disk: " + str(device).strip())
예제 #9
0
    def setUp(self):
        """
        Initializer
        """
        self.setMessageLevel("normal")

        self.subdirs = ["two", "three" "one/four"]

        """
        Set up a ramdisk and use that random location as a root to test the
        filesystem functionality of what is being tested.
        """
        #Calculate size of ramdisk to make for this unit test.
        size_in_mb = 100
        self.mnt_pnt_requested = ""

        self.success = False
        self.mountPoint = False
        self.ramdiskDev = False
        self.mnt_pnt_requested = False

        # get a ramdisk of appropriate size, with a secure random mountpoint
        my_ramdisk = RamDisk(str(size_in_mb), self.mnt_pnt_requested, self.message_level)
        (self.success, self.mountPoint, self.ramdiskDev) = my_ramdisk.get_data()

        log_message("::::::::Ramdisk Mount Point: " + str(self.mountPoint), "debug", self.message_level)
        log_message("::::::::Ramdisk Device     : " + str(self.ramdiskDev), "debug", self.message_level)

        
        if not self.success:
            raise IOError
예제 #10
0
 def detachRamdisk(self, device, message_level="normal"):
     if detach(device, message_level):
         log_message("Successfully detached disk: " + str(device).strip(),
                     "verbose", message_level)
     else:
         log_message("Couldn't detach disk: " + str(device).strip())
         raise Exception("Cannot eject disk: " + str(device).strip())
예제 #11
0
 def getStderr(self) :
     """
     Getter for standard err
     
     @author: Roy Nielsen
     """
     log_message("Getting stderr...", "verbose", self.message_level)
     return self.reterr
예제 #12
0
    def __isMemoryAvailable(self) :
        """
        Check to make sure there is plenty of memory of the size passed in 
        before creating the ramdisk

        Best method to do this on the Mac is to get the output of "top -l 1"
        and re.search("unused\.$", line)
        
        @author: Roy Nielsen
        """
        #mem_free = psutil.phymem_usage()[2]

        #print "Memory free = " + str(mem_free)
        success = False
        self.free = 0
        cmd = ["/usr/bin/top", "-l", "1"]
        pipe = Popen(cmd, stdout=PIPE, stderr=STDOUT)
        size = None
        freeMagnitude = None
         
        if pipe:
            while True:
                myout = pipe.stdout.readline()

                if myout == '' and pipe.poll() != None:
                    break
                
                line = myout.split()
                
                # Get the last item in the list
                found = line[-1]
                almost_size = line[:-1]
                size = almost_size[-1]
                
                if re.search("unused", found) or re.search("free", found):
                    break
            if size:
                sizeCompile = re.compile("(\d+)(\w+)")
                    
                split_size = sizeCompile.search(size)
                freeNumber = split_size.group(1)
                freeMagnitude = split_size.group(2)

                log_message("freeNumber: " + str(freeNumber), "debug", self.message_level)
                log_message("freeMagnitude: " + str(freeMagnitude), "debug", self.message_level)

                if re.match("^\d+$", freeNumber.strip()):
                    if re.match("^\w$", freeMagnitude.strip()):
                        success = True
                        if freeMagnitude:    
                            if re.search("G", freeMagnitude.strip()):
                                self.free = 1024 * int(freeNumber)
                                self.free = str(self.free)
                            elif re.search("M", freeMagnitude.strip()):
                                self.free = freeNumber
                
        return success
예제 #13
0
 def tearDown(self):
     """
     disconnect ramdisk
     """
     if detach(self.ramdiskDev, self.message_level):
         log_message(r"Successfully detached disk: " + str(self.ramdiskDev).strip(), "verbose", self.message_level)
     else:
         log_message(r"Couldn't detach disk: " + str(self.ramdiskDev).strip() + " : mntpnt: " + str(self.mntPoint))
         raise Exception(r"Cannot eject disk: " + str(self.ramdiskDev).strip() + " : mntpnt: " + str(self.mntPoint))
예제 #14
0
파일: macbuild.py 프로젝트: aes512/stonix
 def detachRamdisk(self, device):
     # TODO: Add debug/verbose options
     message_level = "normal"
     
     if detach(device, message_level):
         log_message(r"Successfully detached disk: " + str(device).strip(), "verbose", message_level)
     else:
         log_message(r"Couldn't detach disk: " + str(device).strip())
         raise Exception(r"Cannot eject disk: " + str(device).strip())
예제 #15
0
def authenticate(user="", password="", message_level="normal") :
    """
    Use pexpect to run "su" to run a command as another user...

    Required parameters: user, password, command
    
    inspiration from: http://stackoverflow.com/questions/12419198/python-subprocess-readlines-hangs
    
    @author: Roy Nielsen
    """
    authenticated = False

    if re.match("^\s*$", user) or \
       re.match("^\s*$", password):
        log_message("Cannot pass in empty parameters...", "normal", message_level)
        log_message("user = \"" + str(user) + "\"", "normal", message_level)
        log_message("check password...", "normal", message_level)
        return(255)
    else :
        output = ""
        internal_command = ["/usr/bin/su", "-", str(user), "-c", "/bin/echo hello world"]
        command = " ".join(internal_command)
        log_message("command: " + str(command), "debug", message_level)
        (master, slave) = pty.openpty()
        
        process = Popen(internal_command, stdin=slave, stdout=slave, stderr=slave, shell=False)
        #####
        # Read password prompt
        prompt = os.read(master, 512)
        #####
        # send the password
        os.write(master, password + "\n")
        #####
        # catch the password
        prompt = os.read(master, 512)
        #####
        # catch the output
        output = os.read(master, 512)

        os.close(master)
        os.close(slave)
        process.wait()
        #print output.strip()
        output = output.strip()

        #####
        # Check if valid or not...
        if re.match("^su: Sorry", str(output)):
            authenticated = False
        elif re.match("^hello world", str(output)):
            authenticated = True
        else:
            authenticated = False
        log_message("Leaving authenticate with output of: \"" + str(output) + "\"", "debug", message_level)
        return authenticated
예제 #16
0
 def unmount(self) :
     """
     Unmount the disk - same functionality as __eject on the mac
     
     @author: Roy Nielsen
     """
     success = False
     if self.__eject() :
         success = True
     log_message("Success: " + str(success) + " in unmount", "debug", self.message_level)
     return success
예제 #17
0
 def _runcmd(self, cmd, err_message) :
     """
     Run the command
     
     @author Roy Nielsen
     """
     success = False
     try :
         retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     except Exception, err :
         log_message(err_message + str(err))
예제 #18
0
 def _runcmd(self, cmd, err_message):
     """
     Run the command
     
     @author Roy Nielsen
     """
     success = False
     try:
         retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     except Exception, err:
         log_message(err_message + str(err))
예제 #19
0
 def unmount(self):
     """
     Unmount the disk - same functionality as __eject on the mac
     
     @author: Roy Nielsen
     """
     success = False
     if self.__eject():
         success = True
     log_message("Success: " + str(success) + " in unmount", "debug",
                 self.message_level)
     return success
예제 #20
0
 def __getRandomizedMountpoint(self) :
     """
     Create a randomized (secure) mount point - per python's implementation
     of mkdtemp - a way to make an unguessable directory on the system
     
     @author: Roy Nielsen
     """
     success = False
     try :
         self.mntPoint = mkdtemp()
     except Exception, err :
         log_message("Exception trying to create temporary directory")
예제 #21
0
 def __getRandomizedMountpoint(self):
     """
     Create a randomized (secure) mount point - per python's implementation
     of mkdtemp - a way to make an unguessable directory on the system
     
     @author: Roy Nielsen
     """
     success = False
     try:
         self.mntPoint = mkdtemp()
     except Exception, err:
         log_message("Exception trying to create temporary directory")
예제 #22
0
def checkIfUserIsAdmin(user="", message_level="normal") :
    """
    Check if the passed in user is in the admin group - local or directory 
    service.  The Admin group is group 80 on the Mac.
    
    @author: Roy Nielsen
    """
    if re.match("^\s*$", user) :
        message = "Cannot check the group of a user string that is empty..."
        log_message(message, "normal", message_level)
        log_message("user: \"" + str(user) + "\"", "normal", message_level )
        found = False
    else: 
        found = False
        retval = False
        #####
        # Looking for user in local directory as well as all attached 
        # directory services
        cmd = ["/usr/bin/dscl", "/Search", "-read", "/Groups/admin", "GroupMembership"]

        #retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()

        (retcode, retval, reterr, didTimeOut) = runWithTimeout(cmd, 15)
        
        if didTimeOut :
            cmd = ["/usr/bin/dscl", ".", "-read", "/Groups/admin", "GroupMembership"]
            (retcode, retval, reterr, didTimeOut) = runWithTimout(cmd, 15)
        
        if retval :
            lines = retval.split("\n")
            users = []
            for line in lines :
                #print "Line: " + str(line)
                if re.match("^GroupMembership:\s+", line) :
                    members = line.split()[1:]
                    for member in members :
                        users.append(member)
                        
            #####
            # Find unique members of the list
            users = list(set(users))
            
            #####
            # Search the list for the passed in user
            for member in users :
                if re.match("^%s$"%user.strip(),  member.strip()) :
                    #print "found... user: "******" = " + member
                    found = True
                    break
                else :
                    found = False
    return found
예제 #23
0
    async def purger(self):
        before_datetime = datetime.utcnow() - timedelta(
            seconds=self.config.get('purge_messages_after'))

        try:
            log_message(
                self.lfg_channel.guild,
                f'purging messages from "{self.lfg_channel}#{self.lfg_channel.id}" older than {before_datetime}'
            )
            deleted_messages = await self.lfg_channel.purge(
                before=before_datetime, limit=100, check=self.check_id)

        except Exception as e:
            print(e)
예제 #24
0
    def __init__(self, parent=None) :
        """
        Initialization method
        
        Author: Roy Nielsen
        """
        super(GeneralWarning, self).__init__(parent)
        self.ui = Ui_GeneralWarning()

        self.message_level = "debug"
        self.ui.setupUi(self)

        self.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.accept)

        log_message("Finished initializing NotOnCorrectDisk Class...", "debug", self.message_level)
예제 #25
0
    def __init__(self, parent=None):
        """
        Initialization method
        
        Author: Roy Nielsen
        """
        super(GeneralWarning, self).__init__(parent)
        self.ui = Ui_GeneralWarning()

        self.message_level = "debug"
        self.ui.setupUi(self)

        self.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.accept)

        log_message("Finished initializing NotOnCorrectDisk Class...", "debug",
                    self.message_level)
예제 #26
0
 def __format(self) :
     """
     Format the ramdisk
     
     @author: Roy Nielsen
     """
     success = False
     cmd = ["/sbin/newfs_hfs", "-v", "ramdisk", self.myRamdiskDev]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug", self.message_level)
     log_message("retval: \"" + str(retval).strip() + "\"", "debug", self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug", self.message_level)
     log_message("*******************************************", "debug", self.message_level)
     log_message("Success: " + str(success) + " in __format", "debug", self.message_level)
     return success
예제 #27
0
 def __partition(self) :
     """
     Not implemented on the Mac
     
     """
     success=False
     size = int(self.diskSize)/(2*1024)
     cmd = [self.diskutil, "partitionDisk", self.myRamdiskDev, str(1), "MBR", "HFS+", "ramdisk", str(size) + "M"]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug", self.message_level)
     log_message("retval: \"\"\"" + str(retval).strip() + "\"\"\"", "debug", self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug", self.message_level)
     log_message("*******************************************", "debug", self.message_level)
     log_message("Success: " + str(success) + " in __format", "debug", self.message_level)
     return success
예제 #28
0
    def test_files_n_dirs(self):
        """
        Should work when files exist in ramdisk.
        """
        # Do file setup for this test
        for subdir in self.subdirs:
            dirpath = self.mountPoint + "/" + subdir
            log_message("DIRPATH: : " + str(dirpath), "debug", self.message_level)
            self.mkdirs(dirpath)
            self.touch(dirpath + "/" + "test")

        # Do the tests
        for subdir in self.subdirs:
            # CANNOT use os.path.join this way.  os.path.join cannot deal with
            # absolute directories.  May work with mounting ramdisk in local
            # relative directories.
            self.assertTrue(os.path.exists(self.mountPoint + "/" + subdir + "/" +  "test"))
예제 #29
0
 def eject(self) :
     """
     Eject the ramdisk
     Detach (on the mac) is a better solution than unmount and eject 
     separately.. Besides unmounting the disk, it also stops any processes 
     related to the mntPoint
     """
     success = False
     cmd = [self.hdiutil, "detach", self.myRamdiskDev]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug", self.message_level)
     log_message("retval: \"" + str(retval).strip() + "\"", "debug", self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug", self.message_level)
     log_message("*******************************************", "debug", self.message_level)
     log_message("Success: " + str(success) + " in eject", "debug", self.message_level)
     return success
예제 #30
0
 def __init__(self, command=[], message_level="normal") :
     """
     Initialization method
     """
     self.command = command
     self.message_level = message_level
     self.retout = None
     self.reterr = None
     threading.Thread.__init__(self)
     
     if isinstance(self.command, types.ListType) :
         self.shell = True
         self.printcmd = " ".join(self.command)
     if isinstance(self.command, types.StringTypes) :
         self.shell = False
         self.printcmd = self.command
 
     log_message("Initialized runThread...", "normal", self.message_level)
예제 #31
0
 def __create(self) :
     """
     Create a ramdisk device
     
     @author: Roy Nielsen
     """
     success = False
     cmd = [self.hdiutil, "attach", "-nomount", "ram://" + self.diskSize]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if reterr:
         success = False
         raise Exception("Error trying to create ramdisk(" + str(reterr).strip() + ")")
     else:
         self.myRamdiskDev = retval.strip()
         log_message("Device: \"" + str(self.myRamdiskDev) + "\"", "debug", self.message_level)
         success = True
     log_message("Success: " + str(success) + " in __create", "debug", self.message_level)            
     return success
예제 #32
0
 def touch(self, fname="", message_level="normal") :
     """
     Python implementation of the touch command..
     
     inspiration: http://stackoverflow.com/questions/1158076/implement-touch-using-python
     
     @author: Roy Nielsen
     """
     if re.match("^\s*$", str(fname)) :
         log_message("Cannot touch a file without a filename....", "normal", self.message_level)
     else :
         try:
             os.utime(fname, None)
         except:
             try :
                 open(fname, 'a').close()
             except Exception, err :
                 log_message("Cannot open to touch: " + str(fname), "normal", self.message_level)
예제 #33
0
    def processAdminUser(self) :
        """
        Run Stonix as an admin user - load AdministratorCredentials dialog
        with the current user as the default username.
        
        Have AdministratorCredentials handle it's own buttons.
        
        @author: Roy Nielsen
        """
        retval = self.admin_creds.exec_()
        self.admin_creds.raise_()
        
        if retval == 1 :
            self.accept

        log_message("processAdminUser complete...", "verbose", self.message_level)

        self.reject()
예제 #34
0
def runWithWaitTillFinished(command=[], message_level="normal") :
    """
    Use subprocess to call a command and wait until it is finished before
    moving on...
    
    @author: Roy Nielsen
    """
    if command :
        if isinstance(command, types.ListType) :
            printcmd = " ".join(command)
        if isinstance(command, types.StringTypes) :
            printcmd = command
        proc = Popen(command, stdout=PIPE, stderr=PIPE)
        proc.wait()
        log_message("command: " + printcmd + " returned: " + str(proc.retcode), \
                    "verbose", self.message_level)
        return (proc.retcode)
    else :
        log_message("Cannot run a command that is empty...", "normal", message_level)
예제 #35
0
def runMyThreadCommand(cmd=[], message_level="normal") :
    """
    Use the RunThread class to get the stdout and stderr of a command
    
    @author: Roy Nielsen
    """
    retval = None
    reterr = None
    
    if cmd and message_level :
        run_thread = RunThread(cmd, message_level)
        run_thread.start()
        run_thread.join()
        retval = run_thread.getStdout()
        reterr = run_thread.getStderr()
    else :
        log_message("Invalid parameters, please report this as a bug.")
        
    return retval, reterr
예제 #36
0
    def __remove_journal(self) :
        """
        Having a journal in ramdisk makes very little sense.  Remove the journal
        after creating the ramdisk device
        
        cmd = ["/usr/sbin/diskutil", "disableJournal", "force", myRamdiskDev]
        
        using "force" doesn't work on a mounted filesystem, without it, the command
        will work on a mounted file system

        @author: Roy Nielsen
        """
        success = False
        cmd = [self.diskutil, "disableJournal", self.myRamdiskDev + "s1"]
        retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
        if not reterr:
            success = True
        log_message("Success: " + str(success) + " in __remove_journal", "debug", self.message_level)
        return success
예제 #37
0
    def processAdminUser(self):
        """
        Run Stonix as an admin user - load AdministratorCredentials dialog
        with the current user as the default username.
        
        Have AdministratorCredentials handle it's own buttons.
        
        @author: Roy Nielsen
        """
        retval = self.admin_creds.exec_()
        self.admin_creds.raise_()

        if retval == 1:
            self.accept

        log_message("processAdminUser complete...", "verbose",
                    self.message_level)

        self.reject()
예제 #38
0
def runWithPty(command, message_level="normal") :
    """
    Run a command with the pty...
    
    @author: Roy Nielsen
    """
    output = "ERROR..."
    #####
    # Check input
    if command :
    
        (master, slave) = pty.openpty()
        
        #process = Popen(command, stdout=slave, stderr=slave, close_fds=True)
        process = Popen(command, stdout=slave, stderr=slave)
    
        output = ""
        #temp = os.read(master, 10)
        while True :
            #r,w,e = select.select([master], [], [], 0) # timeout of 0 means "poll"
            r,w,e = select.select([], [], [], 0) # timeout of 0 means "poll"
            if r :
                line = os.read(master, 512)
                #####
                # Warning, uncomment at your own risk - several programs
                # print empty lines that will cause this to break and
                # the output will be all goofed up.
                #if not line :
                #    break
                #print output.rstrip()
                output = output + line
            elif process.poll() is not None :
                break
        os.close(master)
        os.close(slave)
        process.wait()
        #print output.strip()
        output = output.strip()
        log_message("Leaving runAs with: \"" + str(output) + "\"", "debug", message_level)
    else :
        log_message("Cannot run a command that is empty...", "normal", message_level)
    return output
예제 #39
0
    def __remove_journal(self):
        """
        Having a journal in ramdisk makes very little sense.  Remove the journal
        after creating the ramdisk device
        
        cmd = ["/usr/sbin/diskutil", "disableJournal", "force", myRamdiskDev]
        
        using "force" doesn't work on a mounted filesystem, without it, the command
        will work on a mounted file system

        @author: Roy Nielsen
        """
        success = False
        cmd = [self.diskutil, "disableJournal", self.myRamdiskDev + "s1"]
        retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
        if not reterr:
            success = True
        log_message("Success: " + str(success) + " in __remove_journal",
                    "debug", self.message_level)
        return success
예제 #40
0
 def __create(self):
     """
     Create a ramdisk device
     
     @author: Roy Nielsen
     """
     success = False
     cmd = [self.hdiutil, "attach", "-nomount", "ram://" + self.diskSize]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if reterr:
         success = False
         raise Exception("Error trying to create ramdisk(" +
                         str(reterr).strip() + ")")
     else:
         self.myRamdiskDev = retval.strip()
         log_message("Device: \"" + str(self.myRamdiskDev) + "\"", "debug",
                     self.message_level)
         success = True
     log_message("Success: " + str(success) + " in __create", "debug",
                 self.message_level)
     return success
예제 #41
0
 def __format(self):
     """
     Format the ramdisk
     
     @author: Roy Nielsen
     """
     success = False
     cmd = ["/sbin/newfs_hfs", "-v", "ramdisk", self.myRamdiskDev]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("retval: \"" + str(retval).strip() + "\"", "debug",
                 self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug",
                 self.message_level)
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("Success: " + str(success) + " in __format", "debug",
                 self.message_level)
     return success
예제 #42
0
def system_call_retval(cmd="", message_level="normal", myshell=False) :
    """
    Use the subprocess module to execute a command, returning
    the output of the command
    
    Author: Roy Nielsen
    """
    retval = ""
    reterr = ""
#    mycmd = cmd.split()
    if isinstance(cmd, types.ListType) :
        printcmd = " ".join(cmd)
    if isinstance(cmd, types.StringTypes) :
        printcmd = cmd
    
    try :
        if myshell == False :
            pipe = Popen(cmd, stdout=PIPE, stderr=PIPE)
        elif myshell == True :
            pipe = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=myshell)
        else :
            pipe = Popen(cmd, stdout=PIPE, stderr=PIPE)
        
        (stdout_out, stderr_out) = pipe.communicate()

        if stdout_out :
            for line in stdout_out : 
                if line is not None :
                    line.strip("\n")
                    retval = retval + line

        if stderr_out :
            for line in stderr_out : 
                if line is not None :
                    line.strip("\n")
                    reterr = reterr + line            
            
    except ValueError, err :
        log_message("system_call_retval - ValueError: " + str(err) + " command: " + printcmd, "normal", message_level)
예제 #43
0
 def run(self):
     if self.command :
         try :
             p = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=self.shell)
         except Exception, err :
             log_message("Exception trying to open: " + str(self.printcmd), "normal", self.message_level)
             log_message("Associated exception: " + str(err), "normal", self.message_level)
             raise err
         else :
             try: 
                 self.retout, self.reterr = p.communicate()
             except Exception, err :
                 log_message("Exception trying to open: " + str(self.printcmd), "normal", self.message_level)
                 log_message("Associated exception: " + str(err), "normal", self.message_level)
                 raise err
             else :
예제 #44
0
 def eject(self):
     """
     Eject the ramdisk
     Detach (on the mac) is a better solution than unmount and eject 
     separately.. Besides unmounting the disk, it also stops any processes 
     related to the mntPoint
     """
     success = False
     cmd = [self.hdiutil, "detach", self.myRamdiskDev]
     retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate()
     if not reterr:
         success = True
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("retval: \"" + str(retval).strip() + "\"", "debug",
                 self.message_level)
     log_message("reterr: \"" + str(reterr).strip() + "\"", "debug",
                 self.message_level)
     log_message("*******************************************", "debug",
                 self.message_level)
     log_message("Success: " + str(success) + " in eject", "debug",
                 self.message_level)
     return success
예제 #45
0
async def on_message(message):

    guild = message.guild
    author = message.author
    channel = message.channel

    # check if message is not a DM and not created by a bot
    if not isinstance(channel, discord.DMChannel) and not message.author.bot:

        lfg_channel_id = config.get('lfg_channel_id')

        # check if message was send to the lfg channel and does not contain an lfg
        if (channel.id == config.get('lfg_channel_id')
            ) and not (command_prefix + lfg_command in message.content):
            dm_no_lfg_command = config.get('dm_no_lfg_command')
            await send_command_error_message(author, dm_no_lfg_command)
            await message.delete()
            log_message(
                guild,
                f'* message of "{author}" in "{channel}#{channel.id}" was deleted since it did not contain a command'
            )
            return

        await lfg_bot.process_commands(message)
예제 #46
0
    def __init__(self, args, message_level="debug", parent=None):
        """
        Initialization method
        
        @author: Roy Nielsen
        """
        super(AdministratorCredentials, self).__init__(parent)
        self.ui = Ui_AdministratorCredentials()
        self.ui.setupUi(self)
        self.args = args

        self.message_level = message_level
        self.username = ""
        self.password = ""
        self.cmd = ""
        self.tmpDir = ""

        self.progress_bar = QProgressDialog()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(0)
        self.progress_bar.setLabelText("Checking Password...")

        #####
        # Set up signals and slots
        self.connect(self.ui.authUserButton, SIGNAL("clicked()"),
                     self.isPassValid)
        self.connect(self.ui.cancelButton, SIGNAL("clicked()"), self.rejectApp)

        #####
        # Commented out putting in the current logged in user as the default
        # user - to make more Mac-like
        #user = getpass.getuser()
        #self.ui.adminName.setText(user)

        log_message("Finished initializing AdministratorCredentials Class...",
                    "debug", self.message_level)
예제 #47
0
 def get_data(self):
     """
     Getter for mount data, and if the mounting of a ramdisk was successful
     """
     log_message("Success: " + str(self.success), "debug",
                 self.message_level)
     log_message("Mount point: " + str(self.mntPoint), "debug",
                 self.message_level)
     log_message("Device: " + str(self.myRamdiskDev), "debug",
                 self.message_level)
     return (self.success, str(self.mntPoint), str(self.myRamdiskDev))
예제 #48
0
def isUserOnSystem(user="", message_level="normal") :
    """
    Check if the passed in user is a local user on the system
    
    Author: Roy Nielsen
    """
    is_user_on_local_system = False

    #####
    # If the passed in user is empty or only spaces, return false.
    if re.match("^\s*$", user) :
        return is_user_on_local_system
    
    #####
    # Get valid users on the system, put them in a list
    cmd = ["/usr/bin/dscl", "/Search", "list", "/Users"]
    
    (retval, reterr) = system_call_retval(cmd, message_level)
    
    systemUserList = retval.split("\n")

    validSystemUserList = []
    
    for systemUser in systemUserList :
        if not re.match("^_.*", systemUser) and \
           not re.match("^root$", systemUser) and \
           not re.match("^nobody$", systemUser) and \
           not re.match("^daemon$", systemUser) and \
           not re.match("^\s*$", systemUser) :
            log_message("Valid System User: "******"debug", message_level)
            validSystemUserList.append(systemUser)

    #####
    # Check if the passed in user is a valid local user on the system
    for systemUser in validSystemUserList :
        if re.match("^%s$"%(systemUser), user) :
            is_user_on_local_system = True
            log_message("User: \"" + str(user) + "\" found on the system", "debug", message_level)
            break

    log_message("ivar = " + str(is_user_on_local_system), "debug", message_level)
    return is_user_on_local_system