예제 #1
0
    def _perform_handshake(self):
        """Perform The WebSocket Handshake"""
        try:
            Log.add("Got To Handshake")
            data = self.recv(1024).strip()
            # Log.add("Data: %s" % data)
            headers = Message(StringIO(data.split('\r\n', 1)[1]))

            Log.add("Parsed Headers:")
            # Log.add(headers)

            if headers.get('Upgrade', None) == 'websocket':
                Log.add("Attempting Handshake")

                # create response key
                key = b64encode(
                    sha1(headers['Sec-WebSocket-Key'] + self.SALT).digest())

                # create response headers
                response = ("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
                            "Upgrade: websocket\r\n"
                            "Connection: Upgrade\r\n"
                            "Sec-WebSocket-Origin: %s\r\n"
                            "Sec-WebSocket-Accept: %s\r\n\r\n" %
                            (headers["Origin"], key))
                if self.send_bytes(response):
                    Log.add("Handshake successful")
                    self._assign_room(data)
                    self._ready_state = "authenticating"

        except Exception as e:
            Log.add(e.args)
예제 #2
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def _perform_handshake(self):
        """Perform The WebSocket Handshake"""
        try:
            Log.add("Got To Handshake")
            data = self.recv(1024).strip()
            # Log.add("Data: %s" % data)
            headers = Message(StringIO(data.split('\r\n', 1)[1]))

            Log.add("Parsed Headers:")
            # Log.add(headers)

            if headers.get('Upgrade', None) == 'websocket':
                Log.add("Attempting Handshake")

                # create response key
                key = b64encode(sha1(headers['Sec-WebSocket-Key'] + self.SALT).digest())

                # create response headers
                response = (
                    "HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
                    "Upgrade: websocket\r\n"
                    "Connection: Upgrade\r\n"
                    "Sec-WebSocket-Origin: %s\r\n"
                    "Sec-WebSocket-Accept: %s\r\n\r\n" % (headers["Origin"], key)
                )
                if self.send_bytes(response):
                    Log.add("Handshake successful")
                    self._assign_room(data)
                    self._ready_state = "authenticating"

        except Exception as e:
            Log.add(e.args)
예제 #3
0
  def __init__(self) -> None:
    try:
      with open("config.json") as configFile:
        config = json.load(configFile)
        self.username = os.environ['AMZNFLEXUSERNAME']
        self.password = os.environ["AMZNFLEXPWD"]
        self.desiredWarehouses = config["desiredWarehouses"] if len(config["desiredWarehouses"]) >= 1 else None  # list of warehouse ids
        self.minBlockRate = config["minBlockRate"]
        self.arrivalBuffer = config["arrivalBuffer"]
        self.desiredStartHour = config["desiredStartHour"]  # start hour in military time
        self.desiredEndHour = config["desiredEndHour"]  # end hour in military time
        self.retryLimit = config["retryLimit"]  # number of jobs retrieval requests to perform
        self.twilioFromNumber = config["twilioFromNumber"]
        self.twilioToNumber = config["twilioToNumber"]
        self.__retryCount = 0
        self.__acceptedOffers = []
        self.__startTimestamp = time.time()
        self.__requestHeaders = FlexUnlimited.allHeaders.get("FlexCapacityRequest")
        self.__requestHeaders["x-amz-access-token"] = self.__getFlexRequestAuthToken()

        twilioAcctSid = config["twilioAcctSid"]
        twilioAuthToken = config["twilioAuthToken"]

        if twilioAcctSid != "" and twilioAuthToken != "" and self.twilioFromNumber != "" and self.twilioToNumber != "":
          self.twilioClient = Client(twilioAcctSid, twilioAuthToken)
        else:
          self.twilioClient = None
    except KeyError as nullKey:
      Log.error(f'{nullKey} was not set. Please setup FlexUnlimited as described in the README.')
      sys.exit()
    except FileNotFoundError:
      Log.error("Config file not found. Ensure a properly formatted 'config.json' file exists in the root directory.")
      sys.exit()
