def __init__(self, path, objflags, flags=PBI_FLAGS_NONE, **kwargs): syslog(LOG_DEBUG, "pbi_base.__init__: enter") syslog(LOG_DEBUG, "pbi_base.__init__: path = %s" % path) syslog(LOG_DEBUG, "pbi_base.__init__: flags = 0x%08x" % (flags + 0)) self.path = path self.flags = flags self.args = "" self.error = None if objflags is None: objflags = [] for obj in objflags: if self.flags & obj: if obj.arg == True and obj.argname is not None and \ kwargs.has_key(obj.argname) and kwargs[obj.argname] is not None: self.args += " %s %s" % (obj, kwargs[obj.argname]) elif obj.arg == False: self.args += " %s" % obj syslog(LOG_DEBUG, "pbi_base.__init__: args = %s" % self.args) self.pipe_func = None if kwargs.has_key("pipe_func") and kwargs["pipe_func"] is not None: self.pipe_func = kwargs["pipe_func"] syslog(LOG_DEBUG, "pbi_base.__init__: leave")
def datagramReceived(self, datagram, addr): """This functions handles incoming probes. Each correctly received probe is unpickled, and the corresponding MAC and IP are stored. The neighbor information is stored as receveived and the timestamp for the sender is updated. """ # get the ip of the originating neighbor neighbor_ip = addr[0] # ignore probes from myself if neighbor_ip != self.own_ip: # deserialize the message neighbor_mac, data = pickle.loads(datagram) # store mac <-> ip association self.etx_data.set_mac(neighbor_ip, neighbor_mac) # store etx data self.etx_data.set_neighbor_info(neighbor_ip, data) # add timestamp to the list self.etx_data.add_timestamp(neighbor_ip) if EtxProbeProtocol.DEBUG: # remove old probes self.etx_data.remove_old_probes() syslog(LOG_DEBUG, "%s" % self.etx_data.get_debug_info(neighbor_ip))
def __init__(self, flags=PBI_FLAGS_NONE, **kwargs): syslog(LOG_DEBUG, "pbi_autobuild.__init__: enter") super(pbi_autobuild, self).__init__(PBI_AUTOBUILD, PBI_AUTOBUILD_FLAGS, flags, **kwargs) syslog(LOG_DEBUG, "pbi_autobuild.__init__: leave")
def post_auth(tupleList): try: # Convert the list of RADIUS request packet tuples into a dictionary # for easy lookup request = tupleListToDict(tupleList) mac = request['Calling-Station-Id'] username = request['User-Name'] # MAC addrs come in the form: "00-26-08-E8-90-F1" # We need them to be lowercased, dashes replaced with colons and # the quotation marks removed mac = saneMac(mac) # Usernames have quotation marks around them. # Impose sanity username = saneUsername(username) # Assign a VLAN vlan = vlanLookup(username, mac) # Return the VLAN return (radiusd.RLM_MODULE_UPDATED, ( ('Tunnel-Private-Group-Id', vlan), ('Tunnel-Type', 'VLAN'), ('Tunnel-Medium-Type', 'IEEE-802'), ), (('Post-Auth-Type', 'python'), )) except: e = sys.exc_info()[0] syslog(e) # If execution gets here, something is wrong. Fail closed # eg, no access if things are broken. Devices could end up # on a privileged VLAN return radiusd.RLM_MODULE_REJECT
def render_GET(self, request): """This functions handles the GET requests by returning a list of neighbors. All neighbors are returned, regardless via which interface they are reachable. For each neighbor, its MAC adress, the link quality (ETX), and the local interface the neighbor can be reached with is returned. """ # initialize dictionary to assemble all neighbors ret_val = {"node": self.hostname, "time": time.time(), "neighbors": []} # return neighborhood information for all interfaces for interface in self.interfaces.values(): # discard interfaces without data if not hasattr(interface, 'data'): continue # make sure the data is up to date interface.data.remove_old_probes() neighbors = interface.data.get_neighbors() for neighbor, quality in neighbors.items(): mac = interface.data.get_mac(neighbor) # ignore the item if we cannot determine the corresponding MAC if not mac: syslog(LOG_ERR, "Unable to determine MAC address for %s" % neighbor) continue # append the neighbor to the return dictionary ret_val["neighbors"].append({ "if_name": interface.name, "mac_address": mac, "quality": quality }) return simplejson.dumps(ret_val) + "\n"
def _handle_error(self, error): """Method for printing error messages. """ syslog(LOG_DEBUG, str(datetime.now()) + " Error: %s" % (error.getErrorMessage())) error.printTraceback() reactor.stop()
def __init__(self, flags=PBI_FLAGS_NONE, **kwargs): syslog(LOG_DEBUG, "pbi_update_hashdir.__init__: enter") super(pbi_update_hashdir, self).__init__(PBI_UPDATE_HASHDIR, None, flags, **kwargs) syslog(LOG_DEBUG, "pbi_update_hashdir.__init__: leave")
def writeOutput(source,data,outputMethod,dataType): if outputMethod == "syslog": for line in data: if dataType == "Domain": line = line[0]+ line[1] res = re.match(r"^[a-z0-9].*", line) if res is not None: line = res.group(0) if not line.startswith("iFrame"): # line = res.group(0) + "," + source + "\n" cef = 'CEF:0|CyberIntel|MalDomain|0.1|100|Known Malicious '+dataType+'|5|dhost='+line+' msg='+source elif dataType == "IP": cef = 'CEF:0|CyberIntel|MalIP|0.1|100|Known Malicious '+dataType+'|5|dst='+line+' msg='+source syslog(cef,syslogServer,syslogPort) elif outputMethod == "file": f = open(writeOutFileName, 'a') for line in data: if dataType == "Domain": line = line[0]+ line[1] res = re.match(r"^[a-z0-9].*", line) if res is not None: line = res.group(0) if not line.startswith("iFrame"): line = res.group(0) + "," + source + "\n" f.write(line) if dataType == "IP": line = line + "," + source + "\n" f.write(line) f.close()
def runcmd(cmdline, more=False): syslog(LOG_INFO, 'Running: ' + cmdline) retval = os.system('sudo ' + cmdline) if retval != 0: fatal('Error: ' + str(retval) + '\n') elif not more: log_debug('OK\n')
def check_output(cmd, **kwargs): if 'cwd' in kwargs: syslog(LOG_DEBUG, "%s cwd=%s" % (cmd, kwargs['cwd'])) else: syslog(LOG_DEBUG, "%s" % (cmd,)) with open(os.devnull, 'r+b') as devnull: return subprocess.check_output(cmd, stdin=devnull, **kwargs)
def starter(fpid): if fpid.find('.pid') == -1: fpid = fpid + '.pid' openlog(fpid.replace('.pid','')) fpid = os.getcwd()+'/'+fpid pidfile = fpid param = 'start' if len(sys.argv) > 1: param = sys.argv[1] if(param == 'kill'): os.unlink(fpid) os.system("killall -9 %s"%fpid.replace('.pid','')) print("killall -9 %s"%fpid.replace('.pid','')) exit(0) if param == "stop" or param == "restart": if os.path.isfile(fpid): f=open(fpid,'r') pid = f.readline() os.system("kill -9 %s" % (pid)) print("stoped %s" % (pid)) f.close() os.unlink(fpid) else: print "is already stopped" if(param == "restart"): param = "start" if(param == "stop"): exit(0) if(param == 'start'): if os.path.isfile(fpid): syslog(LOG_INFO, "second start") print "already started" exit(0) else: print("starting") daemon.createDaemon() signal.signal(signal.SIGTERM, cleanup) f=open(fpid,'w+') f.write(str(os.getpid())) f.close()
def type(self, output): devs = glob.glob(serial_glob) if len(devs): for dev in devs: self.sprint(dev, serial_baud_rate, output) else: syslog(LOG_WARNING, "No output devices found")
def get_devices(filename: str = '/etc/siddio/iocontrol.conf') -> List: ''' Loads the configuration and returns a list of tuples in the form of (pin, initial_state, description). ''' if hasattr(get_devices, 'conf'): return getattr(get_devices, 'conf') config = ConfigObj(filename) r = [] for k, v in config.iteritems(): if not k.startswith('Device'): syslog(LOG_WARNING, 'Unrecognised section in config: %s' % k) continue r.append( Device( v['name'], v.get('description', ''), v.get('tags', ''), int(v['pin']), bool(int(v.get('default', 0))), bool(int(v.get('invert', 0))), )) setattr(get_devices, 'conf', r) return r
def process_default(self, event): syslog(LOG_DEBUG, "caught %s on %s" % \ (event.maskname, os.path.join(event.path, event.name))) for wpath in config.wpaths: if os.path.realpath(wpath) in os.path.realpath(event.path): self.sync(wpath) break
def _getrels(self): rels, tags, dev_dict = get_relations() context = {'devices': rels, 'tags': tags} try: expr_on = parse(self.onquery) except Exception as e: syslog(LOG_ERR, 'Unable to parse %s %s' % (self.onquery, e)) raise try: expr_off = parse(self.offquery) except Exception as e: syslog(LOG_ERR, 'Unable to parse %s %s' % (self.offquery, e)) raise try: rel_devs_on = expr_on(context) except Exception as e: syslog(LOG_ERR, 'Error in running query: %s %s' % (self.onquery, e)) raise try: rel_devs_off = expr_off(context) except Exception as e: syslog(LOG_ERR, 'Error in running query: %s %s' % (self.offquery, e)) raise # Allow overlapping queries if len(rel_devs_off.intersection(rel_devs_on)): syslog(LOG_WARNING, 'Relations intersect!') rel_devs_off = rel_devs_off.difference(rel_devs_on) return dev_dict, rel_devs_on, rel_devs_off
def sprint(self, path, baud, payload): port = serial.Serial(path, baud) # The FTDI chip resets the Arduino on connect, wait for it to stabilise! time.sleep(wait_serial_init) pos = 0 for c in payload: if c not in serial_allowed_characters: print "replacing character '"+c+"' with '?'" c = "?" # Dumb line wrapping, if necessary if pos >= line_width and c != '\n': syslog(LOG_WARNING, "Force wrapping!") port.write('\n') time.sleep(wait_newline) pos = 0 port.write(c) if c == '\n': sleeptime = float(wait_newline) * float(pos) / float(line_width) + 0.2 pos = 0 time.sleep(sleeptime) else: pos = pos + 1 time.sleep(wait_char)
def main(): parser = OptionParser(option_list=OPTION_LIST, version="%prog " + ".".join(map(str, __version__))) (options, args) = parser.parse_args() if len(args) > 0: parser.error("too many arguments") logopt = LOG_PID | LOG_CONS | LOG_PERROR openlog("inosync", logopt, LOG_DAEMON) if options.verbose: setlogmask(LOG_UPTO(LOG_DEBUG)) else: setlogmask(LOG_UPTO(LOG_INFO)) load_config(options.config) syslog(LOG_DEBUG, "source " + config.wpath) syslog(LOG_DEBUG, "destination " + config.rpath) import fnmatch wm = WatchManager( exclude_filter=ExcludeFilter(map(fnmatch.translate, config.rexcludes))) ev = RsyncEvent() AsyncNotifier(wm, ev) mask = reduce(lambda x, y: x | y, [EventsCodes.ALL_FLAGS[e] for e in DEFAULT_EVENTS]) wm.add_watch(config.wpath, mask, rec=True, auto_add=True) asyncore.loop() sys.exit(0)
def sync(self, src, dst, include): """ build cmd and run process for each node :param src: source parent directory :param dst: destination parent directory :param include: file or directory changed :return: None """ args = [config.rsync, "-ltp", "--dirs", "--delete"] if config.extra: args.append(config.extra) if int(config.rspeed) > 0: args.append("--bwlimit=%s" % config.rspeed) if config.logfile: args.append("--log-file=%s" % config.logfile) args.append("--include='%s'" % include) args.append(src + '/') args.append("%s" + dst + '/') # to set node:dst in the nodes loop cmd = " ".join(args) for node in config.rnodes: ncmd = cmd % node # set node:dst syslog(LOG_DEBUG, "executing %s" % ncmd) process = os.popen(ncmd) for line in process: syslog(LOG_DEBUG, "[rsync] %s" % line.strip())
def check_output(cmd, **kwargs): if 'cwd' in kwargs: syslog(LOG_DEBUG, "%s cwd=%s" % (cmd, kwargs['cwd'])) else: syslog(LOG_DEBUG, "%s" % (cmd, )) with open(os.devnull, 'r+b') as devnull: return subprocess.check_output(cmd, stdin=devnull, **kwargs)
def get_no_of_pending_dnssec_actions(orderid): parameters = [('order-id', orderid)] parameters += [('no-of-records', 50)] parameters += [('page-no', 1)] parameters += [('action-type1', 'AddDNSSEC')] parameters += [('action-type2', 'DelDNSSEC')] cmd_url = build_sg_get_url(sg_api_baseurl_actions, 'search-current.json', parameters) json_data = sg_get_json(cmd_url) dbgprint('Current pending orders for order {0} "{1}"'.format( orderid, json_data)) if json_data == None: return -1 elif 'recsindb' in json_data: return int(json_data['recsindb']) elif json_data.get('status', None) == 'ERROR' and json_data.get( 'message', None) == 'No record found': syslog(LOG_INFO, 'No pending DNSSEC actions, proceeding') return 0 else: syslog( LOG_ERR, 'Unexpected JSON data returned from search for pending actions ({0})' .format(json_data)) return -1
def findLocker(self, name): """Lookup a locker in hesiod and return its path""" if name in self.attachtab: return self.attachtab[name] else: try: lockers = locker.lookup(name) except locker.LockerNotFoundError as e: if self.syslog_unknown: syslog(LOG_NOTICE, str(e)) return None except locker.LockerUnavailableError as e: if self.syslog_unavail: syslog(LOG_NOTICE, str(e)) return None except locker.LockerError as e: syslog(LOG_WARNING, str(e)) return None # TODO: Check if the first locker is valid # See Debathena Trac #583 for l in lockers: if l.automountable(): self.attachtab[name] = l if self.syslog_success: syslog(LOG_INFO, "Mounting "+name+" on "+l.path) return l.path syslog(LOG_WARNING, "Lookup succeeded for %s but no lockers could be attached." % (name)) return None
def datagramReceived(self, datagram, addr): """Handle received datagrams. """ request = datagram.split(":") if len(request) == 5 and request[0].upper() == Messaging.UPDATE_MSG: # received channel update node1, node2, channel, forward = request[1:] channel = int(channel) forward = int(forward) syslog(LOG_DEBUG, str(datetime.now()) + " UpdateProtocol:datagramReceived: received channel update for (%s_%s, %d, %s)" % (node1, node2, channel, forward)) # discard messages from ourselves if node1 == self.mica.node_name or node2 == self.mica.node_name: syslog(LOG_DEBUG, str(datetime.now()) + " UpdateProtocol:datagramReceived: node is part of the concerned vertex, discarding update message") return # get corresponding conflict graph vertex vertex = self.mica.conflict_graph.get_vertex(node1, node2) if vertex: # update channel in the conflict graph vertex.set_channel(channel) #print self.mica.conflict_graph.network_graph.get_adjacency_matrix() # forward the message if info is new and flag was set if forward: syslog(LOG_DEBUG, str(datetime.now()) + " UpdateProtocol:datagramReceived: forward flag set") reactor.callWhenRunning(self.mica.messaging.send_channel_update, vertex) else: syslog(LOG_DEBUG, str(datetime.now()) + " UpdateProtocol:datagramReceived: vertex %s_%s is not in the conflict graph" % (node1, node2)) else: syslog(LOG_DEBUG, str(datetime.now()) + " UpdateProtocol:datagramReceived: received unknown message: %s" % datagram)
def connectionMade(self): """This functions logs the connection. """ syslog( LOG_INFO, "Handling IPC connection from %s:%s" % (self.transport.getPeer().host, self.transport.getPeer().port))
def __init__(self, path, objflags, flags=JEXEC_FLAGS_NONE, **kwargs): syslog(LOG_DEBUG, "Jail_bait.__init__: enter") syslog(LOG_DEBUG, "Jail_bait.__init__: path = %s" % path) syslog(LOG_DEBUG, "Jail_bait.__init__: flags = 0x%08x" % (flags + 0)) self.path = path self.flags = flags self.args = "" if objflags is None: objflags = [] for obj in objflags: if self.flags & obj: if obj.arg == True and obj.argname is not None and \ kwargs.has_key(obj.argname) and kwargs[obj.argname] is not None: self.args += " %s %s" % (obj, kwargs[obj.argname]) elif obj.arg == False: self.args += " %s" % obj syslog(LOG_DEBUG, "Jail_bait.__init__: args = %s" % self.args) self.pipe_func = None if kwargs.has_key("pipe_func") and kwargs["pipe_func"] is not None: self.pipe_func = kwargs["pipe_func"] syslog(LOG_DEBUG, "Jail_bait.__init__: leave")
def process_item(self, item, spider): # data = dict(item) # self.post.insert(data) # return item try: # 查重处理 self.cursor.execute( """select id from doubanmovie where serial_number = %s""", item['serial_number']) # 是否有重复数据 repetition = self.cursor.fetchone() # 重复 if repetition: pass else: # 插入数据 self.cursor.execute( """insert into doubanmovie(serial_number, movie_name, introduce, star, evaluate, describe1) value (%s, %s, %s, %s, %s, %s)""", (item['serial_number'], item['movie_name'], item['introduce'], item['star'], item['evaluate'], item['describe'])) # 提交sql语句 self.connect.commit() except Exception as error: # 出现错误时打印错误日志 syslog(error) return item
def getboolean(self, section, option): try: return RawConfigParser.getboolean(self, section, option) except ValueError: rv = RawConfigParser.getboolean(self, 'DEFAULT', option) syslog(LOG_WARNING, "Invalid boolean value for %s in config file; assuming %s" % (option, rv)) return rv
def getfilename(self,filename): for d in self.cfg_flowdirs: f = d + '/' + filename if (os.path.exists(f) == True): return f #Serious error, filename not found, abort syslog('Could not find file (' + filename + ')') sys.exit(1)
def _allocate_interface(self, if_name, u, k): """Allocates a lock for the given interface and vertex-channel combination, to make sure that it is not used to satisfy another channel request while we are waiting for the reply. """ syslog(LOG_DEBUG, str(datetime.now()) + " _allocate_interface: allocating %s for (%s, %d)" % (if_name, u, k)) self._allocated_interfaces[if_name] = (u, k)
def syslogthis(what, val): """ Display a given information in syslog. @parameters : what = what to display. val = value to display. @return : none. """ syslog(LOG_DEBUG, "{0} = {1}".format(what, val))
def search_ridx_screen(self): for sc in list_screens(): self.dbg("Found screen: "+ sc.name) if (sc.name == self.cfg_idx_scr_name): self.dbg("Indexer Screen found") return sc syslog("RedisIndexerScreen was not found") sys.exit(1)
def clientConnectionFailed(self, connector, reason): """Log connection failed. """ host = connector.getDestination().host port = connector.getDestination().port syslog(LOG_DEBUG, str(datetime.now()) + " MessageClientFactory:clientConnectionFailed: connection to %s:%s failed: %s" % (host, port, reason.getErrorMessage())) self._retry()
def warning(message): ''' Print warning. < message: string message ''' openlog("V4LCapture", LOG_CONS | LOG_PID, LOG_USER) syslog(LOG_USER | LOG_WARNING, message)
def cleanup(self): pid = self.getjobstate(self.redis) if (pid > 0): syslog("There is a remaining job killing it " + str(pid)) try: os.kill(pid, signal.SIGKILL) except OSError, e: syslog(str(e))
def log(message): ''' Print non fatal error only. < message: string message ''' openlog("V4LCapture", LOG_CONS | LOG_PID, LOG_USER) syslog(LOG_USER | LOG_INFO, message)
def search_ridx_screen(self): for sc in list_screens(): self.dbg("Found screen: " + sc.name) if (sc.name == self.cfg_idx_scr_name): self.dbg("Indexer Screen found") return sc syslog("RedisIndexerScreen was not found") sys.exit(1)
def error(message): ''' Print error. < message: string message ''' openlog("V4LCapture", LOG_CONS | LOG_PID, LOG_USER) syslog(LOG_USER | LOG_ERR, message)
def getfilename(self, filename): for d in self.cfg_flowdirs: f = d + '/' + filename if (os.path.exists(f) == True): return f #Serious error, filename not found, abort syslog('Could not find file (' + filename + ')') sys.exit(1)
def cleanup(self): pid=self.getjobstate(self.redis) if (pid > 0): syslog("There is a remaining job killing it "+str(pid)) try: os.kill(pid, signal.SIGKILL) except OSError,e: syslog(str(e))
def __call__(self, msg): if self._syslog is None: openlog(ident=current_app.config.get('MONGOALCHEMY_DATABASE', 'msregistry-api'), logoption=(LOG_PID | LOG_CONS | LOG_NDELAY), facility=self._facility[current_app.config.get( 'AUDIT_LOG_FACILITY', 'authpriv').upper()]) syslog(msg)
def refresh_cache(self): syslog(LOG_INFO, "refresh cache") if os.path.exists(self.remote_cache_path): cmd = [self.git, 'fetch', '--quiet', '--prune'] check_call(cmd, cwd=self.remote_cache_path) else: cmd = [self.git, 'clone', '--quiet', '--mirror', self.remote, self.remote_cache_path] check_call(cmd)
def log(priority, eventtype, subjectum, objectum, **attrs): attlist = [] for (k, v) in attrs.items(): attlist.append(" %s=%s"%(k,v)) attstring = ",".join(attlist) message="event=%s, prio=%s, subject=%s, object=%s,%s"%(eventtype, priority, subjectum, objectum, attstring) if config.debug: sys.stderr.write(message+'\n') syslog(priority,message)
def write_failure_message(self, result_details, failure_message, feature, priority, scenario, step): result_details.add(" Error: %s\n" % (failure_message.partition('\n')[0])) message = "%s | %s%s | %s | %s%s | Error - %s" % ( self.step_status(step), self.feature_name(feature), priority, scenario['name'], step['keyword'], self.ascii_step_name(step), failure_message.partition('\n')[0]) syslog(LOG_NOTICE, message.encode('ascii', 'xmlcharrefreplace'))
def critical(message): ''' Print fatal error and exit. < message: string message ''' openlog("V4LCapture", LOG_CONS | LOG_PID, LOG_USER) syslog(LOG_USER | LOG_CRIT, message) sys.exit(1)
def write_step_description_and_status(self, result_details, feature, priority, scenario, step): result_details.add( " Step: [%s] %s%s\n" % ((self.step_status(step)), step['keyword'], step['name'])) syslog( LOG_NOTICE, "%s | %s%s | %s | %s%s" % ((self.step_status(step)), (self.feature_name(feature)), priority, scenario['name'], step['keyword'], self.ascii_step_name(step)))
def set_state(self, state: bool): syslog( LOG_INFO, 'Setting state %s for %s' % ('ON' if state else 'OFF', self.name)) self.state = state if self.invert: state = not state GPIO.output(self.pin, state) syslog(LOG_DEBUG, 'Pin %d set to %s' % (self.pin, state))
def write_step_description_and_status(self, result_details, feature, priority, scenario, step): result_details.add( " Step: [%s] %s%s\n" % ((self.step_status(step)), step['keyword'], step['name'])) message = "%s | %s%s | %s | %s%s" % ( (self.step_status(step)), (self.feature_name(feature)), priority, scenario['name'], step['keyword'], self.ascii_step_name(step)) syslog(LOG_NOTICE, message.encode('ascii', 'xmlcharrefreplace'))
def clientConnectionLost(self, connector, reason): """Log lost connection and retry. """ host = connector.getDestination().host port = connector.getDestination().port syslog(LOG_DEBUG, str(datetime.now()) + " MessageClientFactory:clientConnectionLost: connection to %s:%s lost: %s" % (host, port, reason.getErrorMessage())) if not self.received_answer: syslog(LOG_DEBUG, str(datetime.now()) + " MessageClientFactory:clientConnectionLost: did not receive an answer yet") self._retry()
def log_result_to_syslog(exitcode, message): if exitcode == 3: log_priority = LOG_ERR elif exitcode == 2: log_priority = LOG_CRIT elif exitcode == 1: log_priority = LOG_WARNING else: log_priority = LOG_NOTICE syslog(log_priority, "CHCK | %s@%s | %s" % (sys.argv[1], sys.argv[2], message))
def send2log(msg, loglevel=LOG_INFO, **kargs): """ Send the message msg to syslog """ msg = prepare2log(msg, loglevel, **kargs) # carefully send a message to syslog try: syslog(loglevel, msg) except Exception: pass
def print_data(interfaces): """Logs the neighbor data for all interfaces to the log file. Calls itself again later when the window has expired. """ for interface in interfaces.values(): # check if there is any neighborhood data available for the particular interface if hasattr(interface, 'data'): interface.data.remove_old_probes() syslog(LOG_DEBUG, "%s: %s" % (interface.name, interface.data.get_neighbors())) reactor.callLater(WINDOW, print_data, interfaces)
def fetch(self): params = {'q': '@Square', 'result_type': 'recent'} if self.latest is not None: params['since_id'] = self.latest result = self.session.get('https://api.twitter.com/1.1/search/tweets.json', params=params).json() if result['statuses'] and len(result['statuses']): tweets = result['statuses'] self.latest = tweets[0]['id_str'] syslog(LOG_INFO, "Latest tweet id is " + self.latest) return tweets return []
def connectionMade(self): """Send the request after the connection has been made. """ request = "%s:%d" % (Messaging.REQUEST_MSG, self.factory.k) syslog(LOG_DEBUG, str(datetime.now()) + " MessageClientProtocol:connectionMade: sending %s" % request) # send channel request and wait for reply self.sendLine(request) # set timeout for reply self.factory.timeout = reactor.callLater(5, self.transport.loseConnection)
def lock(self, tokens=None): """Lock the instance. """ if self._locked: syslog(LOG_DEBUG, str(datetime.now()) + " Lock:lock: instance already locked") else: syslog(LOG_DEBUG, str(datetime.now()) + " Lock:lock: %s instance" % util.red("locking")) self._locked = True if tokens: self._tokens.update(tokens)
def tupleListToDict(tupleList): # Initialize empty dictionary dict = {} try: for tuple in tupleList: dict[tuple[0]] = tuple[1] except: e = sys.exc_info()[0] syslog(e) return dict