def post(self,postid): md = self.get_argument('markdown') time_now = int(time()) user = self.current_user postid = int(postid) content = md_convert(md,notice=True,time=time_now,user=user['username'],db=self.db,postid=postid) post = self.db.posts.find_one({'_id':postid}) source = self.parse_user_agent() comment_reversed = reversed(post['comments']) for _ in range(min(len(post['comments']),5)):#look up in the recently 5 comment comment = comment_reversed.next() if comment['author'] == user['username'] and comment['content'] == content:#Reply has already been posted. self.redirect('/topics/'+str(postid)) return post['comments'].append({'author':user['username'], 'content':content, 'posttime':time_now, }) post['changedtime'] = time_now if source: post['comments'][-1]['source'] = source self.db.posts.save(post) try: del self.mc['index'] except KeyError: pass try: cache = self.mc[str(postid)] except KeyError: pass else: for i in range(len(post['comments'])): post['comments'][i]['location'] = str(i+1) cache[2] = self.render_string('modules/comments.html',db=self.db,time_span=time_span,post=post) self.mc[str(postid)] = cache self.redirect('/topics/'+str(postid)) url = '%s/topics/%s#reply-%s' % (self.application.settings['forum_url'],postid,len(post['comments'])) if user['twitter_bind'] and self.get_argument('twitter-sync') == 'yes': for i in set(html_killer.findall(content)): content = content.replace(i,'')#不知道为什么,直接用sub返回的是空字符串。 for i in set(username_finder.findall(content)): u = self.db.users.find_one({'username':i}) if u and 'twitter' in u: content = content.replace(u'@'+i,u' @'+user['twitter']) self.twitter_request( '/statuses/update', post_args={'status': u'%s %s' % (content,url)}, access_token=user['access_token'],callback=self._on_post) ping(self.application.settings['forum_title_e'],self.application.settings['forum_url'],url)
def gather(): '''Check how the nodes we're responsible for are doing. To keep the architecture simple, for now the nodes are arranged in a unidirectional ring. Each node is responsible for watching the node below it, skipping over any nodes it detects as down or not having monitord running. ''' lookup = {True: {True:'up -monitord', False:'up -ssh -monitord'}, False:{True:'-ping +ssh', False:'down'}} data = {} nodes = neighbours.nodes print 'Pinging downstream nodes:' count=0 for node in nodes: count+=1 if count>conf.MAX_WATCH_NODES: break up = ping.ping(node) ssh = ping.has_ssh(node) mond = ping.has_monitord(node) # if it's got monitord, it can handle things further down the list if mond: break # otherwise, we need to keep the server informed and keep scanning state=lookup[up][ssh] # don't bother telling the server things it knows if node in cache: if cache[node]==state: continue # do tell it new stuff, but cache it for later cache[node] = data[node] = state print '\tnode',node,'is',state return data
def test_db_servers_ubuntu_ami_in_australia(self): """ Find database servers with the Ubuntu AMI in Australia region """ args = self.parser.parse_args(['database', '-R', 'australia', '-A', 'idbs81839']) result = ping(args.tags, args.region, args.ami) self.assertIsNotNone(result)
def monitor( hosts, timeout = 2, length = 56, ttl = 128, interval = 10, verbose = False ): """Monitor by ping""" hosts = [[host, None, None] for host in hosts] while True: for i in range(len(hosts)): updown, journey, packet = ping.ping(hosts[i][0], timeout, length, ttl) now = time.asctime() if hosts[i][1] != updown: hosts[i][1] = updown hosts[i][2] = now print("[%s]\n %s changed to %s" % ( hosts[i][2], hosts[i][0], ping.status[hosts[i][1]]) ) else: pass if verbose: print(" Data:\n%s" % (packet)) time.sleep(interval)
def run(self): if ping.ping(self.DEBUG): self.streamStatus = True self.check() else: self.streamStatus = False self.check() time.sleep(60) return
def do_run(self): '''Returns time to ping a host.''' try: delay = float(ping(self.config['host'], 5)) except: # TODO: should be time TimeOut and some other errors return () return (("default", delay), )
def post(self): title = xhtml_escape(self.get_argument('title')) assert len(title)<51 user = self.current_user md = self.get_argument('markdown') posts = self.db.posts tags = [] for x in set(xhtml_escape(self.get_argument('tags').lower()).split(' ')): tags.append(x) post = self.db.posts.find_one({'title':title,'author':user['username'],'tags':tags}) if post:#Topic has already been posted. self.redirect('/topics/'+str(post['_id'])) return time_now = int(time()) tid = self.db.settings.find_and_modify(update={'$inc':{'post_id':1}}, new=True)['post_id'] posts.insert({'_id':tid, 'title':title, 'author':user['username'], 'content':md_convert(md,notice=True,time=time_now,user=user['username'],db=self.db,postid=tid), 'comments':[], 'posttime':int(time()), 'changedtime':int(time()), 'tags':tags, }) for tag in tags: self.db.tags.update({'name':tag}, {'$inc':{'count':1}}, True) try: del self.mc['index'] del self.mc['tagcloud:10'] del self.mc['tagcloud:False'] except KeyError: pass self.redirect('/topics/'+str(tid)) url = '%s/topics/%s' % (self.application.settings['forum_url'],tid) if user['twitter_bind'] and self.get_argument('twitter-sync') == 'yes': self.twitter_request( '/statuses/update', post_args={'status': u'%s %s' % (title,url)}, access_token=user['access_token'],callback=self._on_post) ping(self.application.settings['forum_title_e'],self.application.settings['forum_url'],url)
def read(self, host): """Ping host. Return 'OK' if packets returns, 'FAILURE' otherwise.""" import os env = os.environ.get('watcher-env', 'production') packets = ping(host, 2, env=env) if packets < 2: return 'FAILURE' return 'OK'
def run(self): while True: try: pingval = ping.ping(host) except: pingval = {'minping': -1, 'avgping': -1, 'timeout': True} rrd.update_rrd(rrdfile, pingval) self.emit( rrd_thread.signal, pingval ) self.emit( self.signal, str( round( float(pingval['minping']), 2 ) ) ) time.sleep(1)
def run(protocol, files, csvfile): shared.seed_random(1234) for path in sorted(glob.glob(files)): state = shared.load_json(path) (node_count, link_count) = shared.json_count(state) print(f'run {protocol} on {path}') network.apply(state=state, link_command=get_tc_command, remotes=remotes) shared.sleep(10) for offset in range(0, 60, 2): tmp_ms = shared.millis() traffic_beg = traffic.traffic(remotes) traffic_ms = shared.millis() - tmp_ms tmp_ms = shared.millis() software.start(protocol) software_ms = shared.millis() - tmp_ms # Wait until wait seconds are over, else error shared.sleep(offset) paths = ping.get_random_paths(state, 2 * 200) paths = ping.filter_paths(state, paths, min_hops=2, path_count=200) ping_result = ping.ping(paths=paths, duration_ms=2000, verbosity='verbose', remotes=remotes) traffic_end = traffic.traffic(remotes) sysload_result = shared.sysload(remotes) software.clear(remotes) # add data to csv file extra = (['node_count', 'traffic_ms', 'software_ms', 'offset_ms'], [node_count, traffic_ms, software_ms, offset * 1000]) shared.csv_update(csvfile, '\t', extra, (traffic_end - traffic_beg).getData(), ping_result.getData(), sysload_result) network.clear(remotes)
def run(protocol, files, csvfile): for path in sorted(glob.glob(files)): state = shared.load_json(path) (node_count, link_count) = shared.json_count(state) # Limit node count to 300 if node_count > 300: continue print(f'run {protocol} on {path}') network.apply(state=state, link_command=get_tc_command, remotes=remotes) shared.sleep(10) software_start_ms = shared.millis() software.start(protocol, remotes) software_startup_ms = shared.millis() - software_start_ms shared.sleep(300) start_ms = shared.millis() traffic_beg = traffic.traffic(remotes) paths = ping.get_random_paths(state, 2 * 200) paths = ping.filter_paths(state, paths, min_hops=2, path_count=200) ping_result = ping.ping(remotes=remotes, paths=paths, duration_ms=300000, verbosity='verbose') traffic_ms = shared.millis() - start_ms traffic_end = traffic.traffic(remotes) sysload_result = shared.sysload(remotes) software.clear(remotes) network.clear(remotes) # add data to csv file extra = (['node_count', 'traffic_ms', 'software_startup_ms'], [node_count, traffic_ms, software_startup_ms]) shared.csv_update(csvfile, '\t', extra, (traffic_end - traffic_beg).getData(), ping_result.getData(), sysload_result)
def custom_test_connection(ser=-1): list = serial.tools.list_ports.comports() print(*list) if (ser == -1): ser = serial.Serial(port='COM4', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=5) response = optimized_start_up_nbiot(ser) response = optimized_setup_PDP_context(ser, response_history=response["response_history"], retries=3, custom_delay=1000) response = ping(ser, response_history=response["response_history"]) print(response) ser.close() return response
def ping(self): """ ping this host @returns: True on success, False on failure """ logging.info('pinging %s' % self.name_or_ip) try: response = ping.ping(self.name_or_ip) if not response: logging.info("no response from %s" % (self.name_or_ip)) return False else: logging.info("%s is alive" % (self.name_or_ip)) return True except: logging.error('ping error') return False
def check(ip): success_ping = 0 delay = 0 for i in xrange(COUNT): try: d = ping(ip, TIMEOUT, PSIZE) if d is not None: delay += d success_ping += 1 except socket.gaierror: # todo: log error return False, "error" except socket.error: return False, "down" if success_ping == 0: return False, "down" return True, '{:0.4f}ms'.format((delay * 1000 / success_ping))
def check(ip): success_ping = 0 delay = 0 for i in xrange(COUNT): try: d = ping(ip, TIMEOUT, PSIZE) if d is not None: delay += d success_ping += 1 except socket.gaierror: # todo: log error return False, "error" except socket.error: return False, "down" if success_ping == 0: return False, "down" return True, '{:0.4f}ms'.format((delay * 1000 / success_ping))
def ipcheck(self): ip = unicode(self.ipEdit.text()) ping_flag, ping_result = ping(ip) if ping_flag: self.ipokbutton.setText(u'连接正常') self.tabs.show() else: self.ipokbutton.setText(u'连接错误') self.tabs.hide() mainwindow = self.parent.parent() mainwindow.statusBar().showMessage(ping_result) if self.v2Radio.isChecked(): self.ver = 2 elif self.VqRadio.isChecked(): self.ver = 3
def set_ntp(ntp_server): bad_ntp = '' if ping(ntp_server): nch.send_config_commands(['clock timezone GMT 0', f'ntp server {ntp_server}']) else: print('ping failed') bad_ntp += 'Bad NTP Server, ' outputs_dict = nch.send_show_commands('sh ntp status') outputs_list = convert_output_to_list(outputs_dict) #pprint(outputs_dict) for output in outputs_list: hostname, ip, command, command_output = output if 'Clock is unsynchronized' in command_output: result = bad_ntp + 'Clock not in Sync' elif 'Clock is synchronized' in command_output: result = bad_ntp + 'Clock in Sync' summary[hostname].append(result)
def ping_once(session, host): latency = None error = None when = datetime.datetime.now() try: latency = ping.ping(host) print(latency) except Exception as e: error = str(e) traceback.print_exc() ping_inst = models.Ping( date = when, latency = latency, error = error, ) session.merge(ping_inst) session.commit()
def run(csv_document, ip_column, ping_count): total_reachable = 0 total_unreachable = 0 list_iterator = iter(csv_document) next(list_iterator) #Skip header column for row in list_iterator: addr = row[ip_column] if ping.ping(addr, ping_count): total_reachable += 1 print(f"{colors.LIGHT_GREEN}{addr:<20}{'[+][OK]':<12}{colors.NC}") else: total_unreachable += 1 print(f"{colors.LIGHT_RED}{addr:<20}{'[-][FAIL]':<12}{colors.NC}") print("Total Reachable : {}".format(str(total_reachable))) print("Total Unreachable : {}".format(str(total_unreachable)))
def run(protocol, csvfile): for path in sorted(glob.glob(f'../../data/grid4/*.json')): state = shared.load_json(path) (node_count, link_count) = shared.json_count(state) print(f'run {protocol} on {path}') network.apply(state=state, link_command=get_tc_command, remotes=remotes) shared.sleep(10) software_start_ms = shared.millis() software.start(protocol, remotes) software_startup_ms = shared.millis() - software_start_ms shared.sleep(30) paths = ping.get_random_paths(state, 2 * link_count) paths = ping.filter_paths(state, paths, min_hops=2, path_count=link_count) ping_result = ping.ping(remotes=remotes, paths=paths, duration_ms=30000, verbosity='verbose') sysload_result = shared.sysload(remotes) software.clear(remotes) # add data to csv file extra = (['node_count', 'software_startup_ms'], [node_count, software_startup_ms]) shared.csv_update(csvfile, '\t', extra, ping_result.getData(), sysload_result) network.clear(remotes) # abort benchmark when less then 40% of the pings arrive if ping_result.transmitted == 0 or (ping_result.received / ping_result.transmitted) < 0.4: break
def run_all(config_dict, log_folder, verbose): dns_logger = create_logger("dns", log_folder, verbose) name_dict = config_dict.get("dns", {}) for name in name_dict: expected = name_dict[name].get("expected") dns_logger.info(';'.join(str(x) for x in resolve(name, expected))) ping_logger = create_logger("ping", log_folder, verbose) for host in config_dict.get("ping",[]): ping_logger.info(';'.join(str(x) for x in ping(host))) ping6_logger = create_logger("ping6", log_folder, verbose) for host in config_dict.get("ping6", []): ping6_logger.info(';'.join(str(x) for x in ping6(host))) http_logger = create_logger("http", log_folder, verbose) url_dict = config_dict.get("url", {}) for url in url_dict: http_logger.info(';'.join(str(x) for x in request(url, url_dict[url])))
def monitor(hosts, timeout=2, length=56, ttl=128, interval=10, verbose=False): hosts = [[host, None, None] for host in hosts] while True: for i in range(len(hosts)): updown, journey, packet = ping.ping(hosts[i][0], timeout, length, ttl) now = time.asctime() if hosts[i][1] != updown: hosts[i][1] = updown hosts[i][2] = now print "[%s]\n %s changed to %s" % (hosts[i][2], hosts[i][0], ping.status[hosts[i][1]]) else: pass if verbose: print " Data:\n%s" % (packet) time.sleep(interval)
def update_gui(option, obj): try: if option == 0: tmp = obj.ping.tmp.text() + "\n" obj.ping.tmp.setText(tmp + ping(obj.ping.field.text())[0]) if option == 1: tmp = obj.trace.tmp.text() + "\n" obj.trace.tmp.setText(tmp + trace(obj.trace.field.text())) if option == 2: tmp = obj.dns.tmp.text() + "\n" obj.dns.tmp.setText(tmp + nslookup(obj.dns.field.text())) except Exception: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText( "Error! \n\n-Make Sure you entered correct dst. \n-Make sure you have admin permissions." ) msg.setWindowTitle("Error") msg.exec_()
def ping_services(): for service in Service.query.all(): response = ping.ping(service.address) if response == 0 and service.current_state != ServiceState.unspecified: service.previous_state = service.current_state service.time_of_last_change_of_state = datetime.datetime.now() service.current_state = ServiceState.unspecified # history history = History(service.address, service.name, ServiceState.unspecified, service.time_of_last_change_of_state, service.organization_id) db.session.add(history) elif response >= 200 and response < 300 and service.current_state != ServiceState.up: service.previous_state = service.current_state service.time_of_last_change_of_state = datetime.datetime.now() service.current_state = ServiceState.up # history history = History(service.address, service.name, ServiceState.up, service.time_of_last_change_of_state, service.organization_id) db.session.add(history) # notifications if service.users: send_notification("icon_blue", service, "UP") elif response >= 400 and response < 600 and service.current_state != ServiceState.down: service.previous_state = service.current_state service.time_of_last_change_of_state = datetime.datetime.now() service.current_state = ServiceState.down # history history = History(service.address, service.name, ServiceState.down, service.time_of_last_change_of_state, service.organization_id) db.session.add(history) # notifications if service.users: send_notification("icon_red", service, "DOWN") db.session.commit() db.session.close()
def trace(target): """ :param target: Target url/ip to be traced :return: trace output for gui """ _, dest_ip = ping.ping(target) output = [] for _ttl in range(1, Constants.MAX_TTL): # Create and send ICMP Packets packet = IP(dst=target, ttl=_ttl) / ICMP() reply = sr1(packet, verbose=0) # If reply is empty if reply is None: continue latency = round((reply.time - packet.sent_time) * 1000 - Constants.LATENCY_OFFSET) # Special Print for destination if reply.src in dest_ip: tmp = "Hop {0}: at {1} {3} Response Time: {2}\n".format( _ttl, reply.src, latency, "X") output.append(tmp.replace("X", " " * (45 - len(tmp)))) output.append("-----------------------------------------\n") tmp = "Reached {0} in {1} hops {3} Response Time: {2}\n".format( target, _ttl, latency, "X") output.append(tmp.replace("X", " " * (45 - len(tmp)))) break # Print Log else: tmp = "Hop {0}: at {1} {3} Response Time: {2}\n".format( _ttl, reply.src, latency, "X") output.append(tmp.replace("X", " " * (45 - len(tmp)))) return ''.join(output)
def run(protocol, tasks, csvfile): for path, gateways in tasks: state = shared.load_json(path) (node_count, link_count) = shared.json_count(state) # Limit node count to 300 if node_count > 300: continue print(f'run {protocol} on {path}') network.apply(state=state, remotes=remotes) shared.sleep(10) software_start_ms = shared.millis() software.start(protocol, remotes) software_startup_ms = shared.millis() - software_start_ms shared.sleep(30) start_ms = shared.millis() traffic_beg = traffic.traffic(remotes) paths = ping.get_paths_to_gateways(state, gateways) ping_result = ping.ping(remotes=remotes, paths=paths, duration_ms=300000, verbosity='verbose') traffic_ms = shared.millis() - start_ms traffic_end = traffic.traffic(remotes) sysload_result = shared.sysload(remotes) software.clear(remotes) network.clear(remotes) # add data to csv file extra = (['node_count', 'traffic_ms', 'software_startup_ms'], [node_count, traffic_ms, software_startup_ms]) shared.csv_update(csvfile, '\t', extra, (traffic_end - traffic_beg).getData(), ping_result.getData(), sysload_result)
def log_pings(TIME_LIMIT=5, HOST="8.8.8.8"): plot = [] # array of tuples of (success to ms or failures to ms CURR_TIME = datetime.now() DIFF = datetime.now() - CURR_TIME while DIFF.total_seconds() < TIME_LIMIT: ret = None try: ret = ping(HOST, "1") except Exception as e: print(e) DIFF = datetime.now() - CURR_TIME plot.append((DIFF.total_seconds(), ret)) time.sleep(.05) with open("net_report.csv", "w") as outfile: outfile.write("error,timings\n") for point in plot: outfile.write(str(point[0]) + "," + str(point[1]) + "\n")
def sensor_ping(host, count=1, timeout=1, interval=0.2, sleep_time=60, output=False, log_db=False, db_name=None, sensor_id=None): conn = None while True: result = ping.ping(host, count, timeout, interval) if output == True: print(result) if log_db == True: if conn == None: conn = db.conn(db_name) attributes = { "response": str(result[0]), "reason_code": str(result[1]), "response_time": float(result[2]) } db.log_sensor(conn, sensor_id, result[0], json.dumps(attributes)) time.sleep(sleep_time)
t.start() def check_alive(upstream): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(UPSTREAM_TIMEOUT) try: addr = (upstream['ip'], upstream['port']) sock.connect(addr) logging.debug("Upstream %s is ALIVE", addr) except Exception, e: if sock is not None: sock.close() logging.debug("Upstream %s is DEAD", addr) return try: ping((upstream['ip'], upstream['port'])) UpstreamQueue.put((time.time(), upstream)) except Exception, e: logging.debug("Ping to %s failed: %s", addr, e) def set_upstream(cfg): while True: ts, upstream = UpstreamQueue.get() addr = (upstream['ip'], upstream['port']) if cfg.last_update == 0 or ts - cfg.last_update > MIN_INTERVAL: logging.info("Setting upstream to: %s", addr) cfg.last_update = ts cfg.upstream_addr = addr cfg.upstream_auth = upstream['auth'] cfg.upstream_ssl = upstream['ssl'] cfg.upstream_username = upstream['username']
def run(self): while True: pingval = ping.ping(host) self.emit(self.signal, str(round(float(pingval['avgping']), 2))) time.sleep(1)
def print_ping(address): result = ping(address) if result is not None: print(address + " - " + gethostbyaddr(address)[0])
def test_ping(): assert ping.ping('www.yahoo.com') == 'UP'
def Ping(self, request, context): ping_reply = ping.ping(request.host, request.count, request.timeout) return message_pb2.PingReply(**ping_reply)
await client.change_presence(status=discord.Status.online, activity=activity) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('mb!help'): embed = discord.Embed(title='Commands', color=discord.Colour.green()) embed.add_field( name="User Commands:", value="**mb!info (id)**: Gives info about a MimoBox User.") embed.set_footer(text='Request by: ' + message.author.name + ' | ' + str(datetime.now()), icon_url=message.author.avatar_url) await message.channel.send(embed=embed) if message.content.startswith('mb!info'): chosen_id = message.content.split('mb!info ', 1)[1] gotten_info = get_UserInfo(chosen_id, message.author) if gotten_info: await message.channel.send(embed=gotten_info) else: await message.channel.send("Error : ID doesn't exist") ping() client.run(os.getenv('TOKEN'))
def test_ping(): assert ping(None)['response'] == 'pong'
def MessageStatus(self, msg, status): if status == Skype4Py.cmsReceived or status == Skype4Py.cmsSent: # I have no idea what this line does other than it makes the bot respond to its own messages, and it only works in private chat #if not msg.Sender.Handle in self.blacklist: if msg.Body[0] == "!" and msg.Sender.Handle != "everythingbot": print "[" + str(datetime.now())[:-7] + "] " + msg.Sender.Handle + ": " + msg.Body # !help if re.match("!help(?!\S)", msg.Body): msg.Chat.SendMessage(help()) # !ping elif re.match("!ping(?!\S)", msg.Body): msg.Chat.SendMessage(ping()) # !members elif re.match("!members(?!\S)", msg.Body): msg.Chat.SendMessage(members(msg.Chat.Members)) # !profile elif re.match("!profile(?!\S)", msg.Body): try: skypeName = msg.Body[9:] msg.Chat.SendMessage(profile(skypeName, msg.Chat.Members)) except IndexError: msg.Chat.SendMessage("Skype username required for profile lookup.") # !orangecrush # If you're reading this on the Github repo, congratulations on being the first to figure out that it's been public all along. elif re.match("!orangecrush(?!\S)", msg.Body): msg.Chat.SendMessage("!orangecrush") # !lenny elif re.match("!lenny(?!\S)", msg.Body): msg.Chat.SendMessage(self._lenny) # !friendcodes elif re.match("!friendcodes(?!\S)", msg.Body) or re.match("!fc(?!\S)", msg.Body): msg.Chat.SendMessage(friendcodes()) # !gostats elif re.match("!gostats(?!\S)", msg.Body): msg.Chat.SendMessage("http://csgo-stats.com/" + msg.Body[9:]) # !tableflip elif re.match("!tableflip(?!\S)", msg.Body): msg.Chat.SendMessage(self._tableflip) # !tableset elif re.match("!tableset(?!\S)", msg.Body): msg.Chat.SendMessage(self._tableset) # !coinflip elif re.match("!coinflip(?!\S)", msg.Body): msg.Chat.SendMessage(coinflip()) # URL titles # This is the opt-into title code. #elif re.match("!title(?!\S)", msg.Body): # if re.match('!title http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE): # url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE) # msg.Chat.SendMessage(url_get(url.group(0))) # else: # msg.Chat.SendMessage("Invalid URL.") # This is the opt-out of title code. elif re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE) and not re.search("!nt(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot": url = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', msg.Body, re.IGNORECASE) msg.Chat.SendMessage(url_get(url.group(0))) # !removebot elif re.match("!removebot(?!\S)", msg.Body): if removebot(msg.Sender.Handle): msg.Chat.Leave() # !restartbot elif re.match("!restartbot(?!\S)", msg.Body): if removebot(msg.Sender.Handle): msg.Chat.SendMessage("Restarting bot.") execfile("~halbrdbot.py") sys.exit() # !twitch (channel) # !gostats elif re.match("!twitch(?!\S)", msg.Body): # msg.Chat.SendMessage("http://twitch.tv/" + msg.Body[8:]) msg.Chat.SendMessage(twitch(msg.Body[8:])) # !requestfunction (string) #elif re.match("!requestfunction(?!\S)", msg.Body): # msg.Chat.SendMessage(requestfunction(msg.Sender.Handle, msg.Body[17:])) #elif msg.Body == "!chatname": # msg.Chat.SendMessage(msg.Chat.Name) # !hug elif re.match("!hug(?!\S)", msg.Body) and msg.Sender.Handle != "everythingbot": msg.Chat.SendMessage(hug(msg.Sender.FullName, msg.Body[5:])) # !bothug elif re.match("!bothug(?!\S)", msg.Body): msg.Chat.SendMessage(bothug(msg.Body[8:])) # !blacklist #elif re.match("!blacklist(?!\S)", msg.Body): # msg.Chat.SendMessage(blacklist(msg.Sender.Handle, msg.Body[11:])) # !strats elif re.match("!strats(?!\S)", msg.Body): msg.Chat.SendMessage(strats(msg.Body[8:])) # !lwc elif re.match("!lwc(?!\S)", msg.Body): msg.Chat.SendMessage("Literally who cares.\nhttp://lynq.me/lwc.mp4") # lmao # Keep this as the last thing that gets checked elif re.search("l+ *m+ *a+ *o+", msg.Body, re.IGNORECASE) and msg.Sender.Handle != "everythingbot": msg.Chat.SendMessage("ayyy")
hostname = socket.gethostname() logfile = "/var/log/watchdog/PS4IsUp.log" flog = open(logfile,"a") sec = 0 while True: try: now = datetime.datetime.now().strftime("%H:%M:%S") print(now) if sec % sleep_IP == 0: myIP = get_ip_address(myInterface) #print("hostname : " + hostname) #print("myIP : "+myIP) r = requests.get("http://192.168.0.147/monitor/getEvent.php?eventFct=add&host={0}&type=ip&text={1}".format(hostname,myInterface+":"+myIP)) #print(r.json()) #r = requests.get("http://192.168.0.147/monitor/getEvent.php?eventFct=getLastEventByType&host=hostname&type=ip") #print(r.json()) print(now + " ip : " + myIP) if sec % 10 == 0: if ping("192.168.0.40"): log_PS4IsUp() except Exception as error: print("there was an exception : " + str(error)) sec += 1 sleep(1)
def pinger(self, ip): status = ping.ping(ip) if status is None: return False else: return True
def latency(host): while True: for pong, online in ping('10.221.64.1'): print(pong + 'ms')
__author__ = 'marco' from osx_notifier import Notifier from files import GetFiles from files import ReadFilesRsync from ping import ping from ssh_sync import ssh from volume_sync import volume get = GetFiles() Send = Notifier() user = ReadFilesRsync(get.GetUser()) server = (ReadFilesRsync(get.GetServer())) mode = ReadFilesRsync(get.GetMode()) #Checking if server is online serverping = server.ReadFile() ping = ping(serverping) ping.pingServer() #Checking which protocol is used proto = ReadFilesRsync(get.GetProto()) if proto.ReadFile() == "ssh": sync = ssh() sync.sshSync() else: sync = volume() sync.volumeSync()
log("Resetting the relay... We've done this " + str(concurrent_relay_resets) + plural_or_not + " so far.") relay.toggle(15) log("Reset done. Waiting for " + str(backoff_time) + " before continuing to monitor.") time.sleep(backoff_time) while True: if concurrent_failures == retry_max: reset() concurrent_failures = 0 else: if ping(hostname): if not success_state: log("Connection up. Everything's good.") success_state = True if concurrent_failures > 0: concurrent_failures = 0 log("Connection re-established. Resetting counters.") if concurrent_relay_resets > 0: concurrent_relay_resets = 0 else: success_state = False concurrent_failures += 1 if concurrent_failures == 1: log("Connection down. Monitoring...") else: log("Connection still down...")
if len(URL)==0: URL='http://134.128.196.10:9081/iservuc/ServiceGate/SimpleXMLGate' if __name__ == '__main__': tempPath=os.path.split(sys.argv[0])#取文件名的路径。 if tempPath[0]=='':#文件名采用绝对路径,而是采用相对路径时,取工作目录下的路径 config_dir=os.getcwd()+os.sep else: config_dir=tempPath[0]+os.sep alarmObjectMap={} log = logging.getLogger() log.setLevel(logging.DEBUG) h1 = logging.handlers.RotatingFileHandler(config_dir+'ping.log',maxBytes=2097152,backupCount=20) #h1.setLevel(logging.INFO) f=logging.Formatter('%(asctime)s %(levelname)s %(message)s') h1.setFormatter(f) log.addHandler(h1) ping.__log__=log getCommonConfig() try: while IS_START=='1': getCommonConfig() for (ipname,ipvalue) in ipAddressList: ping.ping(ipvalue) time.sleep(RECYCLE_TIMES) if IS_START=='0': log.info('IS_START value=:'+IS_START+' so exit!') except Exception: log.exception('系统报错') h1.close()
from files import ReadFilesRsync from ping import ping from ssh_sync import ssh from volume_sync import volume get = GetFiles() Send = Notifier() user = ReadFilesRsync(get.GetUser()) server =(ReadFilesRsync(get.GetServer())) mode = ReadFilesRsync(get.GetMode()) #Checking if server is online serverping = server.ReadFile() ping = ping(serverping) ping.pingServer() #Checking which protocol is used proto = ReadFilesRsync(get.GetProto()) if proto.ReadFile() == "ssh": sync = ssh() sync.sshSync() else: sync = volume() sync.volumeSync()
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from ping import ping from mailer import MailTransport, Email if not ping('thecus'): Email(To='*****@*****.**', Subject='Fehler: Thecus nicht erreichbar').send( MailTransport() )
f.write(msg + "\n") f.close() # main --------------------------------------------------- thisScript = sys.argv[0] to_email = params.to_email PS4 = "192.168.0.40" sec = 0 while True: try: if sec % 60 == 0: log(ping(PS4)) if sec % 60 * 10 == 0: if ping(PS4): mailNotif(to_email, thisScript) except Exception as error: msg = "there was an exception : " + str(error) print(msg) mySimpleSendMail( "Problem with script " + thisScript + " (exception !)", msg, to_email) sec += 1 sleep(1)
parser = argparse.ArgumentParser(description='Website Crawler') parser.add_argument('site', type=str, help='Url to Scan') parser.add_argument('-o', type=str, help='Output File (optional)') args = parser.parse_args() site = args.site file = args.o def url_handler(site): #Handle url global site_handled site_handled = site if "http://" not in site: if "https://" not in site: site_handled = "https://" + site if site_handled[-1:] == "/": site_handled = site_handled[:-1] return site_handled url_handler(site) ping.ping(site_handled) #get site contents website_url = requests.get(site_handled) soup = BeautifulSoup(website_url.content, 'html.parser', from_encoding="iso-8859-1") crawl.cr(soup, website_url, site_handled, file)
def main(target): # Check to see if we have a target if not target: print("[!] No target specified. See help or other options") exit() else: # If we do then check to make sure its formatted correctly match = re.search('http:\/\/www\.', target) match2 = re.search('www\.', target) if match: print('[-] Remove http://www. from target for best results') exit() elif match2: print('[-] Remove www from subdomain') exit() if not os.path.exists('data/ipout'): print("[!] Missing crimeflare database! Downloading and unzipping...") crimedb() try: print(''' ..,co88oc.oo8888cc,.. o8o. ..,o8889689ooo888o"88888888oooc.. .88888 .o888896888".88888888o'?888888888889ooo.... a888P ..c6888969""..,"o888888888o.?8888888888"".ooo8888oo. 088P ..atc88889"".,oo8o.86888888888o 88988889",o888888888888. 888t ...coo688889"'.ooo88o88b.'86988988889 8688888'o8888896989^888o 888888888888"..ooo888968888888 "9o688888' "888988 8888868888'o88888 ""G8889""'ooo888888888888889 .d8o9889""' "8688o."88888988"o888888o . o8888'""""""""""' o8688" 88868. 888888.68988888"o8o. 88888o. "8888ooo. '8888. 88888.8898888o"888o. "888888' "888888' '""8o"8888.8869888oo8888o . . :.:::::::::::.: . . :.::::::::.: .atc. : ::.:."8888 "888888888888o :..8888,. "88888888888. .:o888.o8o. "866o9888o アu刀イ乇尺 = アム丂丂ノ√乇 んu刀イ乇尺 :888.o8888. "88."89". . 89 888888 "88":. ENUMERATE THE TARGET :. '8888o . "8888.. 888888o. "888889, . : :.:::::::.: :. ''') # Lists to hold our ips cloudflare_ips = [] not_cloudflare_ips = [] print("[+] Enumerate subdomains passively") subdomains_dict = subdomains.subdomains_search(target) print("[+] Querying whois info") whois_text, whois_emails, whois_dict = whois_search.whois_target(target) print("[+] Reverse lookup domains by email then check if IP resolves") email_list = [] if isinstance(whois_emails, basestring): whois_emails = [whois_emails] for email in whois_emails: # Add list of most popular hosting companies ignore_emails = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] if email in ignore_emails: print("[!] Skipping email: %s" % email) else: email_list.append(reversewhois.query_rwhois(email)) print(email_list) except: print("Error connecting=> obtaining info") exit() # Output data into something redable print("[+] Target: %s" % target) print("[+] Domain: %s" % subdomains_dict.get('domain')) print("[+] Emails found in WHOIS data:") for email in whois_emails: print("[+] Email found: %s" % email) print("[+] Name servers found in WHOIS data:") for ns in whois_dict.name_servers: print("[+] Name server: %s " % ns) print("[+] Get data out of dnsdumpster:") for x in subdomains_dict.get('dns_records').get('host'): print('[+] HOST (A): %s' % x) if subdomains_dict.get('dns_records').get('dns'): for x in subdomains_dict.get('dns_records').get('dns'): print('[+] DNS: %s' % x) if subdomains_dict.get('dns_records').get('txt'): for x in subdomains_dict.get('dns_records').get('txt'): print('[+] TXT: %s' % x) if subdomains_dict.get('dns_records').get('mx'): for x in subdomains_dict.get('dns_records').get('mx'): print('[+] MX: %s' % x) print("[+] Checking for ssl certs for any subdomains using crt.sh") crtsh_results = crt_sh.req_crtsh(target) # Begin HTML generator with open(target + now + 'report.html', 'w') as html: html.write(''' <!DOCTYPE html> <html> ''') html.write('<head><title>Site: '+ target + now + '</title>') html.write(''' <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/png" href="assets/img/favicon.ico"> <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.css"> <link rel="stylesheet" href="assets/css/styles.css"> </head> <body> <div class="container"> <header> <div class="page-header"> ''') # Add target to banner html.write('\t\t\t<h1>Site: ' + target + '</h1> Scan conducted on: ' + now + '</div>\r') html.write(''' </header> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"><a class="navbar-brand navbar-link" href="#">Home </a> <button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"> <span class="sr-only">Toggle navigation</span><span class="icon-bar"></span> <span class="icon-bar"></span><span class="icon-bar"></span></button> </div> <div class="collapse navbar-collapse" id="navcol-1"> <ul class="nav navbar-nav"> <li class="active" role="presentation"><a href="#dnsdumpster">DNS DUMPSTER</a></li> <li role="presentation"><a href="#whois">WHOIS </a></li> <li role="presentation"><a href="#reversewhois">REVERSE WHOIS</a></li> <li role="presentation"><a href="#SSL_certs">CRT.SH SSL</a></li> <li role="presentation"><a href="#shodan">SHODAN </a></li> </ul> </div> </div> </nav> <hr> <span id="dnsdumpster">Host A Records</span> <div class="table-responsive"> <table class="table"> <thead> <tr> <th data-sortable="true">Domain </th> <th data-sortable="true">Header </th> <th data-sortable="true">Country </th> <th data-sortable="true">Provider </th> <th data-sortable="true">Reverse DNS</th> <th data-sortable="true">AS </th> <th data-sortable="true">IP</th> <th data-sortable="true">Cloudflare</th> </tr> </thead> <tbody>''') # Fill in DNS Dumpster into table # A Records if subdomains_dict.get('dns_records').get('host'): for x in subdomains_dict.get('dns_records').get('host'): # Build list of cloudlfare IPs cloudflare_host_records = subdomains.build_cloudlfare_iplist(x.get('provider'), x.get('ip')) if cloudflare_host_records: cloudflare_ips.append(cloudflare_host_records) else: not_cloudflare_ips.append(x.get('ip')) html.write('\t\t\t<tr>') html.write('\t\t\t<td>' + x.get('domain') + '</td>\r') html.write('\t\t\t<td>' + x.get('header') + '</td>\r') html.write('\t\t\t<td>' + x.get('country') + '</td>\r') html.write('\t\t\t<td>' + x.get('provider') + '</td>\r') html.write('\t\t\t<td>' + x.get('reverse_dns') + '</td>\r') html.write('\t\t\t<td>' + x.get('as') + '</td>\r') html.write('\t\t\t<td>' + x.get('ip') + '</td>\r') html.write('\t\t\t<td>' + subdomains.check_provider_for_cloudflare(x.get('provider')) + '</td>\r') html.write('\t\t\t</tr>\r') else: html.write('\t\t\t<tr>No data found</tr>') html.write(''' </tbody> </table> </div>''') html.write('''<hr> <span>DNS Records</span> <div class="table-responsive"> <table class="table"> <thead> <tr> <th data-sortable="true">Domain </th> <th data-sortable="true">Header </th> <th data-sortable="true">Country </th> <th data-sortable="true">Provider </th> <th data-sortable="true">Reverse DNS</th> <th data-sortable="true">AS </th> <th data-sortable="true">IP</th> <th data-sortable="true">Cloudflare</th> </tr> </thead> <tbody>''') if subdomains_dict.get('dns_records').get('dns'): for x in subdomains_dict.get('dns_records').get('dns'): # Build list of cloudlfare IPs cloudflare_dns_records = subdomains.build_cloudlfare_iplist(x.get('provider'), x.get('ip')) if cloudflare_dns_records: cloudflare_ips.append(cloudflare_dns_records) else: not_cloudflare_ips.append(x.get('ip')) html.write('\t\t\t<tr>') html.write('\t\t\t<td>' + x.get('domain') + '</td>\r') html.write('\t\t\t<td>' + x.get('header') + '</td>\r') html.write('\t\t\t<td>' + x.get('country') + '</td>\r') html.write('\t\t\t<td>' + x.get('provider') + '</td>\r') html.write('\t\t\t<td>' + x.get('reverse_dns') + '</td>\r') html.write('\t\t\t<td>' + x.get('as') + '</td>\r') html.write('\t\t\t<td>' + x.get('ip') + '</td>\r') html.write('\t\t\t<td>' + subdomains.check_provider_for_cloudflare(x.get('provider')) + '</td>\r') html.write('\t\t\t</tr>') else: html.write('\t\t\t<tr>No data found</tr>') html.write(''' </tbody> </table> </div>''') html.write('''<hr> <span>MX Records</span> <div class="table-responsive"> <table class="table"> <thead> <tr> <th data-sortable="true">Domain </th> <th data-sortable="true">Header </th> <th data-sortable="true">Country </th> <th data-sortable="true">Provider </th> <th data-sortable="true">Reverse DNS</th> <th data-sortable="true">AS </th> <th data-sortable="true">IP</th> <th data-sortable="true">Cloudflare</th> </tr> </thead> <tbody>''') if subdomains_dict.get('dns_records').get('mx'): for x in subdomains_dict.get('dns_records').get('mx'): # Build list of cloudlfare IPs cloudflare_mx_records = subdomains.build_cloudlfare_iplist(x.get('provider'), x.get('ip')) if cloudflare_mx_records: cloudflare_ips.append(cloudflare_mx_records) else: not_cloudflare_ips.append(x.get('ip')) html.write('\t\t\t<tr>') html.write('\t\t\t<td>' + x.get('domain') + '</td>\r') html.write('\t\t\t<td>' + x.get('header') + '</td>\r') html.write('\t\t\t<td>' + x.get('country') + '</td>\r') html.write('\t\t\t<td>' + x.get('provider') + '</td>\r') html.write('\t\t\t<td>' + x.get('reverse_dns') + '</td>\r') html.write('\t\t\t<td>' + x.get('as') + '</td>\r') html.write('\t\t\t<td>' + x.get('ip') + '</td>\r') html.write('\t\t\t<td>' + subdomains.check_provider_for_cloudflare(x.get('provider')) + '</td>\r') html.write('\t\t\t</tr>') else: html.write('\t\t\t<tr>No data found</tr>') html.write(''' </tbody> </table> </div> <div class="row"> <div class="col-md-6"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th id="whois">Emails Found in WHOIS</th> <th id="whois">Have I Been Pwned?</th> </tr> </thead> <tbody> ''') if whois_emails: for email in whois_emails: pwned_email = haveibeenpwned.pwned_email_check(email) html.write('\t\t\t<tr><td>' + email + '</td><td>' + pwned_email + '</td></tr>\r') print("[+] Whois email %s | Pwned: %s" % (email, pwned_email)) else: html.write('\t\t\t<tr><td>No emails found</td></tr>\r') html.write(''' </tbody> </table> </div> </div> <div class="col-md-6"> ''') html.write('<p><p><span>WHOIS Info:</span><p><pre>' + whois_text + '</pre>') html.write(''' </div> </div> </div> <div class="container"> <hr> <b> <span id="reversewhois">Reverse WHOIS</span> </b> <p> <p> ''') # We have a list of dictionary. Values in dictionary are a list. So K, V= is a list i = 1 # For loop (label each email) # Loop over list and get each dictionary item for emails in email_list: # Loop over key, value (list) for key in emails: print("[+] Emails: %s" % key) html.write(' <div class="panel-group" role="tablist" aria-multiselectable="true" id="mailAccordion' + str(i) + '">') html.write('''<div class="panel panel-default">''') html.write('<div class="panel-heading" role="tab" id="heading' + str(i) + '> <h4 class="panel-title">') html.write('<a class="collapsed" role="button" data-toggle="collapse" data-parent="#mailAccordion-' + str(i) + '" aria-expanded="true" href="#mails_mail' + str(i) +'">') html.write(key) html.write('</a></h4></div><div class="panel-collapse" id="mails_mail' + str(i) + '" role="tabpanel">') html.write(''' <div class="panel-body"><span> </span> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Domain </th> </tr> </thead> <tbody> ''') # Add 1 to i for each loop i += 1 # For each value add a cell for domains in emails.itervalues(): for v in domains: print("[+] Domain associated with email %s: %s" % (key, v)) html.write('<tr><td>' + v + '</td></tr>') html.write(''' </tbody> </table> </div> </div> </div> </div> ''') html.write(''' <p> <hr> <p> <p> <div class="container"><span id="SSL_certs"><strong>SSL Certs from CRT.SH</strong></span> <p> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Subdomain </th> <th>IP</th> <th>Cloudflare</th> </tr> </thead> <tbody>''') if crtsh_results: print("[+] CRT SH Results:") for subdomain in crtsh_results: resolved_ip = str(dns_resolve.dns_query(subdomain)) # Holy double negative! (aka If this IP resolved then check from cloudlflare) if not "Not resolved" in resolved_ip: check_resolved_ip = subdomains.in_cloudlflare_ip(resolved_ip) if check_resolved_ip: resolved_ip_cloudflare = "Cloudflare enabled" cloudflare_ips.append(resolved_ip) else: resolved_ip_cloudflare = "Not cloudflare" not_cloudflare_ips.append(resolved_ip) else: resolved_ip_cloudflare = "Not resolved" html.write('<tr><td>' + str(subdomain) + '</td><td>' + resolved_ip + '</td><td>'+ resolved_ip_cloudflare + '</td></tr>' ) print("[+] Subdomain: %s | Resolved IP: %s | Cloudflare: %s" % (str(subdomain), resolved_ip, resolved_ip_cloudflare)) else: html.write('<tr><td>No results found</td><td>No results found</td></tr>') html.write(''' </tbody> </table> </div> </div> ''') # Remove duplicate IPs from both lists not_cloudflare_ips = list(set(not_cloudflare_ips)) cloudflare_ips = list(set(cloudflare_ips)) if cloudflare_ips: html.write(''' <p> <hr> <p> <p> <div class="container"><span id="crimeflare"><strong>Crimeflare</strong></span> <p> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>Cloudflare IP </th> <th>Resolved IP (Crimeflare)</th> </tr> </thead> <tbody>''') crime_ip = subdomains.crimeflare(target) if crime_ip: not_cloudflare_ips.append(crime_ip) print("[+] Target IP: %s | Discovered IP: %s" % (target, crime_ip)) html.write('<tr><td>' + target + '</td><td>'+ crime_ip + '</td></tr>') else: html.write('<tr><td>' + target + '</td><td>Unresolved IP</td></tr>') html.write(''' </tbody> </table> </div> </div> ''') if not_cloudflare_ips: html.write(''' <p> <hr> <p> <p> <div class="container"><span id="crimeflare"><strong>IP Breakdown</strong></span> <p> <div class="table-responsive"> <table class="table"> <thead> <tr> <th>IP </th> <th>Ping</th> <th>Curl</th> <th>Shodan</th> </tr> </thead> <tbody>''') for ip in not_cloudflare_ips: html.write('<tr><td>' + ip + '</td><td><pre>'+ ping.ping(ip) + '</pre></td><td>add curl (todo)</td><td>add shodan (todo)</td></tr>') html.write(''' </tbody> </table> </div> </div> ''') html.write(''' </div> <section></section> </div> <script src="assets/js/jquery.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> </body> </html>''')
from ping import ping import time from datetime import datetime while 1 == 1: ping('127.0.0.1') time.sleep(60)
def giveInstruction(serverNum, primaryServerIP, secundaryServerIP): """ This function checks if the server is the primary server. If so it will always be active. If the server is secundary it will set itself to inactive. All the data is gathered from the gpio pi and the web api and the parameters are obtained from the local file. A calculation is made based on the gathered data and the parameters. This calculation will result in an instruction for the gpio pi. The instruction is written to the local webserver. Afterwards a connection will be made with the database to write the gathered data to it. """ global buienradarAPI # set buienradarAPI to be global variable # on the secundary server sync parameters with primary if serverNum == 2: if ping(primaryServerIP) == "Online": serverFunctions.synchroniseParameters(primaryServerIP) # on the primary server sync parameters with the secundary elif serverNum == 1: if ping(secundaryServerIP) == "Online": serverFunctions.synchroniseParameters(secundaryServerIP) while True: # loop until the program gets interrupted if serverNum == 1: activity = "active" # primary server is always active elif serverNum == 2: # sync parameters if the server is inactive activity = serverFunctions.serverCheck(primaryServerIP) if activity == "active": print("server active") elif activity == "inactive": print("server inactive") serverFunctions.synchroniseParameters(primaryServerIP) waterHeight, gateStatus = serverFunctions.gpioRequest( ) # request gpio data paramWindDirection, paramWindSpeed, paramWaterHeight, paramRainFall = serverFunctions.getParameters( ) # get parms # print parameters obtained obtained by this function print("Main obtained parameters: ", paramWindDirection, paramWindSpeed, paramWaterHeight, paramRainFall) while True: # wait for API call if call is not yet made try: print( buienradarAPI ) # try to print buienradarAPI (raises exception if its None) break except (NameError, ValueError, TypeError): print("API call not yet made") time.sleep(1) continue # get data from API (API call is made asynchronous on another thread, see function doApiCall()) windSpeed = buienradarAPI["windsnelheidMS"] windDirection = buienradarAPI["windrichtingGR"] rainFall = buienradarAPI["regenMMPU"] if paramWaterHeight == "-": # check if the parameter should be disabled waterHeightBoolean = False else: waterHeightBoolean = int(waterHeight) >= int(paramWaterHeight) if paramRainFall == "-": # check if parameter should be disabled rainFallBoolean = False else: if rainFall == "-": rainFall = 0 rainFallBoolean = float(rainFall) >= int(paramRainFall) # set up a boolean for wind data to be in range with parameters windRange = range( int(paramWindDirection) - 45, int(paramWindDirection) + 45) windDirectionBoolean = int(windDirection) in windRange if paramWindSpeed == "-": # check if the parameter should be disabled windSpeedBoolean = False else: windSpeedBoolean = float(windSpeed) >= int(paramWindSpeed) # give instruction if waterHeightBoolean | (windDirectionBoolean & windSpeedBoolean) | rainFallBoolean: instruction = "close" else: instruction = "open" # write instruction to webserver writingJson.serverWriteJson(serverNum, activity, instruction, paramWaterHeight, paramWindDirection, paramWindSpeed, paramRainFall) # save data to database if server is active server if activity == "active": try: database.makeDatabaseConnection() database.insertIntoDatabase(gateStatus, waterHeight, windSpeed, windDirection, serverNum, rainFall) database.closeDatabaseConnection() except (TimeoutError, mysql.connector.errors.InterfaceError ): # except connection errors print("Could not connect to database") try: # catch keyboard interrupts time.sleep(10) except KeyboardInterrupt: print("Stopped") break