예제 #4
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def client_ready(self):
        """Check if the client is ready to receive messages

        Returns
        -------
        Boolean
        """
        Log.add(self._ready_state == "open", Log.NOTICE)
        return self._ready_state == "open"
예제 #5
0
    def client_ready(self):
        """Check if the client is ready to receive messages

        Returns
        -------
        Boolean
        """
        Log.add(self._ready_state == "open", Log.NOTICE)
        return self._ready_state == "open"
예제 #6
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def send_json_object(self, json_object):
        """Send a pre defined json object to the room

        Parameters
        ----------
        json_object : dictionary
        """
        if self._ready_state == "open":
            Log.add(json_object)
            RoomManager.send_to_room(self._room_id, Builder.build(json.dumps(json_object)))
예제 #7
0
    def send_json_object(self, json_object):
        """Send a pre defined json object to the room

        Parameters
        ----------
        json_object : dictionary
        """
        if self._ready_state == "open":
            Log.add(json_object)
            RoomManager.send_to_room(self._room_id,
                                     Builder.build(json.dumps(json_object)))
예제 #8
0
파일: Client.py 프로젝트: iam4423/WebSocket
 def handle_close(self):
     """Cleanup a closed connection"""
     Log.add("got to close")
     sys_message = {
         "usr": "******",
         "msg": "User \"%s\" has left the room" % self._client_name,
         "tme": int(time.time())
     }
     Log.add(sys_message)
     RoomManager.send_to_room(self._room_id, Builder.build(json.dumps(sys_message)))
     Room.remove_from_room(self._room_id, self)
     self.close()
예제 #9
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def handle_read(self):
        """Handle incoming data"""
        if self._ready_state == "connecting":
            self._perform_handshake()

        elif self._ready_state == "authenticating":
            frame = Parser.parse(self.socket)
            self._perform_login(frame)

        elif self._ready_state == "open":
            frame = Parser.parse(self.socket)
            Log.add("Decoded Message: %s" % frame.payload)
            self._handle_frame(frame)
예제 #10
0
 def handle_close(self):
     """Cleanup a closed connection"""
     Log.add("got to close")
     sys_message = {
         "usr": "******",
         "msg": "User \"%s\" has left the room" % self._client_name,
         "tme": int(time.time())
     }
     Log.add(sys_message)
     RoomManager.send_to_room(self._room_id,
                              Builder.build(json.dumps(sys_message)))
     Room.remove_from_room(self._room_id, self)
     self.close()
예제 #11
0
    def handle_read(self):
        """Handle incoming data"""
        if self._ready_state == "connecting":
            self._perform_handshake()

        elif self._ready_state == "authenticating":
            frame = Parser.parse(self.socket)
            self._perform_login(frame)

        elif self._ready_state == "open":
            frame = Parser.parse(self.socket)
            Log.add("Decoded Message: %s" % frame.payload)
            self._handle_frame(frame)
예제 #12
0
    def _assign_room(self, headers):
        """Assign the client to the room they are trying to join

        Parameters
        ----------
        headers : String
        """
        # split room_id from the headers
        room_id = headers.split('\r\n')[0].split(' ')[1].strip()

        Log.add("Room ID: %s" % room_id)

        # assign self to room
        self._room_id = room_id
        Room.add_to_room(room_id, self)
예제 #13
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def _assign_room(self, headers):
        """Assign the client to the room they are trying to join

        Parameters
        ----------
        headers : String
        """
        # split room_id from the headers
        room_id = headers.split('\r\n')[0].split(' ')[1].strip()

        Log.add("Room ID: %s" % room_id)

        # assign self to room
        self._room_id = room_id
        Room.add_to_room(room_id, self)
