# From http://stackoverflow.com/questions/92438/stripping-non-printable-characters-from-a-string-in-python
control_chars = ''.join(map(unichr, range(0, 32) + range(127, 160)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))


def remove_control_chars(s):
return control_char_re.sub('', s)

# coding: utf-8
import sys
import time

# emitter 发射
'''
异步封装

def on_response(self, response):
    dosomething()

http = tornado.httpclient.AsyncHTTPClient()
http.fetch(req, callback=self.on_response)

'''
def main():

    def sigterm_handler(signum, frame):
        print 'stop...'
        return -1

    import signal
    signal.signal(signal.SIGTERM, sigterm_handler)
    signal.signal(signal.SIGINT, sigterm_handler)

    count = 10
    while count:
        print 'hello'
        time.sleep(1)
        count -= 1


    return 0

if __name__ == '__main__':

    import uuid
    import platform
    print platform.uname()
    print platform.node()

    hostid = uuid.uuid5(uuid.NAMESPACE_DNS, platform.node() + str(uuid.getnode())).hex

    print hostid

    import socket

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('www.baidu.com', 0))
    ip = s.getsockname()[0]
    print ip

        s = socket.socket()
        s.connect(('114.114.114.114', 53))
        addr, port = s.getsockname()
        s.close()
        print addr

    import requests

    try:
        bad_r = requests.get('http://httpbin.org/status/404')

        print bad_r.status_code

        bad_r.raise_for_status()

        if bad_r.status_code >= 200 and bad_r.status_code < 205:
            print "success ooh! to log"


    except Exception:
        print 'bad_r raise to log %s'%bad_r.status_code

    sys.exit(main())


class EmitterThread(threading.Thread):

    def __init__(self, *args, **kwargs):
        self.__name = kwargs['name']
        self.__emitter = kwargs.pop('emitter')()
        self.__logger = kwargs.pop('logger')
        self.__config = kwargs.pop('config')
        self.__max_queue_size = kwargs.pop('max_queue_size', 100)
        self.__queue = Queue(self.__max_queue_size)
        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True

    def run(self):
        while True:
            (data, headers) = self.__queue.get()
            try:
                self.__logger.debug('Emitter %r handling a packet', self.__name)
                self.__emitter(data, self.__logger, self.__config)
            except Exception:
                self.__logger.error('Failure during operation of emitter %r', self.__name, exc_info=True)

    def enqueue(self, data, headers):
        try:
            self.__queue.put((data, headers), block=False)
        except Full:
            self.__logger.warn('Dropping packet for %r due to backlog', self.__name)


class EmitterManager(object):
    """Track custom emitters"""

    def __init__(self, config):
        self.agentConfig = config
        self.emitterThreads = []
        for emitter_spec in [s.strip() for s in self.agentConfig.get('custom_emitters', '').split(',')]:
            if len(emitter_spec) == 0:
                continue
            logging.info('Setting up custom emitter %r', emitter_spec)
            try:
                thread = EmitterThread(
                    name=emitter_spec,
                    emitter=modules.load(emitter_spec, 'emitter'),
                    logger=logging,
                    config=config,
                )
                thread.start()
                self.emitterThreads.append(thread)
            except Exception:
                logging.error('Unable to start thread for emitter: %r', emitter_spec, exc_info=True)
        logging.info('Done with custom emitters')

    def send(self, data, headers=None):
        if not self.emitterThreads:
            return  # bypass decompression/decoding
        if headers and headers.get('Content-Encoding') == 'deflate':
            data = zlib.decompress(data)
        data = json_decode(data)
        for emitterThread in self.emitterThreads:
            logging.info('Queueing for emitter %r', emitterThread.name)
            emitterThread.enqueue(data, headers)

  

原文地址:https://www.cnblogs.com/newpython/p/6421341.html