def handle(text, mic, profile):
os, name, version, _, _, _ = platform.uname()
version = version.split('-')[0]
cores = psutil.cpu_count()
cpu_percent = psutil.cpu_percent()
memory_percent = psutil.virtual_memory()[2]
disk_percent = psutil.disk_usage('/')[3]
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
running_since = boot_time.strftime("%A %d. %B %Y")
response = "I am currently running on %s version %s. " %(os, version)
response += "This system is named %s and has %s CPU cores. " %(name, cores)
response += "Current CPU utilization is %s percent. " %cpu_percent
response += "Current memory utilization is %s percent." %memory_percent
mic.say(response)
python类boot_time()的实例源码
def test_boot_time(self):
self.execute(psutil.boot_time)
# XXX - on Windows this produces a false positive
def test_boot_time(self):
vmstat_value = vmstat('boot time')
psutil_value = psutil.boot_time()
self.assertEqual(int(vmstat_value), int(psutil_value))
def test_boot_time_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
RuntimeError,
psutil._pslinux.boot_time)
assert m.called
def create_time(self, ret, proc):
try:
self.assertGreaterEqual(ret, 0)
except AssertionError:
if OPENBSD and proc.status == psutil.STATUS_ZOMBIE:
pass
else:
raise
# this can't be taken for granted on all platforms
# self.assertGreaterEqual(ret, psutil.boot_time())
# make sure returned value can be pretty printed
# with strftime
time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
def test_boot_time(self):
s = sysctl('sysctl kern.boottime')
s = s[s.find(" sec = ") + 7:]
s = s[:s.find(',')]
btime = int(s)
self.assertEqual(btime, psutil.boot_time())
# --- sensors_battery
def test_boot_time(self):
s = sysctl('kern.boottime')
sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y")
psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time())
self.assertEqual(sys_bt, psutil_bt)
# =====================================================================
# --- NetBSD
# =====================================================================
def test_boot_time(self):
self.execute(psutil.boot_time)
# XXX - on Windows this produces a false positive
def test_boot_time(self):
vmstat_value = vmstat('boot time')
psutil_value = psutil.boot_time()
self.assertEqual(int(vmstat_value), int(psutil_value))
def test_boot_time_mocked(self):
with mock.patch('psutil._pslinux.open', create=True) as m:
self.assertRaises(
RuntimeError,
psutil._pslinux.boot_time)
assert m.called
def create_time(self, ret, proc):
try:
self.assertGreaterEqual(ret, 0)
except AssertionError:
if OPENBSD and proc.status == psutil.STATUS_ZOMBIE:
pass
else:
raise
# this can't be taken for granted on all platforms
# self.assertGreaterEqual(ret, psutil.boot_time())
# make sure returned value can be pretty printed
# with strftime
time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
def test_boot_time(self):
s = sysctl('sysctl kern.boottime')
s = s[s.find(" sec = ") + 7:]
s = s[:s.find(',')]
btime = int(s)
self.assertEqual(btime, psutil.boot_time())
# --- sensors_battery
def test_boot_time(self):
s = sysctl('kern.boottime')
sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y")
psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time())
self.assertEqual(sys_bt, psutil_bt)
# =====================================================================
# --- NetBSD
# =====================================================================
def _get_uptime():
return int(time() - psutil.boot_time())
def process(self, context, ticket_location):
"""This method runs once on each ticket.
Note that this method runs inside a threadpool.
"""
components = ticket_location.to_path().split("/")
# Ensure the ticket location matches the ticket content.
if (components[-2] != self.client_id or
components[-3] != self.__class__.__name__):
raise IOError("Ticket location unexpected.")
# Verify the client id and public key match.
if self.public_key.client_id() != self.client_id:
raise crypto.CipherError("Public key incompatible with client_id")
# Update the client's record by deleting the old one and inserting a new
# one.
context["messages"].append(
dict(client_id=self.client_id,
fqdn=self.system_info.fqdn,
system=self.system_info.system,
architecture=self.system_info.architecture,
boot_time=self.boot_time,
agent_start_time=self.agent_start_time,
)
)
# Modify the client record atomically.
self._config.server.client_record_for_server(
self.client_id).read_modify_write(self._update_client_record)
def _get_system_status(self):
system_uptime_value = TimeFormatter.format(self.__get_elapsed_seconds_since(psutil.boot_time()))
system_uptime = FormattedText()\
.normal("Uptime: {system_uptime}").start_format().bold(system_uptime=system_uptime_value).end_format()
cpu_usage_value = str(psutil.cpu_percent(interval=self.cpu_usage_sample_seconds)) + " %"
cpu_usage = FormattedText()\
.normal("CPU usage: {cpu_usage} ({sample_interval} sec. sample)").start_format()\
.bold(cpu_usage=cpu_usage_value).normal(sample_interval=self.cpu_usage_sample_seconds).end_format()
return FormattedText().newline().join((
FormattedText().bold("System status"),
system_uptime,
cpu_usage
))
def starttime(pid):
"""starttime(pid) -> float
Arguments:
pid (int): PID of the process.
Returns:
The time (in seconds) the process started after system boot
"""
return psutil.Process(pid).create_time() - psutil.boot_time()
getSystemStatus.py 文件源码
项目:LinuxBashShellScriptForOps
作者: DingGuodong
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def getUptime():
uptime_file = "/proc/uptime"
if os.path.exists(uptime_file):
with open(uptime_file, 'r') as f:
return f.read().split(' ')[0].strip("\n")
else:
return time.time() - psutil.boot_time()
getSystemStatus.py 文件源码
项目:LinuxBashShellScriptForOps
作者: DingGuodong
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def getUptime2():
boot_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
print "system start at: %s" % boot_time,
uptime_total_seconds = time.time() - psutil.boot_time()
uptime_days = int(uptime_total_seconds / 24 / 60 / 60)
uptime_hours = int(uptime_total_seconds / 60 / 60 % 24)
uptime_minutes = int(uptime_total_seconds / 60 % 60)
uptime_seconds = int(uptime_total_seconds % 60)
print "uptime: %d days %d hours %d minutes %d seconds" % (uptime_days, uptime_hours, uptime_minutes, uptime_seconds)
user_number = len(psutil.users())
print "%d user:" % user_number
print " \\"
for user_tuple in psutil.users():
user_name = user_tuple[0]
user_terminal = user_tuple[1]
user_host = user_tuple[2]
user_login_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(user_tuple[3]))
print " |- user online: %s, login from %s with terminal %s at %s" % (
user_name, user_host, user_terminal, user_login_time)
cpu_count = psutil.cpu_count()
try:
with open('/proc/loadavg', 'r') as f:
loadavg_c = f.read().split(' ')
loadavg = dict()
if loadavg_c is not None:
loadavg['lavg_1'] = loadavg_c[0]
loadavg['lavg_5'] = loadavg_c[1]
loadavg['lavg_15'] = loadavg_c[2]
loadavg['nr'] = loadavg_c[3]
loadavg['last_pid'] = loadavg_c[4]
print "load average: %s, %s, %s" % (loadavg['lavg_1'], loadavg['lavg_5'], loadavg['lavg_15'])
if float(loadavg['lavg_15']) > cpu_count:
print "Note: cpu 15 min load is high!"
if float(loadavg['lavg_5']) > cpu_count:
print "Note: cpu 5 min load is high!"
if float(loadavg['lavg_1']) > cpu_count:
print "Note: cpu 1 min load is high!"
except IOError:
pass
def getDmesg():
# because can NOT get data from /proc, so use 'dmesg' command to get data
dmesg = subprocess.check_output(['dmesg']).split('\n')
for message in dmesg:
try:
print time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(
(float(psutil.boot_time()) + float(message.split('] ')[0][2:].strip())))), message
sys.stdout.flush()
except ValueError:
pass