예제 #14
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def _perform_login(self, frame):
        """Perform login attempt

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        try:
            if frame.opcode == 0x1 and frame.length > 0:
                json_obj = json.loads(frame.payload)
                Log.add(json_obj)
                if json_obj['cmd'] == "System|login" and len(json_obj['args']):
                    parts = json_obj['cmd'].split('|')
                    Command.run_command(parts[0], parts[1], self, json_obj['args'])
        except Exception as e:
            Log.add(e.args)
예제 #15
0
    def send(self, data):
        """Send a message to the room at large

        Parameters
        ----------
        data : String
        """
        if self._ready_state == "open":
            Log.add(data)
            obj = json.dumps({
                "msg": data,
                "usr": self._client_name,
                "tme": int(time.time())
            })

            RoomManager.send_to_room(self._room_id, Builder.build(obj))
예제 #16
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def send(self, data):
        """Send a message to the room at large

        Parameters
        ----------
        data : String
        """
        if self._ready_state == "open":
            Log.add(data)
            obj = json.dumps({
                "msg": data,
                "usr": self._client_name,
                "tme": int(time.time())
            })

            RoomManager.send_to_room(self._room_id, Builder.build(obj))
예제 #17
0
	def __init__(self):
		self.conf = ConfUtil.zen(__file__)

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)
예제 #18
0
    def _perform_login(self, frame):
        """Perform login attempt

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        try:
            if frame.opcode == 0x1 and frame.length > 0:
                json_obj = json.loads(frame.payload)
                Log.add(json_obj)
                if json_obj['cmd'] == "System|login" and len(json_obj['args']):
                    parts = json_obj['cmd'].split('|')
                    Command.run_command(parts[0], parts[1], self,
                                        json_obj['args'])
        except Exception as e:
            Log.add(e.args)
예제 #19
0
  def __acceptOffer(self, offer: Offer):
    self.__requestHeaders["X-Amz-Date"] = self.__getAmzDate()

    request = requests.post(
      FlexUnlimited.routes.get("AcceptOffer"),
      headers=self.__requestHeaders,
      json={"offerId": offer.id})

    if request.status_code == 200:
      self.__acceptedOffers.append(offer)
      if self.twilioClient is not None:
        self.twilioClient.messages.create(
          to=self.twilioToNumber,
          from_=self.twilioFromNumber,
          body=offer.toString())
      Log.info(f"Successfully accepted offer {offer.id}")
    else:
      Log.error(f"Unable to accept offer {offer.id}. Request returned status code {request.status_code}")
예제 #20
0
 def __getFlexRequestAuthToken(self) -> str:
   """
       Get authorization token for Flex Capacity requests
       Returns:
       An access token as a string
       """
   payload = {
     "requested_extensions": ["device_info", "customer_info"],
     "cookies": {
       "website_cookies": [],
       "domain": ".amazon.com"
     },
     "registration_data": {
       "domain": "Device",
       "app_version": "0.0",
       "device_type": "A3NWHXTQ4EBCZS",
       "os_version": "15.2",
       "device_serial": "B262D48AC3EA4671B288C20F406821B5",
       "device_model": "iPhone",
       "app_name": "Amazon Flex",
       "software_version": "1"
     },
     "auth_data": {
       "user_id_password": {
         "user_id": self.username,
         "password": self.password
       }
     },
     "user_context_map": {
       "frc": "AFgQ07+f4rZ1HkMDmsLeD9GlOFoIa9auy7p03s6CSDsZFiskgDYWhSIQyD7S8EUxSMGAGs1gf0e"
              "\/wlmnvGBZ2Jh7YkvVfXENXnwoQ12acgHysONHR\/oBMWPwNOBg+qY88UlNQ1RXNOv9fgMDJPjr5gvZJs3S5RY9RyAMg7H"
              "\/sSIEJ9j+TXIE+xnMZrT1lOpEMdQJHV53+pgcJEG2SB4kt8OraJqoZCt7A\/lyWO9RAL1gWlnhEHyEd3"
              "\/\/t8TNQBKXbjO2G9iFUQs\/s0VqVSchIVzOzT\/BRpe36iFW7XnbGU0N9Q5Y40m+M"
              "\/kxySQ3h5YWs9kl1PuLGTx3ql1ttSf7nSHLGj342KZJtK3oOjCxVrsjteGRyekpKe6Jagrssjq1QOVNIyRmU428fdl"
              "\/lWILDAnSFSMZNiOzzQ=="},
     "requested_token_type": ["bearer", "mac_dms", "website_cookies"]
   }
   try:
     response = requests.post(FlexUnlimited.routes.get("GetAuthToken"),
                              headers=FlexUnlimited.allHeaders.get("AmazonApiRequest"), json=payload).json()
     return response.get("response").get("success").get("tokens").get("bearer").get("access_token")
   except Exception as e:
     Log.error("Unable to authenticate to Amazon Flex. Please provide a valid Amazon Flex username and password.")
     sys.exit()
