Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def sys_statz():
conn_init()
io_statz = psutil.disk_io_counters(perdisk=False)
statz_mem = psutil.virtual_memory()
statz_cpu_load = psutil.cpu_percent(interval=0, percpu=False)
cpu_statz = psutil.cpu_stats()
cursor = conn.cursor()
cursor.execute('INSERT INTO statz.system_activity \
(ctx_switches,interrupts,soft_interrupts,syscalls,cpu_load,read_count,write_count, \
read_bytes,write_bytes,total,available,mem_used_percent,used,free,active,inactive ) \
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ; commit',
(cpu_statz.ctx_switches,cpu_statz.interrupts,cpu_statz.soft_interrupts,cpu_statz.syscalls,statz_cpu_load,
io_statz.read_count,io_statz.write_count,io_statz.read_bytes,io_statz.write_bytes,
int(statz_mem.total),int(statz_mem.available),statz_mem.percent,int(statz_mem.used),
int(statz_mem.free),int(statz_mem.active),int(statz_mem.inactive)))
metric = args[1].lower()
if metric not in valid_metrics:
metric = 'iops'
if metric == 'used':
path = '/' if len(args) < 3 else args[2].replace("'", "")
try:
usage = psutil.disk_usage(path)
total = usage.percent
except OSError:
logging.error("disk usage: path \"%s\" not found" % path)
return None
return ("Disk usage for %s|Disk=%.2f%%" % (path, total))
else:
counters = psutil.disk_io_counters()
if metric == 'iops':
total = self._calculate_total2(counters.write_count,
'write_count',
counters.read_count,
'read_count')
elif metric == 'ips':
total = self._calculate_total(counters.read_count,
'read_count')
elif metric == 'ops':
total = self._calculate_total(counters.write_count,
'write_count')
elif metric == 'bps':
total = self._calculate_total2(counters.write_bytes,
'write_bytes',
counters.read_bytes,
'read_bytes')
disk_info={}
# 返回已经挂载的文件系统信息 (device='/dev/sda3', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro')
partitions=psutil.disk_partitions()
# 过滤掉光盘
partitions=[(partition[1],partition[2],partition[0])for partition in partitions if partition[2]!='iso9660']
disk_info={}
for partition in partitions:
disk_info[partition[0]]={}
disk_info[partition[0]]['fstype']=partition[1]
disk_info[partition[0]]['device']=partition[2]
for mount_point in disk_info.keys():
data=psutil.disk_usage(mount_point)
disk_info[mount_point]['total(GB)']=data[0]/1024/1024/1024
disk_info[mount_point]['used_percent(%)']=data[3]
device=disk_info[mount_point]['device']
counter=psutil.disk_io_counters(perdisk=True)
#disk_info['read_count']=counter[0]
return disk_info
except Exception:
continue
else:
self.network.append(netstat)
self.network_old = self.network_new
# SENSORS
if sensors_tag:
self.sensors = self.glancesgrabsensors.get()
# DISK I/O
if psutil_disk_io_tag:
self.diskio = []
if psutil_disk_io_tag and hasattr(psutil, 'disk_io_counters'):
if not hasattr(self, 'diskio_old'):
self.diskio_old = psutil.disk_io_counters(True)
else:
self.diskio_new = psutil.disk_io_counters(True)
for disk in self.diskio_new:
try:
# Try necessary to manage dynamic disk creation/del
diskstat = {}
diskstat['disk_name'] = disk
diskstat['read_bytes'] = (
self.diskio_new[disk].read_bytes -
self.diskio_old[disk].read_bytes)
diskstat['write_bytes'] = (
self.diskio_new[disk].write_bytes -
self.diskio_old[disk].write_bytes)
except Exception:
continue
else:
#get memory usage
physmem_psutil = psutil.virtual_memory()
physmem = {u"Available":bytes2human(physmem_psutil.available),u"Used":bytes2human(physmem_psutil.used),u"Free":bytes2human(physmem_psutil.free),u"Total":bytes2human(physmem_psutil.total)}
#print json.dumps(physmem)
#get network usage
nw_psutil = psutil.net_io_counters()
nw = {u"Sent":bytes2human(nw_psutil.bytes_sent),u"Recv":bytes2human(nw_psutil.bytes_recv),u"PacketsSent":bytes2human(nw_psutil.packets_sent),u"PacketsRecv":bytes2human(nw_psutil.packets_recv)}
#print json.dumps(nw)
#get disk throughput
disk_tp_psutil = psutil.disk_io_counters()
disk_tp = {u"TimesRead":disk_tp_psutil.read_count,u"TimesWrite":disk_tp_psutil.write_count,u"BytesRead":bytes2human(disk_tp_psutil.read_bytes),u"BytesWrite":bytes2human(disk_tp_psutil.write_bytes)}
#print json.dumps(disk_tpdict)
#combine all info in a dict
allinfo = {u"Temp":sensor_temperatures,u"CPU":cpu,u"HDD":hard_drives,u"Memory":physmem,u"Network":nw,u"DiskThroughput":disk_tp}
#dump it into JSON
data = json.dumps(allinfo, sort_keys=True, indent=4, separators=(',', ': '))
#send data to URL configured in configuration file
#important: set correct content type!
req = urllib2.Request(config[u"url"], data, {u'Content-Type': u'application/json'})
#get and print response
with contextlib.closing(urllib2.urlopen(req)) as f:
response = f.read()
for partition in partitions:
print(f"=== Device: {partition.device} ===")
print(f" Mountpoint: {partition.mountpoint}")
print(f" File system type: {partition.fstype}")
try:
partition_usage = psutil.disk_usage(partition.mountpoint)
except PermissionError:
# this can be catched due to the disk that
# isn't ready
continue
print(f" Total Size: {get_size(partition_usage.total)}")
print(f" Used: {get_size(partition_usage.used)}")
print(f" Free: {get_size(partition_usage.free)}")
print(f" Percentage: {partition_usage.percent}%")
# get IO statistics since boot
disk_io = psutil.disk_io_counters()
print(f"Total read: {get_size(disk_io.read_bytes)}")
print(f"Total write: {get_size(disk_io.write_bytes)}")
# Network information
print("="*40, "Network Information", "="*40)
# get all network interfaces (virtual and physical)
if_addrs = psutil.net_if_addrs()
for interface_name, interface_addresses in if_addrs.items():
for address in interface_addresses:
print(f"=== Interface: {interface_name} ===")
if str(address.family) == 'AddressFamily.AF_INET':
print(f" IP Address: {address.address}")
print(f" Netmask: {address.netmask}")
print(f" Broadcast IP: {address.broadcast}")
elif str(address.family) == 'AddressFamily.AF_PACKET':
print(f" MAC Address: {address.address}")
def getSystemInfo(cls):
system = {
'boot_time': psutil.boot_time(),
'cpu_count': psutil.cpu_count(),
'cpu_stats': psutil.cpu_stats().__dict__,
'cpu_times': [k.__dict__ for k in psutil.cpu_times(percpu=True)],
'disk_io_counters': psutil.disk_io_counters().__dict__,
'disk_usage': [],
'net_io_counters': psutil.net_io_counters().__dict__,
'swap_memory': psutil.swap_memory().__dict__,
'virtual_memory': psutil.virtual_memory().__dict__
}
partitions = psutil.disk_partitions()
for p in partitions:
if p.mountpoint in cls.INCLUDED_PARTITIONS:
usage = psutil.disk_usage(p.mountpoint)
system['disk_usage'].append({
'mountpoint': p.mountpoint,
'total': usage.total,
'used': usage.used
})
read_time = RunnableNode('read_time', method=lambda: (ps.disk_io_counters(perdisk=True)[disk_name].read_time, 'ms'))
write_time = RunnableNode('write_time',
for interface in psutil.net_io_counters(True):
netint = psutil.net_io_counters(True)[interface]
total_bytes = netint.bytes_recv + netint.bytes_sent
total_packages = netint.packets_sent + netint.packets_recv
self.__bandwidth_base[interface] = total_bytes
self.__msg_freq_base[interface] = total_packages
dev_names = []
for disk in psutil.disk_partitions():
if all(['cdrom' not in disk.opts, 'sr' not in disk.device]):
dev_names.append(disk.device)
for key in psutil.disk_io_counters(True):
if key in dev_names:
disk = psutil.disk_io_counters(True)[key]
self.__disk_read_base[key] = disk.read_bytes
self.__disk_write_base[key] = disk.write_bytes
psutil.cpu_percent(True)
psutil.virtual_memory()
disks_before = psutil.disk_io_counters(perdisk=False)
while True:
if time.time() > timeout:
break
#, percpu=True
# non-blocking (percentage since last call)
cpu = psutil.cpu_percent(interval=0)
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
if doDisk:
disks_after = psutil.disk_io_counters(perdisk=False)
disks_read_per_sec = (disks_after.read_bytes - disks_before.read_bytes)/(sleepSec * 1024.*1024.)
disks_write_per_sec = (disks_after.write_bytes - disks_before.write_bytes)/(sleepSec * 1024.*1024.)
disks_read_time_sec = (disks_after.read_time - disks_before.read_time)/(sleepSec*1000.)
disks_write_time_sec = (disks_after.write_time - disks_before.write_time)/(sleepSec*1000.)
#print "read %fM, write=%fM, read_time=%fs, write_time =%fs"%((disks_read_per_sec),\
# (disks_write_per_sec),\
# (disks_read_time_sec),\
# (disks_write_time_sec) )
disks_before = disks_after
#vmem(total=8240947200L, available=7441436672L, percent=9.7, used=1939496960L,
#free=6301450240L, active=727162880, inactive=966086656, buffers=123904000L, cached=1016082432)
sql = """INSERT INTO %s(mem,cpu,swap,