Python Psutil Simple Example
Write a simple detection script with Psutil
0. Installing the Psutil module
Psutil Official website: https://pythonhosted.org/psutil/
Download:
# wget https://pypi.python.org/packages/57/93/ 47a2e3befaf194ccc3d05ffbcba2cdcdd22a231100ef7e4cf63f085c900b/psutil-5.2.2.tar.gz#md5= bb98d48796cd76d9ccee871aad720f9c
Extract:
Tar XF psutil-5.2. 2. tar.gz
Installation:
CD psutil-5.2. 2/grep"python-devel"yuminstall Install[$0echo"install OK"Echo "Install fail"
When install OK is present, it proves that Psutil installation is complete.
Writing a Python script
#!/usr/bin/python#Filename:pustil_free.py#import psutil and OsImportPsutil,os#definition fileFile = Open (r'Log.txt','a')#get memory already in usefree_used =psutil.virtual_memory (). Used#Get Total MemoryFree_total =psutil.virtual_memory (). Total#calculate the percentage of memory usedPercentage_free = free_used * 1.0/free_total * 100#when Free>80ifPercentage_free >= 80: Templist= [] #get PID for all processes forPidinchpsutil.pids ():deltemplist[:] P=Psutil. Process (PID)#when using a memory beam does not equal 0 o'clock perform this if ifP.memory_percent ()! =0:#get the name of the memoryTemplist.append (P.name ())#get the percentage of memory consumptionTemplist.append (P.memory_percent ()) Temp_value=templist#REDIRECT value Print>> file, (templist[0],templist[1]) #Clear Documentsfile.close ()#########################################################################Send mail module sendmail (' Log.txt ')########################################################################Delete the log file to perform the next script regenerationOs.remove ('Log.txt')
2017-05-17 10:06:58
I want to be a Linux OPS engineer
Python Psutil Simple Example