예제 #21
0
    def _handle_message(self, frame):
        """Handle incoming text frame

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        json_obj = json.loads(str(frame.payload.strip()))

        if "cmd" in json_obj:
            # run the command
            parts = json_obj["cmd"].split('|')
            Command.run_command(parts[0], parts[1], self, json_obj['args'])

        elif "msg" in json_obj:
            # send the message back to the room at large
            self.send(json_obj['msg'])

        else:
            Log.add(json_obj, Log.NOTICE)
예제 #22
0
    def send_bytes(self, data):
        """Send raw data back to the client

        Parameters
        ----------
        data : string

        Returns
        -------
        Boolean
        """
        try:
            Log.add(data, Log.NOTICE)
            asyncore.dispatcher_with_send.send(self, data)
            self._buffer = ""
            return True
        except:
            Log.add("Error sending bytes with dispatcher")

        return False
예제 #23
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def send_bytes(self, data):
        """Send raw data back to the client

        Parameters
        ----------
        data : string

        Returns
        -------
        Boolean
        """
        try:
            Log.add(data, Log.NOTICE)
            asyncore.dispatcher_with_send.send(self, data)
            self._buffer = ""
            return True
        except:
            Log.add("Error sending bytes with dispatcher")

        return False
예제 #24
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def _handle_message(self, frame):
        """Handle incoming text frame

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        json_obj = json.loads(str(frame.payload.strip()))

        if "cmd" in json_obj:
            # run the command
            parts = json_obj["cmd"].split('|')
            Command.run_command(parts[0], parts[1], self, json_obj['args'])

        elif "msg" in json_obj:
            # send the message back to the room at large
            self.send(json_obj['msg'])

        else:
            Log.add(json_obj, Log.NOTICE)
예제 #25
0
    def __init__(self, port=4423, handler=Handler):
        """Create a websocket server

        Parameters
        ----------
        port : int
        handler : Object
        """
        Log.add("Server starting")

        # start parent
        asyncore.dispatcher.__init__(self)

        # assign variables
        self._port = port
        self._handler = handler

        # setup server
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind(("", port))
        self.listen(1)
예제 #26
0
	def __init__(self):
		self.conf = ConfUtil.zen(__file__)

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

		self.server = Server(
			self.conf['snpp']['host'],
			self.conf['snpp']['port']
		)
예제 #27
0
	def __init__(self):
		zen = ConfUtil.zen()

		conf = ConfUtil.zen(__file__)

		conf['localhost'] = zen['localhost']

		self.conf = conf

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)
예제 #28
0
  def run(self):
    Log.info("Starting job search...")
    while self.__retryCount < self.retryLimit:
      if not self.__retryCount % 50:
        print(self.__retryCount, 'requests attempted\n\n')

      offersResponse = self.__getOffers()
      if offersResponse.status_code == 200:
        currentOffers = offersResponse.json().get("offerList")
        currentOffers.sort(key=lambda pay: int(pay['rateInfo']['priceAmount']),
                           reverse=True)
        for offer in currentOffers:
          offerResponseObject = Offer(offerResponseObject=offer)
          self.__processOffer(offerResponseObject)
        self.__retryCount += 1
      else:
        Log.error(offersResponse.json())
        break
    Log.info("Job search cycle ending...")
    Log.info(f"Accepted {len(self.__acceptedOffers)} offers in {time.time() - self.__startTimestamp} seconds")
