示例#1
0
文件: SSH.py 项目: smokedice/YATES
class SSHClient(Process):
    TIMEOUT = 10
    PING_RECEIVED = re.compile("1 received")

    def __init__(self, username, password, host, cmdsToSend, port = 22, exitCmd = "exit", timeout = None):
        Process.__init__(self, name = "SSHClient")

        self.logger = LogManager().getLogger('SSHClient-%s' % host)
        self.username = username
        self.password = password
        self.host = host
        self.port = int(port)
        self.cmdsToSend = cmdsToSend if isinstance(cmdsToSend, list) else [cmdsToSend]
        self.exitCmd = exitCmd

        self.queue = Queue()
        self.msg = ""
        self.status = Status.FAILURE
        self.startTime = Value('d', 0.0)
        self.endTime = Value('d', 0.0)
        self.timeout = timeout or SSHClient.TIMEOUT
        self.cmdsSend = False
        self.start()

    def isFinished(self):
        """ True if the process has finished """
        return not self.is_alive()

    def updateOutput(self):
        """
        Update the msg to include the latest
        output from the given commands
        """
        try:
            while True:
                msg = self.queue.get(timeout = 0.5)
                self.msg += msg
        except Empty: pass
        except IOError: pass

        if self.isFinished():
            self.queue.close()
        return self.msg

    def run(self):
        factory = SSHFactory(self)
        factory.protocol = ClientTransport
        reactor.connectTCP(self.host, self.port, factory)

        self.startTime.value = time.time()
        check = task.LoopingCall(self.__ping)
        check.start(2.0)
        reactor.callLater(self.timeout, self.__timeout)
        log.defaultObserver.stop()
        reactor.run()
        self.endTime.value = time.time()
        self.queue.close()
        sys.exit(self.status)

    def __timeout(self):
        """ Timeout checker """
        if self.status != Status.FAILURE:
            return

        self.logger.error('Connection timeout to peer %s:%s'
            %(self.host, self.port))
        reactor.stop()

    def __ping(self):
        with open('/dev/null') as null:
            ping = subprocess.Popen(["ping", "-c1", "-W1", self.host],
                stdout = null, stderr = null)
            ping.wait()

        if ping.returncode != 0 and reactor.running:
            if self.cmdsSend == False:
                self.status = Status.FAILURE
            reactor.stop()

    def cleanup(self):
        self.queue.close()

    def shutdown(self):
        """ Terminate the SSH process """
        self.terminate()
        self.join()
        self.endTime.value = time.time()
示例#2
0
class Objectify(object):
    """
    The objectify class allows the application
    to setup and use Objectify by using the
    constructor, then accessing Objectify
    by using the .instance attribute
    @param xml: XML file path
    @param xsd: XSD file path
    @raise InvalidConfigurationXML: Non existent XML/XSD. Invalid formatted files
    """

    KWARGS = {
        "xmlIfClass": pyxsval.XMLIF_ELEMENTTREE,
        "warningProc": pyxsval.PRINT_WARNINGS,
        "errorLimit": 200,
        "verbose": 0,
        "useCaching": 0,
        "processXInclude": 0
    }

    def __init__(self, xml, xsd):
        self.logger = LogManager().getLogger(self.__class__.__name__)

        self.cwd = os.path.abspath('.')
        self.xmlFile = os.path.abspath(xml)
        self.xsdFile = os.path.abspath(xsd)

        if not os.path.exists(self.xmlFile) or not os.path.exists(self.xsdFile):
            raise Exception("Given Files: %s - %s" % (self.xmlFile, self.xsdFile))

        successfulLoad, xmlHash, xsdHash = self.__loadFromCache(xml, xsd)

        if not successfulLoad:
            # Hashes are incorrect
            self.__loadAndValidate(xml, xsd, xmlHash, xsdHash)

    def __loadFromCache(self, xml, xsd):
        hashPath = self.__getXmlHashFile(xml)
        xmlHash = self.__hashFile(xml)
        xsdHash = self.__hashFile(xsd)

        if not os.path.exists(hashPath):
            return (False, xmlHash, xsdHash)

        with open(hashPath, 'r') as hashFile:
            cachedXMLHash = hashFile.readline().strip()
            cachedXSDHash = hashFile.readline().strip()

        if cachedXMLHash != xmlHash or cachedXSDHash != xsdHash:
            return (False, xmlHash, xsdHash)

        self.configuration = make_instance(xml)
        return (True, xmlHash, xsdHash)

    def __hashFile(self, path):
        with open(path, 'rb') as xmlFile:
            shaHash = hashlib.sha1()

            while True:
                data = xmlFile.read(4096)
                if not data:
                    break
                shaHash.update(hashlib.sha1(data).hexdigest())

        return shaHash.hexdigest()

    def __loadAndValidate(self, xml, xsd, xmlHash, xsdHash):
        try:
            # Validate the config file
            pyxsval.parseAndValidate(
                inputFile=xml, xsdFile=xsd,
                **Objectify.KWARGS)
        except Exception:
            raise Exception(format_exc())

        #gnosis.xml.objectify._XO_node = Node.Node
        #gnosis.xml.objectify._XO_interface = Interface.Interface
        self.configuration = make_instance(xml)
        hashPath = self.__getXmlHashFile(xml)

        try:
            with open(hashPath, 'w') as hashFile:
                hashFile.write("%s\n%s" % (xmlHash, xsdHash))
                hashFile.close()
        except IOError, e:
            self.logger.error(e)