def _idle_poweroff(self): if not self.powerOffWhenIdle: return if self._waitForHeaters: return if self._waitForTimelapse: return if self._printer.is_printing() or self._printer.is_paused(): return if (uptime() / 60) <= (self._settings.get_int(["idleTimeout"])): self._tasmota_mqtt_logger.debug( "Just booted so wait for time sync.") self._tasmota_mqtt_logger.debug( "uptime: {}, comparison: {}".format( (uptime() / 60), (self._settings.get_int(["idleTimeout"])))) self._reset_idle_timer() return self._tasmota_mqtt_logger.debug( "Idle timeout reached after %s minute(s). Turning heaters off prior to powering off plugs." % self.idleTimeout) if self._wait_for_heaters(): self._tasmota_mqtt_logger.debug("Heaters below temperature.") if self._wait_for_timelapse(): self._timer_start() else: self._tasmota_mqtt_logger.debug( "Aborted power off due to activity.")
async def info_command(self, ctx): svmem = psutil.virtual_memory() day = int(uptime() / 3600 / 24) hours = int(uptime() / 3600 - day * 24) minute = int(uptime() / 60) - day * 24 * 60 - hours * 60 second = int(uptime()) - day * 24 * 3600 - hours * 3600 - minute * 60 statsEmbed = discord.Embed(title=f"📃 {self.client.user.name} Hakkında", color=0xd8f500, timestamp=ctx.message.created_at) statsEmbed.add_field( name="Teknik Bilgiler", value= f"{self.client.user.name} Versiyonu: **v{get_version_number()}**\nPython Versiyonu: **{platform.python_version()}**\nDiscord.py Versiyonu: **{discord.__version__}**\nÇalışma Zamanı: **{day} Gün, {hours} Saat, {minute} Dakika, {second} Saniye**\nCPU(İşlemci): **{get_cpu_info()['brand_raw']}**\nFiziksel Çekirdekler: **{psutil.cpu_count(logical=False)}**\nToplam Çekirdek: **{psutil.cpu_count(logical=True)}**\nKullanımdaki İşlemci Yüzdesi: **%{psutil.cpu_percent(interval=0)}**\nOS(İşletim Sistemi): **{platform.platform()}**\nKullanılan Bellek: **{get_size(svmem.used)}**\nKullanılabilir Bellek: **{get_size(svmem.available)}**\nToplam Bellek: **{get_size(svmem.total)}**\nKullanımdaki Bellek Yüzdesi: **%{svmem.percent}**\nSunucu Bölgesi: **Google Cloud - Hollanda**" ) statsEmbed.set_footer( text="PHOENIX#7103 tarafından 💖 ile geliştirildi!", icon_url=ctx.author.avatar_url) file = discord.File("images/evos.png", filename="evos.png") statsEmbed.set_thumbnail(url="attachment://evos.png") await ctx.send(file=file, embed=statsEmbed) logger.info(f"General | Evosinfo | Tarafından: {ctx.author}")
def rHistory(self, mac, rssi): if self.lastSeen.get(mac) == None: self.lastSeen[mac] = uptime() else: timeSince= (uptime() - self.lastSeen[mac]) / 60 if timeSince >= 2: del self.rssiHistory[mac] self.lastSeen[mac] = uptime() else: self.lastSeen[mac] = uptime() if self.rssiHistory.get(mac) == None: self.seen[mac] = 0 self.sten[mac] = 0 self.rssiHistory[mac] = [0] * 10 self.rssiHistory[mac][0] = rssi else: if self.sten[mac] == 0: self.sten[mac] = 1 cnt = self.seen[mac] + 1 if cnt == 10: cnt = 0 self.sten[mac] = 2 self.rssiHistory[mac][cnt] = rssi self.seen[mac] = cnt if self.sten[mac] == 0: r = rssi elif self.sten[mac] == 1: r = round(sum(self.rssiHistory[mac])/(cnt + 1)) else: r = round(sum(self.rssiHistory[mac])/10) return r
def getUt(formatted=True): """system uptime""" import uptime if formatted: de = str(datetime.timedelta(seconds=uptime.uptime())).split(":") return "System Uptime: %sh, %sm, %ss" % (de[0], de[1], str(round(float(de[2]), 2))) else: return "System Uptime: %s Seconds." % uptime.uptime()
def Uptime(): raw=int(uptime.uptime()) Tmin=raw//60 sec=raw%60 hrs=Tmin//60 min=Tmin%60 return(f"{hrs} hours :{min} minutes :{sec} seconds")
def main_loop(bpf, Flows, web3, Smart_Contract, oracle): flow_data = bpf.get_table("Flow") info_data = bpf.get_table("Info") print("Collecting Data") export_time_limit = 300 #seconds last_export_tstamp = uptime.uptime() while 1: new_flows = oracle.get_new_entries() if (len(new_flows) > 0): print("Merging New Flows") Flows.update(new_flows) try: print("\nFlows:\n") for k in flow_data.keys(): map = flow_data[k] id = map.id if id in Flows: Flows[id].update_stats_from_collector(map) #a = Flows[id].verify_export(web3, Smart_Contract) Flows[id].show() time.sleep(1) except KeyboardInterrupt: print("Removing filter from device") break export_all(Flows, web3, Smart_Contract) bpf.remove_xdp(interface) oracle.stop_t()
def check(self, instance): up = uptime.uptime() if up: self.gauge("system.uptime", up) return # On AIX and some other platforms the uptime module may fail to find the system # uptime and return `None` - in that case, grab the uptime as the init process # (pid 1) uptime try: # get uptime from init process lifetime (pid 1) # format: 8-00:56:09 up, _, _ = get_subprocess_output(['ps', '-o', 'etime=', '-p1'], self.log) up = up.split('-') if len(up) == 1: days, rest = 0, up[0] else: days, rest = up[0], up[1] time = rest.split(':') days_s = int(days) * 24 * 60 * 60 hour_s = int(time[0]) * 60 * 60 mins_s = int(time[1]) * 60 secs = int(time[2]) self.gauge("system.uptime", days_s + hour_s + mins_s + secs) except Exception: self.log.exception("Cannot collect uptime statistics")
def summary_info(): disk_parts = [] nic_parts = [] virt = psutil.virtual_memory() swap = psutil.swap_memory() disks = psutil.disk_partitions() nics = psutil.net_io_counters(pernic=True) freq = psutil.cpu_freq() for disk in disks: disk_parts.append(disk.mountpoint) for nic in nics: nic_parts.append(nic) print('Uptime: %s (Booted: %s)' % (seconds_to_days(uptime()), boottime().strftime('%c'))) if freq is not None: print('CPUs: %d (Frequency - Current (%s), Min (%s), Max (%s))' % (psutil.cpu_count(), freq.current, freq.min, freq.max)) else: print('CPUs: %s' % psutil.cpu_count()) print('Memory: Total %s, Available %s, Free %.2f %%' % (human_size(virt.total), human_size(virt.available), (100 - virt.percent))) print('Swap: Total %s, Available %s, Free %.2f %%' % (human_size(swap.total), human_size(swap.free), (100 - swap.percent))) print('Disks: %s (%s)' % (len(disks), ', '.join(disk_parts))) print('NICs: %s (%s)' % (len(nics), ', '.join(nic_parts))) print('Processes: %s' % len(psutil.pids()))
def receiveRigidBodyFrame( self, id, position, rotation ): if self.body == id: # Quartarion parsing q0 = float(rotation[0].real) q1 = float(rotation[1].real) q2 = float(rotation[2].real) q3 = float(rotation[3].real) # Convert to Eulers. - This origionally converted all 3 eulers # but was removed in speed up processing. t3 = 2.0*(q3*q2+q1*q0) t4 = 1.0 - 2.0*(q1*q1+q2*q2) psi = math.atan2(t3,t4) self.eulerAngles.append([0, psi, 0]) y = position[0] x = position[1] z = position[2] self.position.append([x, y, z]) self.inRecieve = False # Log data self.log.write("Optitrack, "+ str(uptime()) +" %4d, %4d, %4d\n"%tuple( self.position[-1]))
def updateeink(issdetails, mapdot, trail): """update location text and map to the e-ink screen""" issx = int(mapdot[0]) issy = int(mapdot[1]) inky_display = InkyPHAT("yellow") palette = [255, 255, 255, 0, 0, 0, 255, 0, 0] font10 = ImageFont.truetype('/home/pi/isstracker/FreeSans.ttf', 10) font14 = ImageFont.truetype('/home/pi/isstracker/FreeSans.ttf', 14) font16 = ImageFont.truetype('/home/pi/isstracker/FreeSans.ttf', 16) font18 = ImageFont.truetype('/home/pi/isstracker/FreeSans.ttf', 18) im = Image.open('/home/pi/isstracker/small-world-map.png') d = ImageDraw.ImageDraw(im) taille_pt = 3 isspos = (int(mapdot[0]) - taille_pt, int(mapdot[1]) - taille_pt, int(mapdot[0]) + taille_pt, int(mapdot[1]) + taille_pt) d.ellipse(isspos, fill=2) for item in point2ellipse(trail, 1): d.ellipse(item, fill=2) d.text((3, 80), 'à ' + str(round(issdetails[2])) + ' Km de ' + issdetails[1] + ' (' + issdetails[0] + ')', font=font18, fill=2) from uptime import uptime uptime = round(uptime() / 60, 1) d.text((0, 70), "ut : " + str(uptime) + " min", font=font10, fill=1) inky_display.set_image(im) inky_display.show()
async def host(self, ctx): """ Return host server information """ server_uptime_seconds = uptime.uptime() server_uptime = timedelta(seconds=math.floor(server_uptime_seconds)) processor = psutil.cpu_times_percent(interval=1) processor_system_load = processor.system processor_user_load = processor.user memory = psutil.virtual_memory() memory_load = memory.percent embed = discord.Embed() embed.add_field(name='Platform', value=platform.platform().lower(), inline=False) embed.add_field(name='Hostname', value=socket.gethostname().lower(), inline=False) embed.add_field(name='Host Uptime', value=str( server_uptime), inline=False) embed.add_field(name='CPU System Load', value=str( processor_system_load) + '%', inline=False) embed.add_field(name='CPU User Load', value=str( processor_user_load) + '%', inline=False) embed.add_field(name='Memory Load', value=str( memory_load) + '%', inline=False) embed.colour = 0x738bd7 await ctx.send(embed=embed)
def up_time(): total_seconds = uptime() # Helper vars: MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 # Get the days, hours, etc: days = int(total_seconds / DAY) hours = int((total_seconds % DAY) / HOUR) minutes = int((total_seconds % HOUR) / MINUTE) seconds = int(total_seconds % MINUTE) # Build up the pretty string (like this: "N days, N hours, N minutes, N seconds") string = "" if days > 0: string += str(days) + " " + (days == 1 and "day" or "days") + ", " if len(string) > 0 or hours > 0: string += str(hours) + " " + (hours == 1 and "hour" or "hours") + ", " if len(string) > 0 or minutes > 0: string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes") + ", " string += str(seconds) + " " + (seconds == 1 and "second" or "seconds") return string
async def sysuptime(command): '''Echo how long since the last OS reboot''' sysuptime_seconds = int(UptimeModule.uptime()) sysuptime_delta = datetime.timedelta(seconds = sysuptime_seconds) sysuptime_string = 'OS has been running for {0} Days, {1} Hours, {2} Minutes, and {3} Seconds'.format(str(sysuptime_delta.days), str(sysuptime_delta.seconds//3600), str((sysuptime_delta.seconds//60)%60), str(sysuptime_delta.seconds%60)) print(sysuptime_string) return sysuptime_string
def health(): # dictionary with different stats can be updated data = {"uptime": uptime()} response = app.response_class(response=json.dumps(data), status=200, mimetype='application/json') return response
def get_uptime() -> float: """Returns the system uptime in seconds. Returns: Uptime in seconds. """ return uptime.uptime()
def get_up_stats(self): try: m, s = divmod(uptime(), 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s) except Exception as e: logger.error('Server error : ' + str(e))
def os_status(): # Unlike most stats, we don't need up-to-the-second reports on these. # We're going to sample the data approximately once every eighty cycles. if random.random() > 0.0125: return with statsd.pipeline() as pipe: # Restart required? if os.path.isfile('/var/run/reboot-required'): pipe.gauge('os.restart_required', 1) else: pipe.gauge('os.restart_required', 0) # Updates availale? apt_update_check = '/usr/lib/update-notifier/apt-check' if os.path.isfile(apt_update_check): process = subprocess.Popen(apt_update_check, stderr=subprocess.PIPE) _, response = process.communicate() regular, security = response.split(';') pipe.gauge('os.updates.regular', regular) pipe.gauge('os.updates.security', security) # Uptime pipe.gauge('os.uptime', uptime.uptime()) # Host clock offset try: response = ntplib.NTPClient().request('pool.ntp.org') except ntplib.NTPException: pass else: pipe.gauge('os.ntp.offset', response.offset)
def sysinfo(bot: Bot, update: Update): update.message.chat.send_action(ChatAction.TYPING) uname = platform.uname() a = "=" * 10, " 💻 System Info ", "=" * 9 sys_header = "".join(a) sys_info = "{}\n\nSystem: {}\nNode Name: {}\nVersion: {}\n".format( sys_header, uname.system, uname.node, uname.version) b = "=" * 14, " Uptime ", "=" * 13 upt_header = "".join(b) f = int(uptime()) pcuptime = seconds_to_str(f) up = "{}\n\nUptime: {}\n".format(upt_header, pcuptime) c = "=" * 15, " CPU ", "=" * 15 cpu_header = "".join(c) cpufreq = psutil.cpu_freq() cpu_info = "{}\n\n{}\nPhysical cores: {}\nTotal cores: {}\nMax Frequency: {:.2f} Mhz\nCurrent Frequency: {:.2f} Mhz\nCPU Usage: {}%\n".format( cpu_header, cpumodel, psutil.cpu_count(logical=False), psutil.cpu_count(logical=True), cpufreq.max, cpufreq.current, psutil.cpu_percent(percpu=False, interval=1)) d = "=" * 15, " RAM ", "=" * 15 ram_header = "".join(d) svmem = psutil.virtual_memory() ram_info = "{}\n\nTotal: {}\nAvailable: {} ({:.2f}%)\nUsed: {} ({:.2f}%)\n".format( ram_header, get_size(svmem.total), get_size(svmem.available), 100 - svmem.percent, get_size(svmem.used), svmem.percent) server_status = "```\n{}\n{}\n{}\n{}\n```".format(sys_info, up, cpu_info, ram_info) update.message.reply_text(server_status, parse_mode="Markdown")
def system_info(): viewer_log_file = "/tmp/screenly_viewer.log" if path.exists(viewer_log_file): viewlog = check_output(["tail", "-n", "20", viewer_log_file]).split("\n") else: viewlog = ["(no viewer log present -- is only the screenly server running?)\n"] # Get load average from last 15 minutes and round to two digits. loadavg = round(getloadavg()[2], 2) try: run_tvservice = check_output(["tvservice", "-s"]) display_info = re_split("\||,", run_tvservice.strip("state:")) except: display_info = False # Calculate disk space slash = statvfs("/") free_space = size(slash.f_bavail * slash.f_frsize) # Get uptime uptime_in_seconds = uptime() system_uptime = timedelta(seconds=uptime_in_seconds) return template( "system_info", viewlog=viewlog, loadavg=loadavg, free_space=free_space, uptime=system_uptime, display_info=display_info, )
def returnHealth(): health_status = { "Status": "OK", "uptime": jsonable_encoder(uptime()), "boottime": jsonable_encoder(boottime()) } return JSONResponse(status_code=200, content=health_status)
def system(_, update): """ Plugin for retrieving information about the server/computer running the bot. """ # Retrieve the uptime of the host system. uptimetostr = int(uptime()) pc_uptime = seconds_to_str(uptimetostr) uptime_retrieval = "*Uptime*: ", pc_uptime uptime_text = "".join(uptime_retrieval) # Retrieves the OS name and the version. os = platform.system() pyver = platform.python_version() version = platform.version() # CPU information. Uses some psutil facilities for the # CPU count of logical and non-logical CPU cores. cpu_count = psutil.cpu_count(logical=False) cpus_log = psutil.cpu_count(logical=True) cpu_string = str(psutil.cpu_percent(interval=0.5, percpu=True)).replace("[", " ").replace("]", " ") # Return the number of CPU cores along with the # current load on the CPU(s). cpu_core_count = "*CPU cores*: ", str(cpu_count), " physical, ", str(cpus_log), " logical" cpu_cores = "".join(cpu_core_count) cpu_load_text = "*CPU load*: ", str(cpu_string) cpu_text = "".join(cpu_load_text) update.message.chat.send_action(action=ChatAction.TYPING) update.message.reply_text(parse_mode=ParseMode.MARKDOWN, text="*System Info*:\n\n" + "*OS*: " + os + " " + version + "\n" + "*Python Version*: " + pyver + "\n" + cpu_cores + "\n" + cpu_text + "\n" + uptime_text)
def send_msg(domains_being_blocked, dns_queries_today, ads_percentage_today, ads_blocked_today): json_body = [ { "measurement": "pihole." + HOSTNAME.replace(".", "_"), "tags": { "host": HOSTNAME }, "fields": { "domains_being_blocked": int(domains_being_blocked), "dns_queries_today": int(dns_queries_today), "ads_percentage_today": float(ads_percentage_today), "ads_blocked_today": int(ads_blocked_today), "uptime": int(uptime.uptime()), "temp": float(CPUTemperature().temperature), "load_average": float(LoadAverage().load_average), "disk_usage": float(DiskUsage().usage) } } ] # InfluxDB host, InfluxDB port, Username, Password, database client = InfluxDBClient(INFLUXDB_SERVER, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, INFLUXDB_DATABASE) # Uncomment to create the database (expected to exist prior to feeding it data) # client.create_database(INFLUXDB_DATABASE) client.write_points(json_body) print(json_body)
def mqtt_send_stats(self): self.logger.info("Sending stats") stats_topic = "{0}/$stats/".format(self.topic) self.mqtt_client.publish(stats_topic + "interval", self.stats_interval) self.mqtt_client.publish(stats_topic + "uptime", uptime()) signal = "Not implemented yet" self.mqtt_client.publish(stats_topic + "signal", 0) # cputemp = int(subprocess.check_output(['cat', '/sys/class/thermal/thermal_zone0/temp'])) / 1000 cputemp = 50 self.mqtt_client.publish(stats_topic + "cputemp", cputemp) # cpuload = subprocess.check_output(['cat', '/proc/loadavg']).rstrip() cpuload = 75 self.mqtt_client.publish(stats_topic + "cpuload", cpuload) # freeheap = subprocess.check_output(['cat', '/proc/meminfo']).decode('utf-8').split('\n')[1].replace(' ', '').split(':')[1][:-2] freeheap = 1000 self.mqtt_client.publish(stats_topic + "freeheap", freeheap) supply = "Not implemented yet" self.mqtt_client.publish(stats_topic + "supply", 0) Timer(self.stats_interval - 1, self.mqtt_send_stats).start()
def uptime_string(startup_time_in_seconds, last_error_time): # Machine info uname = platform.uname() uptime_seconds = uptime.uptime() # Delta uptime in human readable format uptime_string = str(timedelta(seconds=uptime_seconds)) # Time now now = time.time() delta = now - startup_time_in_seconds bot_uptime = str(timedelta(seconds=int(delta))) # Get memory usage with ps memory = memory_usage_ps() # Make messsge string = "" string += "\U0001F4BB Running on " + uname[0] + " " + uname[ 2] + " " + uname[4] + "\n" string += "\U0000231B Uptime: " + uptime_string + "\n" string += "\U0001F916 Bot uptime: " + bot_uptime + "\n" string += "\U0001F4CA Bot memory usage: " + memory + "MB" if last_error_time is not None: delta = now - last_error_time last_error = str(timedelta(seconds=int(delta))) string += "\n\U0001F480 " + last_error + " without casualties" return string
def run_scheduler(s): time.sleep(0.01) local_id = tasks.sched_thread_id afk = True if s.task_list_idle: afk = False s.idle_min = min([t['idle_dur'] for t in s.task_list_idle]) while (tasks.sched_thread_id == local_id): schedule.run_pending() if s.task_list_idle: ms = int(uptime.uptime() * 1000) - win32api.GetLastInputInfo() if ms < s.idle_min: if afk: dev_print('user is back') afk = False for task in s.task_list_idle: task['idle_done'] = False else: afk = True for task in s.task_list_idle: if task['idle_done']: continue if ms >= task['idle_dur']: s.run_task(task, caller=CALLER_IDLE) task['idle_done'] = True time.sleep(1)
def turnCharacter(self, desiredTarget=None, location=None): if desiredTarget != None: loc = desiredTarget.loc() if location != None: loc = location f = np.arctan2(loc.y - self.Y(), loc.x - self.X()) #normalise if f < 0.0: f = f + 2 * np.pi if f > 2 * np.pi: f = f - 2 * np.pi toFace = f # print("playerPointer = {}".format(hex(self._address))) # print("ff = {}".format(convertFloatToHex(f))) # print("function = {}".format(hex(constants.Functions.SetFacing.value))) caveContents = ''' mov ecx, {playerPointer}\n add ecx, 0x9A8\n push {ff}\n mov eax, 0x{setFacing:000000008x}\n call eax\n '''.format( playerPointer=hex(self._address), ff=convertFloatToHex(toFace), setFacing=constants.Functions.SetFacing.value) #print("cave contents\n {}".format(caveContents)) self.inj.InjectAndExecute(self._hprocess, caveContents) self.SendMovementUpdate(0xDA, uptime.uptime() * 1000)
def heartbeat(): print("Heartbeat Started") while True: try: m = {} ts = str(timestamp()) ts = ts.translate({ord(' '): 'T'}) ts = ts + "Z" up = round(uptime()) cpu = psutil.cpu_percent() vMem = psutil.virtual_memory() m = { 'ts': ts, 'edgeMAC': DEVmac, 'uptime': up, 'cpu': cpu, 'totalMemory': vMem[0], 'availableMemory': vMem[1], 'percentUsedMemory': vMem[2], 'usedMemory': vMem[3], 'freeMemory': vMem[4] } msgJson = json.dumps(m) clientH.publish(CONFIG.get('topic1') + "/linux/" + DEVmac + "/heartbeat", msgJson, qos=0, retain=False) time.sleep(30) except: pass
def send_heartbeat(username, password, apiUrl, rejectUnauthorized, urn, forceConfig): url = '{}/mediators/{}/heartbeat'.format(apiUrl, urn) headers = generate_auth_headers(username, password) json = { 'uptime': uptime(), } if (forceConfig): json['config'] = True logging.info(url) with warnings.catch_warnings(): warnings.simplefilter("ignore") response = requests.post(url, headers=headers, json=json, verify=rejectUnauthorized) if (response.status_code != 200): raise Exception( 'Heartbeat unsuccessful, received status code of {}'.format( response.status_code)) # logging.info('Heartbeat unsuccessful, received status code of {}'.format(response.status_code)) return {} if (response.reason != 'OK'): return response.json() else: return {}
def cpu(): """ Gather CPU metrics :return: dictionary with CPU statistics """ keep_cpu_stats = ['user', 'idle', 'system', 'nice', 'iowait', 'irq', 'softirq'] # Ignoring: steal, guest, guest_nice def _cpu_stats(stats): return {stat: value for stat, value in stats._asdict().items() if stat in keep_cpu_stats} info = { "stats_type": "cpu", "num_cpus": psutil.cpu_count(), "loadavg": dict(zip(("1min", "5min", "15min"), os.getloadavg())), "cpu": { "all": _cpu_stats(psutil.cpu_times(percpu=False)), }, "uptime": uptime.uptime(), } per_cpu_stats = psutil.cpu_times(percpu=True) for cpu_no in range(0, len(per_cpu_stats)): info['cpu'][str(cpu_no)] = _cpu_stats(per_cpu_stats[cpu_no]) info['cpu']['all'].update(psutil.cpu_stats()._asdict()) return info
def GetWinNTUptime(self): from uptime import uptime seconds = int(uptime()) days = seconds/60/60/24 seconds -= days*60*60*24 hours = seconds/60/60 seconds -= hours*60*60 minutes = seconds/60 seconds -= minutes*60 up = { "Days": days, "Hours": hours, "Minutes": minutes } up_str = u"" _DAYS = u" days" _DAY = u" day" _HOURS = u" hours" _HOUR = u" hour" _MINUTES = u" minutes" _MINUTE = u" minute" if up["Days"] > 1: up_str += ", " + unicode(up["Days"]) + _DAYS elif up["Days"] > 0: up_str += ", " + unicode(up["Days"]) + _DAY if up["Hours"] > 1: up_str += ", " + unicode(up["Hours"]) + _HOURS elif up["Hours"] > 0: up_str += ", " + unicode(up["Hours"]) + _HOUR if up["Minutes"] > 1: up_str += ", " + unicode(up["Minutes"]) + _MINUTES elif up["Minutes"] > 0: up_str += ", " + unicode(up["Minutes"]) + _MINUTE return up_str.lstrip(", ")
def uptime_data(): """Returns uptime data. """ return { 'uptime': mark(uptime.uptime(), 'duration'), 'boottime': uptime.boottime() }
def system_info(): viewer_log_file = '/tmp/sync_viewer.log' if path.exists(viewer_log_file): viewlog = check_output(['tail', '-n', '20', viewer_log_file]).split('\n') else: viewlog = ["(no viewer log present -- is only the sync server running?)\n"] # Get load average from last 15 minutes and round to two digits. loadavg = round(getloadavg()[2], 2) try: run_tvservice = check_output(['tvservice', '-s']) display_info = re_split('\||,', run_tvservice.strip('state:')) except: display_info = False # Calculate disk space slash = statvfs("/") free_space = size(slash.f_bavail * slash.f_frsize) # Get uptime uptime_in_seconds = uptime() system_uptime = timedelta(seconds=uptime_in_seconds) return template('system_info', viewlog=viewlog, loadavg=loadavg, free_space=free_space, uptime=system_uptime, display_info=display_info)
def wait_for_uptime(min_uptime_time): time_on = uptime() if time_on < min_uptime_time: print("The system has been on only for " + str(time_on) + "s, waiting for the system to be on for at least " + str(min_uptime_time)) time.sleep(min_uptime_time - time_on)
def system_info(): viewer_log_file = '/tmp/screenly_viewer.log' if path.exists(viewer_log_file): viewlog = check_output(['tail', '-n', '20', viewer_log_file]).split('\n') else: viewlog = [ "(no viewer log present -- is only the screenly server running?)\n" ] # Get load average from last 15 minutes and round to two digits. loadavg = round(getloadavg()[2], 2) try: run_tvservice = check_output(['tvservice', '-s']) display_info = re_split('\||,', run_tvservice.strip('state:')) except: display_info = False # Calculate disk space slash = statvfs("/") free_space = size(slash.f_bavail * slash.f_frsize) # Get uptime uptime_in_seconds = uptime() system_uptime = timedelta(seconds=uptime_in_seconds) return template('system_info', viewlog=viewlog, loadavg=loadavg, free_space=free_space, uptime=system_uptime, display_info=display_info)
def get_uptime(self): from uptime import uptime up = uptime() if up is not None: parts = [] days, up = up // 86400, up % 86400 if days is 0: parts.append('%d day' % 0) else: parts.append('%d day%s' % (days, 's' if days != 0 and days != 1 else '')) hours, up = up // 3600, up % 3600 if hours is 0: parts.append(' %02d:' % 0) else: parts.append(' %02d:' % hours) minutes, up = up // 60, up % 60 if minutes is 0: parts.append('%02d' % 0) else: parts.append('%02d' % minutes) uptime = '%s' % ''.join(parts) return uptime
def uptime_string(startup_time_in_seconds, last_error_time): # Machine info uname = platform.uname() uptime_seconds = uptime.uptime() # Delta uptime in human readable format uptime_string = str(timedelta(seconds=uptime_seconds)) # Time now now = time.time() delta = now - startup_time_in_seconds bot_uptime = str(timedelta(seconds=int(delta))) # Get memory usage with ps memory = memory_usage_ps() # Make messsge string = "" string += "\U0001F4BB Running on " + uname[0] + " " + uname[2] + " " + uname[4] + "\n" string += "\U0000231B Machine Uptime: " + uptime_string + "\n" string += "\U0001F916 Bot uptime: " + bot_uptime + "\n" string += "\U0001F4CA Bot memory usage: " + memory + "MB" if last_error_time is not None: delta = now - last_error_time last_error = str(timedelta(seconds=int(delta))) string += "\n\U0001F480 " + last_error + " without casualties" return string
def construct_sysinfo() -> str: """ Get system information and construct message from it. Returns: str: Constructed and formatted message, ready for Telegram. """ __uname = platform.uname() __sysname = f"{__uname.system} {__uname.release} ({__uname.version})" __userhost = f"{os.path.basename(os.path.expanduser('~'))}@{__uname.node}" __uptime_raw = uptime() __uptime_dict = { "days": str(floor(__uptime_raw / (24 * 3600))), "hours": str(floor(__uptime_raw / 3600)), "mins": str(floor(__uptime_raw / 60 % 60)), "secs": str(floor(__uptime_raw % 60)) } __uptime_dict.update({ k: f"0{__uptime_dict[k]}" for k in __uptime_dict if len(__uptime_dict[k]) == 1 }) __uptime = f"{__uptime_dict['days']}:{__uptime_dict['hours']}:{__uptime_dict['mins']}:{__uptime_dict['secs']}" string_final = f"{bold('System')}: {code(__sysname)}\n{bold('Uptime')} {italic('dd:hh:mm:ss')}: {code(__uptime)}\n{bold('User@Host')}: {code(__userhost)}" return string_final
def get_up_stats(self): try: from uptime import uptime m, s = divmod(uptime(), 60) h, m = divmod(m, 60) return "%d:%02d:%02d" % (h, m, s) except Exception as e: logger.error('Server error : ' + str(e))
def _boot_time_windows(): try: from time import time import uptime return int(time() - uptime.uptime()) except: return
def __init__(self): """Create a new record, gathering information relevant to the machine on which this code is running. """ self.time = datetime.datetime.utcnow() self.hostname = socket.gethostname() self.load_average = os.getloadavg()[1] self.uptime = uptime.uptime() / 86400.
def get_platform_info(): stats = OrderedDict([ ('Hostname', platform.node()), ('Distribution', " ".join(platform.dist())), ('Kernel', platform.uname()[2]), ('Uptime', str(timedelta(seconds=uptime()))), ('Load avg', ", ".join([str(k) for k in os.getloadavg()])) ]) return stats
def get_uptime(self, socket = False): data = {'uptime' : uptime.uptime(), 'timestamp' : int(time.time()), 'day' : self.weather.is_day(), 'load' : os.getloadavg()} if socket: self.__send_message({'type':'uptime','data':data}) else: return data
def jsondata(): uptime_var = int(uptime()) temp = read_temp() tempString = str(temp) if temp >= 60.0: saying = "Oh Shit, That Beer Is Hot!" else: saying = "Yeah That Beer Is Cold!" timeString = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") cpu_percent = psutil.cpu_percent() virtmem_percent = psutil.virtual_memory()[2] return jsonify(uptime=uptime_var, temp=tempString, time=timeString, cpu=cpu_percent, ram=virtmem_percent, saying=saying)
def host_stats(): return { 'uptime': int(uptime()), 'linux': ''.join(platform.linux_distribution()), 'kernel': platform.uname()[2], 'cpu': { 'cpu_count': cpu_count(), 'model_name': cpu_model_name() }, 'memory': memory_stats(), 'network': network_stats(), 'disk': disk_stats(), 'docker': docker_stats() }
def parse_output(self, data, ethmac): self.spec["ethernet_MAC"] = ethmac self.spec["current_MAC"] = cp.utils.get_MAC() self.spec["source_address"]= cp.utils.get_SA() # shakey self.spec["local_address"] = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] fields = data.split() #self.spec["uptime"] = fields[2][:-1] #self.spec["uptime"] = re.search("up .*?,",data).group(0)[3:-1] self.spec["uptime"] = float(uptime.uptime() / (60*60)) self.spec["load1"] = float(fields[-3][:-1]) self.spec["load5"] = float(fields[-2][:-1]) self.spec["load15"] = float(fields[-1]) return self.spec
def system_uptime(): """ Return uptime of the system linux only :rtype: datetime.timedelta """ try: import uptime uptime_seconds = uptime.uptime() except ImportError: if sys.platform.startswith('linux') and os.path.exists('/proc/uptime'): with open('/proc/uptime', 'r') as f: uptime_seconds = float(f.readline().split()[0]) else: raise ValueError('Using uptime in non-linux environments needs uptime module to be installed') return datetime.timedelta(seconds=uptime_seconds)
def take_sample(self): # memory mem = psutil.virtual_memory() mem_used = mem.total - mem.available mem_used_ratio = float(mem_used)/float(mem.total) if mem_used_ratio > 0.9 or mem.available <= 0.5E9: severity = 'high' elif mem_used_ratio > 0.8 or mem.available <= 1E9: severity = 'medium' else: severity = 'low' self.metrics['Memory'] = {'value': '{:.1%}'.format(mem_used_ratio), 'severity':severity, 'used': str(mem.used), 'total': str(mem.total)} self.metrics['User'] = {'value': win32api.GetUserName()} self.metrics['Up time'] = {'value': str(datetime.timedelta(seconds=uptime.uptime()))} self.metrics['CPU count'] = {'value': str(multiprocessing.cpu_count())} self.metrics['Last seen'] = {'value': str(time.time())} # client display calculates time delta from this
def status(): boards, totalsize = {}, 0 for board in config['boards']: # Index size on disk size = 0 for f in glob.glob(os.path.join(config['index'], '%s_*' % board)): st = os.stat(f) size += st.st_size # Other information try: ix = whoosh.index.open_dir(config['index'], board, readonly=True) num = ix.doc_count() updated = ix.last_modified() ix.close() except whoosh.index.EmptyIndexError: num = 0 updated = None totalsize += size boards[board] = {'size': size, 'num': num, 'updated': updated} # Misc. information try: statvfs = os.statvfs(config['index']) freesize = statvfs.f_bavail * statvfs.f_bsize except AttributeError: freesize = None uname = platform.uname() os_details = { 'Linux': ('%s %s' % platform.linux_distribution()[:2]).capitalize(), 'FreeBSD': uname[2], 'Darwin': platform.mac_ver()[0], 'Windows': '%s %s' % platform.win32_ver()[0::2], }.get(platform.system(), 'Unknown version') return templates.get_template('status.mako').render( uname=uname, os_details=os_details, uptime=uptime.uptime(), totalsize=totalsize, freesize=freesize, boards=boards )
def up(): t = uptime.uptime() days = 0 hours = 0 min = 0 out = "" while t > 86400: t -= 86400 days += 1 while t > 3600: t -= 3600 hours += 1 while t > 60: t -= 60 min += 1 if days > 0: out += str(days) + "d " out += str(hours) + "h " out += str(min) + "m" return out
def get_systeminfo(self): gb = pow(1024.0,3) self.states = collections.OrderedDict() self.states['computername'] = platform.node() self.states['user'] = win32api.GetUserName() self.disks = psutil.disk_partitions(all=True) for disk in self.disks: disk_path = disk[0] try: total, used, free, percent = psutil.disk_usage(disk_path) volume_name, serial_number, max_len, flags, fs_name = win32api.GetVolumeInformation(disk_path) total = total/gb # convert to gb used = used/gb self.states[disk_path] = str(percent) + '% (' + str(used) + ' / ' + str(total) + ' gb) (' + volume_name + ')' except: print("warning: can not access", disk_path) self.states['usertime'] = str(os.times()[0]) self.states['systemtime'] = str(os.times()[1]) self.states['uptime'] = str(datetime.timedelta(seconds = uptime.uptime())) self.states['timestamp'] = time.strftime('%c') return self.states
def site_visits(site, hours_back): """ Number of visits in the last x hours. """ now_epoch = (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).total_seconds() if hours_back == 0: up = uptime.uptime() # OR TODAY IF IT'S LESS!!! datetime.timedelta uptime_epoch = int(now_epoch - up) else: uptime_epoch = int(now_epoch - hours_back*3600) sid = site_id(site) query_string = "select visit_date as raw_visit_date,datetime(visit_date/1000000,'unixepoch', 'localtime') from moz_historyvisits where place_id == %d" % sid c = db.execute(query_string) results = [i for i in c if int(i[0]/1000000) >= uptime_epoch] return len(results)
def readableUptime(): total_seconds = uptime.uptime() # Vars MINUTE = 60 HOUR = MINUTE * 60 DAY = HOUR * 24 # Get the days, hours, etc: days = int( total_seconds / DAY ) hours = int( ( total_seconds % DAY ) / HOUR ) minutes = int( ( total_seconds % HOUR ) / MINUTE ) seconds = int( total_seconds % MINUTE ) # Create String "N days, N hours, N minutes, N seconds" string = "" if days> 0: string += str(days) + " " + (days == 1 and "day" or "days" ) + ", " if len(string)> 0 or hours> 0: string += str(hours) + " " + (hours == 1 and "hour" or "hours" ) + ", " if len(string)> 0 or minutes> 0: string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes" ) + ", " string += str(seconds) + " " + (seconds == 1 and "second" or "seconds" ) return string;
def run(self, message, args): uptime_seconds = int(uptime()) uptime_string = str(timedelta(seconds=uptime_seconds)) self.reply(message, uptime_string)
def check(self, agentConfig): return {"system.uptime": uptime.uptime()}
def get_uptime(): time = uptime() hours = int(time / 3600) minutes = int((time - hours * 3600) / 60) seconds = int(time - hours * 3600 - minutes * 60) return str(hours) + ':' + str(minutes) + ':' + str(seconds)
def check(self, agentConfig): self.save_sample('system.uptime', uptime.uptime()) return self.get_metrics()
def get_uptime(): return uptime()
def getHostInfo(): ''' Use hal-get-property ? STATIC_INFO DYNAMIC_INFO Hostname Uptime_in_Seconds OS_Version Kernel_Version KVM_Version Libvirt_Version Spice_Version RUNNING_VMS CPU_Family CPU_Type CPU_Sockets CPU_Cores_per_Socket CPU_Threads_per_Core All_CPU_Usage Virtualization Physical_Memory_Size Physical_Memory_Usage Swap_Size Swap_Usage IP_Address MAC_Address Network_Interfaces Network_Interface_Bandwidth Network_Interface_Updown Network_Usage ''' info = {} info["hostname"] = platform.node() info["uptime_in_seconds"] = str(uptime.uptime()) info["os_version"] = platform.platform() #OS_Version = platform.linux_distribution() info["kernel_version"] = platform.release() info["kvm_version"] = subprocess.Popen("rpm -qa|grep qemu-kvm|awk -F 'qemu-kvm-' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["libvirt_version"] = subprocess.Popen("rpm -qa|grep libvirt-client|awk -F 'libvirt-client-' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["spice_version"] = subprocess.Popen("rpm -qa|grep spice-server|awk -F 'spice-server-' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() # TBD info["running_vms"] = subprocess.Popen("ps aux|grep qemu|wc -l", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["cpu_family"] = platform.processor() info["cpu_type"]= subprocess.Popen("cat /proc/cpuinfo | grep 'model name' | head -n 1 | awk -F ':' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["cpu_sockets"] = subprocess.Popen("lscpu | grep 'Socket(s)' | awk -F ':' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["cpu_cores_per_socket"] = subprocess.Popen("lscpu | grep 'per socket' | awk -F ':' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["cpu_threads_per_core"] = subprocess.Popen("lscpu | grep 'per core' | awk -F ':' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["virtualization"] = subprocess.Popen("lscpu | grep 'Virtualization:' | awk -F ':' '{print $2}'", stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() info["all_cpu_usage"] = str(psutil.cpu_percent()) info["physical_memory_size_in_mb"] = str(psutil.virtual_memory()[0]/1024/1024) info["physical_memory_used_in_mb"] = str(int(psutil.virtual_memory()[0]*psutil.virtual_memory()[2]/1024/1024/100)) info["swap_size_in_mb"] = str(psutil.swap_memory()[0]/1024/1024) info["swap_used_in_mb"] = str(psutil.swap_memory()[1]/1024/1024) info["networkinfo"] = {} network = {} i = 0 for iface in netifaces.interfaces(): ifaddress = netifaces.ifaddresses(iface) #if iface != "lo0": continue #print iface network["name"] = iface try: network["ip_address"] = ifaddress[2][0]["addr"] except: network["ip_address"] = "null" try: network["broadcast"] = ifaddress[2][0]["broadcast"] except: network["broadcast"] = "null" try: network["netmask"] = ifaddress[2][0]["netmask"] except: network["netmask"] = "null" try: #TBD cmd = "ifconfig | grep %s | head -n 1 | awk -F 'HWaddr' '{print $2}'" % iface network["mac_address"] = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() except: network["mac_address"] = "null" try: cmd = "ethtool %s 2>/dev/null | grep 'Speed' | awk -F ':' '{print $2}'" % iface network["speed"] = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True).stdout.read().strip() % iface except: network["speed"] = "null" info["networkinfo"][i] = network i = i+1 #Network_Interface_Bandwidth #Network_Interface_Updown #Network_Usage #info["network"] = networkinfo return info
def get_value(number): print "get_value, of of item with number=",number BS = sys.platform if number == 1: return BS if number == 2: return sys.getdefaultencoding() if number == 3: if BS == "win32": #This is a work around to make sure everything is in the same syntax. upTimeList = getPowerShell('Get-Uptime').rstrip().split(',') return float(upTimeList[0]+'.'+upTimeList[1]) else: return uptime() if number == 4: if BS == "win32": return getPowerShell('Get-CountPS') else: #get the amount of pid's pidList = [] for pid in os.listdir('/proc'): if pid.isdigit(): pidList.append(pid) return len(pidList) if number == 5: if BS == "win32": return getPowerShell('Get-Memory') else: #create a list so we have used;available;total p = psutil.virtual_memory() waardes = str(p.used/(1024**2)) + ';' + str(p.available/(1024**2)) + ';' + str(p.total/(1024**2)) return waardes if number == 6: if BS == "win32": return (getPowerShell('Get-FreeSpace')) else: #create a list so we have used;available;total p = psutil.disk_usage('/') waardes = str(p.used/(1024**2)) + ';' + str(p.free/(1024**2)) + ';' + str(p.total/(1024**2)) return waardes if number == 7: if BS == "win32": return getPowerShell('Get-IPAddress -first') else: return socket.gethostbyname(socket.gethostname()) if number == 8: #create a list so we have used;available;total p = psutil.cpu_times_percent() waardes = str(p.user) + ';' + str(p.system) + ';' + str(p.idle) return waardes if number == 9: username = getpass.getuser() return str(username) # Last value return None
def monitor(self): MONITOR_PATH = os.path.join(self.LOGS_PATH, "monitor/monitor-log.%s.json" % self.LOG_HOUR) data = {} data["uptime"] = uptime.uptime() data["timestamp"] = datetime.datetime.utcnow().isoformat() data["cpu_percent"] = psutil.cpu_percent(0) data["free_memory"] = psutil.virtual_memory().available data["free_disk"] = psutil.disk_usage(self.DATA_PATH).free device = os.path.basename(get_device(self.DATA_PATH)) if device == 'tmpfs': data["iostat"] = None else: iostat = psutil.disk_io_counters(perdisk=True)[device] data["iostat"] = { "read_bytes": iostat.read_bytes, "write_bytes": iostat.write_bytes, "read_count": iostat.read_count, "write_count": iostat.write_count } self.log.debug(data) with open(MONITOR_PATH, 'a') as f: json.dump(data, f, sort_keys=True) f.write('\n')