예제 #29
0
class ZenSNPP(IZen, Client):

	server = None

	log = None

	def __init__(self):
		self.conf = ConfUtil.zen(__file__)

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

		self.server = Server(
			self.conf['snpp']['host'],
			self.conf['snpp']['port']
		)

	def get(self):
		boxes = []

		for box in sorted(self.conf['boxes']):
			url = 'http://%s:81/gsm1.html' % self.conf['boxes'][box]

			try:
				response = urlopen(url, timeout=self.conf['timeout'])

				if response.getcode() != 200:
					continue
			except URLError:
				continue

			html = response.read()

			if 'ERROR' in html:
				continue

			info = html.split()

			_, _, _, _, _, _, _, signal, _ = info

			signal = signal.replace(',', '.')
			signal = float(signal)
			signal = int(signal)

			if signal < 2 or signal == 99:
				continue

			boxes.append(box)

		if len(boxes) == 0:
			raise MyException

		return boxes

	def post(self, box, to, data):
		to = ';'.join(map(str, to))

		url = 'http://%s/source/send_sms.php' % self.conf['boxes'][box]

		data = {
			'username'	: 'admin',
			'pwd'		: 'zenoss',
			'from'		: 'Zenoss',
			'nphone'	: to,
			'outCh'		: 'GSM1',
			'testo'		: data
		}

		data = urlencode(data)

		request = Request(url, data)

		try:
			response = urlopen(request, timeout=self.conf['timeout'])

			if response.getcode() != 200:
				raise MyException
		except URLError:
			raise MyException

	def sms(self, host, allow, packet):
		i = isinstance(packet['to'], int)

		targets = [packet['to']] if i else packet['to']['phones']

		if not allow:
			debug = DebugUtil.sms(host, targets, packet['data'])

			self.log.info('Message dropped %s' % debug)

			return

		try:
			boxes = self.get()

			if all(d not in packet['data'] for d in self.conf['devices']):
				boxes = [boxes.pop(0)]

			for box in boxes:
				self.post(box, targets, packet['data'])

				smsfrom = {
					'host'	: host,
					'box'	: box
				}

				debug = DebugUtil.sms(smsfrom, targets, packet['data'])

				self.log.info('Message sent %s' % debug)
		except MyException:
			if i:
				self.log.critical('Test message not sent')

				return

			mail = DictUtil.copy(self.conf['mail'])

			mail['to'] = packet['to']['mails']
			mail['body'] = packet['data']

			debug = DebugUtil.mail(host, mail)

			if Mail.sendraw(mail):
				self.log.info('Mail sent %s' % debug)
			else:
				self.log.critical('Mail not sent %s' % debug)

	def run(self):
		try:
			self.log.clear()

			while True:
				read = self.server.select()

				for socket in read:
					if self.server.accept(socket):
						try:
							client, ip, packet = self.server.recv()

							client = ClientProxy(client)

							self.server.attach(client)

							host = Util.hostname(ip)

							d = {'host': host}

							self.send(d)

							pkt = self.recv()

							self.sms(host, pkt['allow'], packet)
						except MyException:
							pass
					else:
						client = ClientProxy(socket)

						self.server.dettach(client)
		except KeyboardInterrupt:
			pass
예제 #30
0
    def handle_accept(self):
        """Manage new connections"""
        Log.add("New Connection")

        conn, addr = self.accept()
        Client(conn, addr, self)
예제 #31
0
 def test(client, args):
     """Test command"""
     Log.add("THE COMMAND WAS CALLED!!! WOOOOO", Log.NOTICE)
     Log.add(args, Log.NOTICE)
