Python运维自动化核心模块
一、系统性能信息模块 psutil
psutil是一个跨平台库,用于获取系统运行进程和系统利用率(CPU、内存、磁盘、网络等)信息,广泛应用于系统监控、分析和资源管理。
1. CPU信息采集
python
import psutil
# 获取CPU完整信息
cpu_info = psutil.cpu_times(percpu=True)
# 获取单项数据
print('用户CPU时间比:', psutil.cpu_times().user)
# CPU逻辑/物理个数
print('逻辑CPU数:', psutil.cpu_count())
print('物理CPU数:', psutil.cpu_count(logical=False))
运行结果:获取User Time、System Time、I/O Wait、Idle等CPU时间占比,以及CPU核心数量。
2. 内存信息采集
python
import psutil
mem = psutil.virtual_memory()
print('内存总数:', mem.total)
print('空闲内存:', mem.free)
print('内存使用率:', mem.percent)
# 交换分区信息
swap = psutil.swap_memory()
print('交换分区:', swap)
关键指标:total(总数)、used(已用)、free(空闲)、buffers(缓冲)、cached(缓存)、swap(交换分区)
3. 磁盘信息采集
python
import psutil
# 磁盘分区信息
print(psutil.disk_partitions())
# 指定分区使用情况
print(psutil.disk_usage('/'))
# 磁盘IO统计(总览)
print(psutil.disk_io_counters())
# 每块磁盘的IO详情
print(psutil.disk_io_counters(perdisk=True))
IO关键指标:read_count(读次数)、write_count(写次数)、read_bytes(读字节数)、write_bytes(写字节数)、read_time(读时间)、write_time(写时间)
4. 网络信息采集
python
import psutil
# 网络总IO信息
print(psutil.net_io_counters())
# 每个网络接口的IO信息
print(psutil.net_io_counters(pernic=True))
网络关键指标:bytes_sent(发送字节数)、bytes_recv(接收字节数)、packets_sent(发送包数)、packets_recv(接收包数)
5. 其他系统信息
python
import psutil, datetime
# 当前登录用户
print(psutil.users())
# 开机时间
print(psutil.boot_time())
print(datetime.datetime.fromtimestamp(psutil.boot_time()).strftime('%Y-%m-%d %H:%M:%S'))
6. 进程管理
python
import psutil
# 获取所有进程PID
print(psutil.pids())
# 实例化Process对象
p = psutil.Process(2000)
# 进程详细信息
print('进程名称:', p.name())
print('进程路径:', p.exe())
print('工作目录:', p.cwd())
print('进程状态:', p.status())
print('创建时间:', p.create_time())
print('UID:', p.uid())
print('GID:', p.gid())
print('CPU时间:', p.cpu_time())
print('CPU亲和度:', p.cpu_affinity())
print('内存利用率:', p.memory_percent())
print('内存RSS/VMS:', p.memory_info())
print('IO信息:', p.io_counters())
print('线程数:', p.num_threads())
7. popen类的使用(subprocess)
python
import subprocess
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
if output:
print("Output:\n", output.decode('utf-8'))
if error:
print("Error:\n", error.decode('utf-8'))
二、IP地址处理模块 IPy
IPy模块用于高效完成IP地址规划工作,包括网段计算、网络掩码、广播地址、子网数、IP类型等。
1. IP版本判断
python
from IPy import IP
print(IP('10.0.0.0/24').version()) # 4
print(IP('::1').version()) # 6
2. 网段IP个数与清单
python
from IPy import IP
ip = IP('192.168.1.0/24')
print(ip.len()) # 输出256
# 遍历所有IP
for x in ip:
print(x)
3. IP类常用方法
python
from IPy import IP
ip = IP('192.168.1.20')
# 反向解析地址
print(ip.reverseNames()) # ['20.1.168.192.in-addr.arpa.']
# 地址类型(PUBLIC/PRIVATE)
print(ip.iptype()) # PRIVATE
print(IP('114.114.114.114').iptype()) # PUBLIC
# 格式转换
print(IP('8.8.8.8').int()) # 134744072
print(IP('8.8.8.8').strHex()) # 0x8080808
print(IP('8.8.8.8').strBin()) # 00001000...
print(IP('8.8.8.8').strNormal()) # 8.8.8.8
4. 网段格式转换
python
from IPy import IP
# 根据IP与掩码生成网段
print(IP('192.168.1.0').make_net('255.255.255.0'))
print(IP('192.168.1.0/255.255.255.0', make_net=True))
print(IP('192.168.1.0-192.168.1.255', make_net=True))
strNormal参数说明:
wantprefixlen=0:无返回,如192.168.1.0wantprefixlen=1:prefix格式,如192.168.1.0/24wantprefixlen=2:十进制掩码格式,如192.168.1.0/255.255.255.0wantprefixlen=3:lastIP格式,如192.168.1.0-192.168.1.255
5. 网段比较与重叠判断
python
from IPy import IP
# 网段比较
print(IP('10.0.0.0/24') < IP('12.0.0.0/24')) # True
# 包含关系判断
print('192.168.1.100' in IP('192.168.1.0/24')) # True
print(IP('192.168.1.0/24') in IP('192.168.0.0/16')) # True
# 重叠判断(1=重叠,0=不重叠)
print(IP('192.168.0.0/23').overlaps('192.168.1.0/24')) # 1
print(IP('192.168.1.0/24').overlaps('192.168.2.0/24')) # 0
6. 交互式IP信息查询
python
from IPy import IP
ips = input('请输入IP或者网段:')
ips = IP(ips)
if len(ips) > 1:
print('网络地址:', ips.net())
print('子网掩码:', ips.netmask())
print('广播地址:', ips.broadcast())
print('反向解析地址:', ips.reverseNames()[0])
print('网络子网数:', len(ips))
else:
print('反向解析IP地址:', ips.reverseNames()[0])
三、系统批量运维管理器 paramiko
paramiko是基于Python实现的SSH2远程安全连接,支持认证及密钥方式,可实现远程命令执行、文件传输、中间SSH代理等功能。
1. 环境安装
部署Python3环境:
bash
yum install -y openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel libffi-devel gcc gcc-c++
tar zxvf Python-3.13.2.tgz
cd Python-3.13.2/
./configure --prefix=/usr/local/python3
make && make install
ln -s /usr/local/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip
配置国内镜像源:
bash
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/
安装paramiko:
bash
pip install paramiko
2. SSHClient核心组件
connect方法参数说明
| 参数 | 类型 | 说明 |
|---|---|---|
| hostname | str | 目标主机地址 |
| port | int | SSH端口,默认22 |
| username | str | 用户名,默认当前本地用户 |
| password | str | 密码验证 |
| pkey | PKey | 私钥身份验证 |
| key_filename | str/list | 私钥文件名 |
| timeout | float | TCP连接超时时间 |
| allow_agent | bool | 是否禁用SSH代理连接 |
| look_for_keys | bool | 是否搜索~/.ssh私钥文件 |
| compress | bool | 是否开启压缩 |
主机密钥策略
AutoAddPolicy:自动添加未知主机密钥RejectPolicy(默认):拒绝未知主机WarningPolicy:警告但接受未知主机
3. SSHClient远程命令执行案例
基础案例:获取远程服务器内存信息
python
import paramiko
hostname = '192.168.128.128'
username = 'root'
password = '123123'
paramiko.util.log_to_file('syslogin.log')
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=hostname, port=22, username=username, password=password, allow_agent=False)
stdin, stdout, stderr = ssh_client.exec_command('free - m')
for line in stdout:
print(line)
stdin.close()
ssh_client.close()
实战案例:多服务器内存信息巡检排序
python
import paramiko as pk
def get_info(host, port, user, pwd):
ssh_client = pk.SSHClient()
ssh_client.set_missing_host_key_policy(pk.AutoAddPolicy())
ssh_client.connect(hostname=host, port=port, username=user, password=pwd, allow_agent=False)
stdin, stdout, stderr = ssh_client.exec_command("free - m | grep Mem | awk '{print $4}'")
return stdout, stderr
hosts = ['192.168.100.138', '192.168.100.140']
infos = []
for ip in hosts:
mem, err = get_info(ip, 22, 'root', '123123')
for line in mem:
infos.append(int(line))
# 排序并保存
infos.sort(reverse=True)
new_list = [str(i) + '\n' for i in infos]
with open('a.txt', 'w', encoding='utf-8') as f:
f.writelines(new_list)
print('数据保存成功!')
4. SFTPClient文件传输
常用方法
from_transport(t):创建SFTP客户端通道put(localpath, remotepath):上传文件get(remotepath, localpath):下载文件mkdir(path):创建目录remove(path):删除文件rename(old, new):重命名stat(path):获取文件属性listdir(path):列出目录内容
文件上传下载示例
python
import paramiko
username = 'root'
password = '123123'
hostname = '192.168.128.128'
port = 22
try:
t = paramiko.Transport((hostname, port))
t.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(t)
# 上传文件
sftp.put('syslogin.log', '/root/files/syslogin.log')
# 下载文件
sftp.get('/root/files/linux.txt', 'E:\\pyproject\\linux.txt')
# 目录操作
sftp.mkdir('usrdir')
sftp.rename('usrdir', 'testdir')
sftp.rmdir('testdir')
# 查看文件属性
print(sftp.stat('linux.txt'))
print(sftp.listdir('./'))
t.close()
except Exception as err:
print(err)
5. 堡垒机模式远程命令执行
原理:通过SSHClient.connect连接堡垒机,使用invoke_shell开启新会话,然后发送"ssh user@IP"命令跳转到目标服务器执行操作。
python
import paramiko
import sys
blip = '192.168.128.128'
bluser = 'root'
blpasswd = '123123'
hostname = '192.168.128.129'
username = 'root'
password = '123123'
passinfo = "'s password:"
paramiko.util.log_to_file('syslogin.log')
# SSH登录堡垒机
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip, username=bluser, password=blpasswd)
# 创建会话
channel = ssh.invoke_shell()
channel.settimeout(10)
buff = ''
# 执行ssh登录业务主机
channel.send('ssh ' + username + '@' + hostname + '\n')
# 密码验证
while not buff.endswith(passinfo):
resp = channel.recv(9999).decode('utf-8')
buff += resp
# 发送密码
channel.send(password + '\n')
buff = ''
# 等待认证通过
while not buff.endswith('#'):
resp = channel.recv(9999).decode('utf-8')
if not resp.find(passinfo) == -1:
print('Error: Authentication failed.')
channel.close()
ssh.close()
sys.exit()
buff += resp
# 执行命令
channel.send('ifconfig\n')
buff = ''
while buff.find('#') == -1:
resp = channel.recv(9999).decode('utf-8')
buff += resp
print(buff)
channel.close()
ssh.close()
6. 堡垒机模式远程文件上传
原理:SFTPClient上传文件至堡垒机临时目录 → invoke_shell执行scp命令 → 复制文件到目标服务器
python
import paramiko
blip = '192.168.128.128'
bluser = 'root'
blpasswd = '123123'
hostname = '192.168.128.129'
username = 'root'
password = '123123'
tmpdir = '/tmp'
remotedir = '/data'
localpath = 'G:\\Python-3.13.2.tgz'
tmppath = tmpdir + '/Python-3.13.2.tgz'
remotepath = remotedir + '/Python-3.13.2.tgz'
passinfo = "'s password:"
# SFTP上传到堡垒机
t = paramiko.Transport((blip, 22))
t.connect(username=bluser, password=blpasswd)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localpath, tmppath)
sftp.close()
# SSH登录堡垒机
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip, username=bluser, password=blpasswd)
channel = ssh.invoke_shell()
channel.settimeout(10)
# 执行scp命令
channel.send('scp ' + tmppath + ' ' + username + '@' + hostname + ':' + remotepath + '\n')
# 密码验证与发送
buff = ''
while not buff.endswith(passinfo):
resp = channel.recv(9999).decode('utf-8')
buff += resp
channel.send(password + '\n')
buff = ''
# 等待完成
while not buff.endswith('#'):
resp = channel.recv(9999).decode('utf-8')
if not resp.find(passinfo) == -1:
print('Error: Authentication failed.')
channel.close()
ssh.close()
sys.exit()
buff += resp
print(buff)
channel.close()
ssh.close()
四、总结
| 模块 | 主要功能 | 应用场景 |
|---|---|---|
| psutil | 系统性能监控 | 获取CPU、内存、磁盘、网络、进程信息,监控系统健康度 |
| IPy | IP地址规划 | 网段计算、IP类型判断、地址格式转换、网段比较 |
| paramiko | 远程运维管理 | 批量服务器命令执行、文件上传下载、堡垒机模式运维 |