#通過Python的psutil模塊,獲取當前系統的各種信息(比如內存,cpu,磁盤,登錄用戶等),並將信息進行備份
# coding=utf-8
# 獲取系統基本信息
import sys
import psutil
import time
import os
#獲取當前時間
time_str = time.strftime( "%Y-%m-%d", time.localtime( ) )
file_name = "./" + time_str + ".log"
if os.path.exists ( file_name ) == False :
os.mknod( file_name )
handle = open ( file_name , "w" )
else :
handle = open ( file_name , "a" )
#獲取命令行參數的個數
if len( sys.argv ) == 1 :
print_type = 1
else :
print_type = 2
def isset ( list_arr , name ) :
if name in list_arr :
return True
else :
return False
print_str = "";
#獲取系統內存使用情況
if ( print_type == 1 ) or isset( sys.argv,"mem" ) :
memory_convent = 1024 * 1024
mem = psutil.virtual_memory()
print_str += " 內存狀態如下:\n"
print_str = print_str + " 系統的內存容量為: "+str( mem.total/( memory_convent ) ) + " MB\n"
print_str = print_str + " 系統的內存以使用容量為: "+str( mem.used/( memory_convent ) ) + " MB\n"
print_str = print_str + " 系統可用的內存容量為: "+str( mem.total/( memory_convent ) - mem.used/( 1024*1024 )) + "MB\n"
print_str = print_str + " 內存的buffer容量為: "+str( mem.buffers/( memory_convent ) ) + " MB\n"
print_str = print_str + " 內存的cache容量為:" +str( mem.cached/( memory_convent ) ) + " MB\n"
#獲取cpu的相關信息
if ( print_type == 1 ) or isset( sys.argv,"cpu" ) :
print_str += " CPU狀態如下:\n"
cpu_status = psutil.cpu_times()
print_str = print_str + " user = " + str( cpu_status.user ) + "\n"
print_str = print_str + " nice = " + str( cpu_status.nice ) + "\n"
print_str = print_str + " system = " + str( cpu_status.system ) + "\n"
print_str = print_str + " idle = " + str ( cpu_status.idle ) + "\n"
print_str = print_str + " iowait = " + str ( cpu_status.iowait ) + "\n"
print_str = print_str + " irq = " + str( cpu_status.irq ) + "\n"
print_str = print_str + " softirq = " + str ( cpu_status.softirq ) + "\n"
print_str = print_str + " steal = " + str ( cpu_status.steal ) + "\n"
print_str = print_str + " guest = " + str ( cpu_status.guest ) + "\n"
#查看硬盤基本信息
if ( print_type == 1 ) or isset ( sys.argv,"disk" ) :
print_str += " 硬盤信息如下:\n"
disk_status = psutil.disk_partitions()
for item in disk_status :
print_str = print_str + " "+ str( item ) + "\n"
#查看當前登錄的用戶信息
if ( print_type == 1 ) or isset ( sys.argv,"user" ) :
print_str += " 登錄用戶信息如下:\n "
user_status = psutil.users()
for item in user_status :
print_str = print_str + " "+ str( item ) + "\n"
print_str += "---------------------------------------------------------------\n"
print ( print_str )
handle.write( print_str )
handle.close()