예제 #32
0
파일: Client.py 프로젝트: iam4423/WebSocket
    def _handle_frame(self, frame):
        """Direct incoming frames to the appropriate handler

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        if frame.opcode == 0x0:
            Log.add("We do not yet support continuation frames", Log.NOTICE)
        elif frame.opcode == 0x1:
            self._handle_message(frame)
        elif frame.opcode == 0x2:
            Log.add("We do not yet support binary frames", Log.NOTICE)
        elif frame.opcode == 0x3:
            Log.add("This will be used when i write the client from scratch (login)", Log.NOTICE)
        elif frame.opcode == 0x4:
            Log.add("This will be used when i write the client from scratch (cmd)", Log.NOTICE)
        elif frame.opcode == 0x8:
            self.handle_close()
        elif frame.opcode == 0x9:
            Log.add("pong needs to be added soon", Log.NOTICE)
        else:
            Log.add("unsupported opcode %d" % frame.opcode, Log.NOTICE)
예제 #33
0
    while 1:
        try:
            data = result_queue.get(20) #60s no data come , seem write done
            if count == 10:
                count = 0
                logger.info("insert result: %s", db.excutemany(SQLMgr.insert_stock_xg_many(), write_list))
                write_list = []
            count += 1
            write_list.append(data)
        except Exception as e:
            logger.info("db break %s", e)
            break
    #result_queue.task_done()

if __name__ == "__main__":
    Log("test.log")
    try:
        db = DB()
        all_data = db.query(SQLMgr.get_all_kline_info(Tools.get_today_str()))
        if all_data:
            for row in all_data:
                task_queue.put(row)
        print all_data
        worker_thread_num = 4
        worker_thread_list = []
        for i in range(worker_thread_num):
            t = threading.Thread(target=worker, args=(task_queue, result_queue))
            worker_thread_list.append(t)
            
        database_thread = threading.Thread(target=db_writer, args=(result_queue, db))
        database_thread.setDaemon(True)
예제 #34
0
__author__ = '4423'

import asyncore
from lib.WebSocket.Server import WebSocketServer
from lib.WebSocket.Handler import Handler
from lib.Log import Log

Log.enable_log(Log.NOTICE)
WebSocketServer(4423, Handler)
asyncore.loop(timeout=5)
예제 #35
0
class ZenTrap(IZen, Client):

	hosts = {}

	queue = []

	log = None

	udp = None

	@staticmethod
	def mac(ip):
		try:
			arp = sep + path.join('proc', 'net', 'arp')

			cmd = ['grep', ip, arp]

			fields = check_output(cmd).split()

			if len(fields) != 6:
				raise MacException

			_, _, _, mac, _, _ = fields

			if mac == '00:00:00:00:00:00':
				raise MacException

			return mac
		except CalledProcessError:
			raise MacException

	def __init__(self):
		self.conf = ConfUtil.zen(__file__)

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

	def loop(self):
		while True:
			try:
				packet = self.udp.recv()

				if packet['dst_port'] != self.conf['port']:
					continue

				self.queue.append(packet)
			except UdpException:
				pass

	def run(self):
		try:
			self.log.clear()

			packet = self.recv()

			self.hosts, self.udp = packet['hosts'], UDP()

			Thread(target=self.loop).start()

			while True:
				if len(self.queue) == 0:
					continue

				packet, targets = self.queue.pop(0), []

				for host in sorted(self.hosts):
					d = {'host': host}

					self.send(d)

					_packet = self.recv()

					if not _packet['allow']:
						continue

					if 'mac' not in self.hosts[host]:
						try:
							mac = ZenTrap.mac(self.hosts[host]['ip'])

							self.hosts[host]['mac'] = mac
						except MacException:
							continue

					packet['dst_mac'] = self.hosts[host]['mac']
					packet['dst_ip'] = self.hosts[host]['ip']

					self.udp.send(packet)

					targets.append(host)

				if len(targets) == 0:
					self.log.info('Trap dropped')
				else:
					to = ', '.join(map(Util.repr, targets))

					if len(targets) > 1:
						to = '(%s)' % to

					self.log.info('Trap sent (%s: %s)' % (Util.repr('To'), to))
		except KeyboardInterrupt:
			pass
예제 #36
0
class ZenSMTP(IZen, Client):

	log = None

	def __init__(self):
		self.conf = ConfUtil.zen(__file__)

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

	def process_message(self, peer, mailfrom, rcpttos, data):
		ip, _ = peer

		host = Util.hostname(ip)

		fr = '(%s, %s)' % (Util.repr(host), Util.repr(mailfrom))

		fr = '%s: %s' % (Util.repr('From'), fr)

		to = ', '.join(map(Util.repr, rcpttos))

		if len(rcpttos) > 1:
			to = '(%s)' % to

		to = '%s: %s' % (Util.repr('To'), to)

		msg = message_from_string(data)

		subject = Util.repr(msg['Subject'])

		subject = '%s: %s' % (Util.repr('Subject'), subject)

		debug = '(%s, %s, %s)' % (fr, to, subject)

		d = {'host': host}

		self.send(d)

		packet = self.recv()

		if packet['allow']:
			if Mail.send(mailfrom, rcpttos, data):
				self.log.info('Mail sent %s' % debug)
			else:
				self.log.critical('Mail not sent %s' % debug)
		else:
			self.log.info('Mail dropped %s' % debug)

	def run(self):
		try:
			self.log.clear()

			server = SMTPServer(
				(self.conf['smtp']['host'], self.conf['smtp']['port']),
				None
			)

			server.process_message = self.process_message

			loop()
		except KeyboardInterrupt:
			pass
예제 #37
0
class ZenStatus(IZen, Client):

	down = []

	hosts = {}

	log = None

	def __init__(self):
		zen = ConfUtil.zen()

		conf = ConfUtil.zen(__file__)

		conf['localhost'] = zen['localhost']

		self.conf = conf

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

	def mail(self, host, success):
		status = 'up' if success else 'down'

		mail = DictUtil.copy(self.conf['mail'])

		mail['subject'] %= status.upper()
		mail['body'] %= host

		debug = DebugUtil.mail(self.conf['localhost']['name'], mail)

		if Mail.sendraw(mail):
			self.log.info('Mail sent %s' % debug)
		else:
			self.log.critical('Mail not sent %s' % debug)

	def start(self, ip):
		up = False

		host = Util.hostname(ip)

		for _ in range(self.conf['start']['retries']):
			if 'backup' in self.hosts[host] and self.hosts[host]['backup']:
				up = True

				break

			cmd = ['ssh', ip, 'service', 'serviced', 'start']

			check_call(cmd, stderr=PIPE)

			cmd = ['ssh', ip, 'service', 'serviced', 'status']

			output = check_output(cmd, stderr=PIPE)

			if 'running' not in output:
				sleep(self.conf['start']['timeout'])

				continue

			cmd = ['ssh', ip, 'serviced', 'service', 'start', 'Zenoss.core']

			output = check_output(cmd)

			if 'started' not in output:
				sleep(self.conf['start']['timeout'])

				continue

			up = True

			break

		if host in self.down:
			if up:
				self.mail(host, True)

				self.down.remove(host)
		else:
			if not up:
				self.mail(host, False)

				self.down.append(host)

		return up

	def status(self):
		_hosts = self.hosts.keys()

		hosts = {h: {} for h in _hosts}

		for host in sorted(_hosts):
			if not self.hosts[host]['ping']:
				hosts[host]['status'] = False

				self.log.error(host)

				continue

			if self.start(self.hosts[host]['ip']):
				hosts[host]['status'] = True

				self.log.success(host)
			else:
				hosts[host]['status'] = False

				self.log.error(host)

		d = {'hosts': hosts}

		self.send(d)

	def run(self):
		try:
			worker = None

			self.log.clear()

			while True:
				packet = self.recv()

				self.hosts = packet['hosts']

				if worker is not None and worker.is_alive():
					continue

				self.log.clear()

				worker = Thread(target=self.status)

				worker.start()
		except KeyboardInterrupt:
			pass
예제 #38
0
    def _handle_frame(self, frame):
        """Direct incoming frames to the appropriate handler

        Parameters
        ----------
        frame : lib.WebSocket.Frame.Frame
        """
        if frame.opcode == 0x0:
            Log.add("We do not yet support continuation frames", Log.NOTICE)
        elif frame.opcode == 0x1:
            self._handle_message(frame)
        elif frame.opcode == 0x2:
            Log.add("We do not yet support binary frames", Log.NOTICE)
        elif frame.opcode == 0x3:
            Log.add(
                "This will be used when i write the client from scratch (login)",
                Log.NOTICE)
        elif frame.opcode == 0x4:
            Log.add(
                "This will be used when i write the client from scratch (cmd)",
                Log.NOTICE)
        elif frame.opcode == 0x8:
            self.handle_close()
        elif frame.opcode == 0x9:
            Log.add("pong needs to be added soon", Log.NOTICE)
        else:
            Log.add("unsupported opcode %d" % frame.opcode, Log.NOTICE)
예제 #39
0
import os
import sys
from lib.Log import Log
from lib.DDNS import DDNS
from lib.Config import Config

if __name__ == '__main__':
    # initial val
    BASE_PATH = os.path.abspath(os.path.dirname(__file__))

    # read config
    configObj = Config(BASE_PATH)
    logObj = Log(configObj)
    logger = logObj.get_logger()

    #debug print
    logger.debug('DOMAIN_DOMAIN {}'.format(configObj.DOMAIN_DOMAIN))
    logger.debug('DOMAIN_PREFIX {}'.format(configObj.DOMAIN_PREFIX))
    logger.debug('DOMAIN_TYPE {}'.format(configObj.DOMAIN_TYPE))
    logger.debug('DOMAIN_TTL {}'.format(configObj.DOMAIN_TTL))
    logger.debug('LOG_PATH {}'.format(configObj.LOG_PATH))
    logger.debug('LOG_FILE {}'.format(configObj.LOG_FILE))
    logger.debug('LOG_MAX_SIZE {}'.format(configObj.LOG_MAX_SIZE))
    logger.debug('LOG_BACKUP_COUNT {}'.format(configObj.LOG_BACKUP_COUNT))

    # initial ddnsObj
    ddnsObj = DDNS(configObj, logger)
    ddnsObj.run()

    # success exit
    sys.exit(configObj.SUCCESS_EXIT)
예제 #40
0
 def __init__(self):
     Log.__init__(self)
     self.path = config.get('EXCEL_CONFIG', 'SOURCE_PATH')
     self.back_path = config.get('EXCEL_CONFIG', 'BACKUPS_PATH')
예제 #41
0
class ZenPing(IZen, Client):

	hosts = {}

	mails = {
		'up'	: [],
		'down'	: []
	}

	down = []

	log = None

	@staticmethod
	def ping(ip):
		try:
			cmd = ['ping', '-c', '1', '-w', '1', '-q', ip]

			output = check_output(cmd)

			return ' 0% packet loss' in output
		except CalledProcessError:
			return False

	def __init__(self):
		zen = ConfUtil.zen()

		conf = ConfUtil.zen(__file__)

		conf['localhost'] = zen['localhost']

		self.conf = conf

		daemon = Util.filename(__file__)

		self.log = Log(daemon)

		Client.__init__(self, daemon, self.log)

	def mail(self, up):
		status = 'up' if up else 'down'

		mail = DictUtil.copy(self.conf['mail'])

		mail['subject'] %= status.upper()

		body = self.mails[status].pop()

		if len(self.mails[status]) > 0:
			hosts = ', '.join(self.mails[status])

			body = '%s & %s' % (hosts, body)

		mail['body'] %= body

		debug = DebugUtil.mail(self.conf['localhost']['name'], mail)

		if Mail.sendraw(mail):
			self.log.info('Mail sent %s' % debug)
		else:
			self.log.critical('Mail not sent %s' % debug)

	def run(self):
		try:
			self.log.clear()

			packet = self.recv()

			self.hosts = packet['hosts']

			hosts = {h: {} for h in self.hosts.keys()}

			while True:
				for host in sorted(self.hosts):
					if ZenPing.ping(self.hosts[host]['ip']):
						if host in self.down:
							self.down.remove(host)

							self.mails['up'].append(host)

						hosts[host]['ping'] = True

						self.log.success(host)
					else:
						if host not in self.down:
							self.down.append(host)

							self.mails['down'].append(host)

						hosts[host]['ping'] = False

						self.log.error(host)

				if len(self.mails['down']) > 0:
					self.mail(False)

					self.mails['down'] = []

				if len(self.mails['up']) > 0:
					self.mail(True)

					self.mails['up'] = []

				d = {'hosts': hosts}

				self.send(d)

				sleep(self.conf['sleep'])

				self.log.clear()
		except KeyboardInterrupt:
			pass