python中系统信息监控及链表的生成
一、模块
1. os模块
os.remove() 删除文件
os.rename() 重命名文件
os.listdir() 列出指定目录下所有文件
os.chdir() 改变当前工作目录
os.getcwd() 获取当前文件路径
os.mkdir() 新建目录
os.rmdir() 删除空目录(删除非空目录, 使用shutil.rmtree())
os.makedirs() 创建多级目录
os.removedirs() 删除多级目录
os.stat(file) 获取文件属性
os.chmod(file) 修改文件权限
os.utime(file) 修改文件时间戳
os.name(file) 获取操作系统标识
os.system() 执行操作系统命令
os.execvp() 启动一个新进程
os.fork() 获取父进程ID,在子进程返回中返回0
os.execvp() 执行外部程序脚本(Uinx)
os.spawn() 执行外部程序脚本(Windows)
os.access(path, mode) 判断文件权限(详细参考cnblogs)
os.wait() 暂时未知
os.path模块:
os.path.split(filename) 将文件路径和文件名分割(会将最后一个目录作为文件名而分离)
os.path.splitext(filename) 将文件路径和文件扩展名分割成一个元组
os.path.dirname(filename) 返回文件路径的目录部分
os.path.basename(filename) 返回文件路径的文件名部分
os.path.join(dirname,basename) 将文件路径和文件名凑成完整文件路径
os.path.abspath(name) 获得绝对路径
os.path.splitunc(path) 把路径分割为挂载点和文件名
os.path.normpath(path) 规范path字符串形式
os.path.exists() 判断文件或目录是否存在
os.path.isabs() 如果path是绝对路径,返回True
os.path.realpath(path) #返回path的真实路径
os.path.relpath(path[, start]) #从start开始计算相对路径
os.path.normcase(path) #转换path的大小写和斜杠
os.path.isdir() 判断name是不是一个目录,name不是目录就返回false
os.path.isfile() 判断name是不是一个文件,不存在返回false
os.path.islink() 判断文件是否连接文件,返回boolean
os.path.ismount() 指定路径是否存在且为一个挂载点,返回boolean
os.path.samefile() 是否相同路径的文件,返回boolean
os.path.getatime() 返回最近访问时间 浮点型
os.path.getmtime() 返回上一次修改时间 浮点型
os.path.getctime() 返回文件创建时间 浮点型
os.path.getsize() 返回文件大小 字节单位
os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径
os.path.lexists #路径存在则返回True,路径损坏也返回True
os.path.expanduser(path) #把path中包含的”~”和”~user”转换成用户目录
os.path.expandvars(path) #根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.sameopenfile(fp1, fp2) #判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2) #判断stat tuple stat1和stat2是否指向同一个文件
os.path.splitdrive(path) #一般用在windows下,返回驱动器名和路径组成的元组
os.path.walk(path, visit, arg) #遍历path,给每个path执行一个函数详细见手册
os.path.supports_unicode_filenames() 设置是否支持unicode路径名
2.platform模块
platform.platform 操作系统信息
platform.system 操作系统类型
platform.node 主机名
platform.release 版本
platform.version 获取操作系统版本号
platform.machine 计算机类型
platform. processor 计算机处理器信息
获取当前系统信息模块用platform,举例:
import os # 操作系统的类型: pofix=Linux, nt=Windows
print(os.name)
# 获取操作系统的其他信息
try:
uname = os.uname()
except:
import platform
uname = platform.uname()
print("操作系统信息",uname)
print("操作系统类型:", uname.system)
print("主机名:", uname.node)
print("版本:", uname.release)
print("获取操作系统版本号",uname.version)
print("计算机类型:", uname.machine)
print("计算机处理器信息",uname.processor)
测试:
3.psutil模块
psutil是一个跨平台库(https://github.com/giampaolo/psutil)
能够实现获取系统运行的进程和系统利用率(内存,CPU,磁盘,网络等),主要用于系统监控,分析和系统资源及进程的管理。
psutil.cpu_times() 获得CPU信息
psutil.cpu_percent() 查看当前主机每个cpu占用的内存比
psutil.cpu_count(logical=True) 查看当前主机逻辑cpu的个数
psutil.vitual_memory() 获得内存使用信息
psutil.swap_memory() 获得交换分区使用信息
psutil.disk_partitions() 获得磁盘的分区情况
psutil.disk_usage('/') 获得’/‘分区的使用情况
psutil.disk_io_counters() 获得磁盘的IO次数统计
psutil.net_io_counters() 获得网络的发包或者发送字节数目的统计信息
psutil.users() 获得登陆用户信息
psutil.boot_time() 用户的开机时间统计
psutil.pids() 列出进程的pid号码
psutil.Process(进程号码) 实例化一个进程,方便之后对该进程直接进行操作
psutil.Popen() 获得应用程序的实例
3.1查看CPU相关的信息
命令 | 作用 |
---|---|
psutil.cpu_times() | 获得CPU信息 |
psutil.cpu_percent() | 查看当前主机每个cpu占用的内存比 |
psutil.cpu_count(logical=True) | 查看当前主机逻辑cpu的个数 |
测试:
3.2查看系统内存时间
命令 | 作用 |
---|---|
psutil.vitual_memory() | 获得内存使用信息 |
psutil.swap_memory() | 获得交换分区使用信息 |
测试:
3.3查看磁盘信息
命令 | 作用 |
---|---|
psutil.disk_partitions() | 获得磁盘的分区情况 |
psutil.disk_usage(’/’) | 获得’/‘分区的使用情况 |
psutil.disk_io_counters() | 获得磁盘的IO次数统计 |
测试:
3.4查看系统其他信息
命令 | 作用 |
---|---|
psutil.users() | 获得登陆用户信息 |
psutil.boot_time() | 用户的开机时间统计 |
psutil.pids() | 列出进程的pid号码 |
psutil.Process(进程号码) | 实例化一个进程,方便之后对该进程直接进行操作 |
测试:
引入:datetime模块
由于psutil.boot_time()显示的时间不好辨识,则可以导入datetime模块中的datetime类中的方法,将时间转换容易识别的时间, time模块的time.ctime()也可以
代码:
import psutil
# 方法一:引入datetime模块
from datetime import datetime
boot_time =psutil.boot_time()
print("开机时间:",boot_time)
print("开机时间:",datetime.fromtimestamp(boot_time))
# 方法二:引入time模块
import time
boot_time =psutil.boot_time()
str_time =time.ctime(boot_time)
print("开机时间:",str_time)
测试:
引入:prettytable 模块
由于psutil.disk_partitions()的打印结果并不是很友好,可以选择导入from prettytable import Prettytable 类来实现制表的过程
代码:
import psutil
from prettytable import PrettyTable
disks = psutil.disk_partitions()
print(disks)
# pt.add_row()按行添加 , pt.add_column() 按列添加
pt = PrettyTable(field_names=['device','mountpoint','fstype','opts'])
for disk in disks:
pt.add_row([disk.device,disk.mountpoint,disk.fstype,disk.opts])
print(pt)
测试:
二、python中文件差异性比较
1.difflab模块,比较文件的差异
脚本运行后会生成一个html文件,进入这个html文件web界面能够清楚的看到文件差异
2.用哈希加密的方式查看两个文件是否被修改过
三、项目案例
- Linux服务器主机监控脚本
1.创建项目
2.修改app.py内容
from flask import Flask, render_template
from datetime import datetime
import psutil
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello Python!'
@app.route('/hostinfo/')
def hostinfo():
# return render_template('hostinfo.html')
# return '<h2 style="color:green">热搜</h2>'
try:
import os
os_uname = os.uname()
except Exception as e:
import platform
os_uname = platform.uname()
node= platform.uname().node
system =platform.uname().system
release =platform.uname().release
version = platform.uname().version
machine = platform.uname().machine
now_time = datetime.now()
boot_time = datetime.fromtimestamp(psutil.boot_time())
run_time = now_time - boot_time # 1:46:22
hour, minutes, seconds = str(run_time).split(':')
# return '<h1 style="color:green">登录页面!</h1>'
# 视图函数返回的值就是页面需要展示的内容
# 租用html模板, 返回好看的页面
return render_template('hostinfo.html', node =node ,
system=system,
release =release,
version = version ,
machine =machine,
now_time=now_time,
boot_time=boot_time,
hour = hour, minutes= minutes, seconds=seconds
)
@app.route('/disk/')
def disk():
# [(), (), (disk.device, disk.mountpoint, disk.fstype, disk.opts), ]
disks = psutil.disk_partitions()
return render_template('disk.html', disks=disks)
@app.route('/users/')
def users():
users = psutil.users()
return render_template('users.html', users=users)
@app.template_filter("todate")
def to_date(timestamp):
from datetime import datetime
dt = datetime.fromtimestamp(timestamp)
return str(dt)
if __name__ == '__main__':
app.run()
3.templates/disks.html 磁盘信息模块对应的html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入 Bootstrap CSS-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
{% include "nav.html" %}
<h1 style="color: darkmagenta">磁盘信息监控</h1>
<table class="table table-striped">
<tr>
<td>设备名称</td>
<td>挂载点</td>
<td>文件系统类型</td>
<td>挂载参数</td>
</tr>
{% for disk in disks %}
<tr>
<td>{{ disk.device }}</td>
<td>{{ disk.mountpoint }}</td>
<td>{{ disk.fstype }}</td>
<td>{{ disk.opts }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
4.templates/hostinfo.html 主机信息模块对应的html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入 Bootstrap CSS-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
{% include "nav.html" %}
<h1 style="color: darkmagenta">系统信息监控</h1>
<table class="table table-striped">
<tr>
<td>主机名</td>
<td>{{ node }}</td>
</tr>
<tr>
<td>系统名称</td>
<td>{{ system }}</td>
</tr>
<tr>
<td>发行版本号</td>
<td>{{ release }}</td>
</tr>
<tr>
<td>内核版本</td>
<td>{{ version }}</td>
</tr>
<tr>
<td>系统架构</td>
<td>{{ machine }}</td>
</tr>
<tr>
<td>开机时间</td>
<td>{{ boot_time }}</td>
</tr>
<tr>
<td>当前时间</td>
<td>{{ now_time }}</td>
</tr>
<tr>
<td>开机时长</td>
<td>{{ hour }}小时{{ minutes }}分钟{{ seconds}}秒</td>
</tr>
</table>
</body>
</html>
5.templates/users.html 用户信息模块对应的html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入 Bootstrap CSS-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
{% include "nav.html" %}
<h1 style="color: #8b008b">用户信息监控</h1>
<table class="table table-striped">
<tr>
<td>登陆的用户</td>
<td>登陆的终端</td>
<td>登陆时间</td>
</tr>
{% for user in users %}
<tr>
<td>{{ user.name }}</td>
<td>{{ user.terminal }}</td>
<td>{{ user.started |todate }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
6.templates/nav.html 导航栏模块对应的html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="/hostinfo/">SysInfo</a>
</div>
<div>
<ul class="nav navbar-nav">
<li class="active"><a href="/hostinfo/">主机信息</a></li>
<li><a href="/disk/">磁盘信息</a></li>
<li><a href="/users/">用户信息</a></li>
</ul>
</div>
</div>
</nav>
</body>
</html>
7.测试结果:
- 基于Python实现链表的创建,使用头插法和尾插法
代码:
class Node(object): # 定义节点类
def __init__(self, value):
self.value = value
self.next = None
class linkedlist(object):
def __init__(self):
self.head = None
self.tail = None
def head_insert(self, n): # 头插法
n = Node(n)
n.next = self.head
self.head = n
def tail_insert(self, n): # 尾插法
n = Node(n)
if not self.tail and not self.head:
self.tail = self.head = n
elif not self.tail and self.head:
cur = self.head
while cur:
self.tail = cur
cur = cur.next
self.tail.next = n
self.tail = n
else:
self.tail.next = n
self.tail = n
def travel(self): # 链表的遍历
cur = self.head
while cur:
print(cur.value)
cur = cur.next
if __name__ == '__main__':
linked_list = linkedlist()
linked_list.head_insert(1)
linked_list.tail_insert(2)
linked_list.tail_insert(3)
linked_list.head_insert(0)
linked_list.tail_insert(4)
linked_list.travel()
测试结果: