python写监控程序Pexpect模块(转载)
Published by xiaosixi on 2018年9月3日
1、安装pexpect模块
pip install pexpect==4.6.0
2、创建py文件
touch monitor.py
文件内容如下:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = 'liao gao xiang'
import re
import time
from datetime import datetime
import pexpect
class Monitor(object):
"""服务器自动化监控"""
def __init__(self):
self.host = "39.107.227.39"
self.user = "root"
self.password = "hj2018@dmg"
def ssh_command(self, command):
"""SSH登录执行命令"""
ssh = pexpect.spawn('ssh -l {} {} {}'.format(self.user, self.host, command)) # 登录口令
i = ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=30)
if i == 0:
ssh.sendline(self.password)
if i == 1:
ssh.sendline('yes')
ssh.expect('[p,P]assword: ')
ssh.sendline(self.password)
index = ssh.expect(["$", "#", pexpect.EOF, pexpect.TIMEOUT]) # 此处注意,root用户登录符号为#,普通用户为$
if index != 0:
print("登录失败!报错内容:{};{}".format(ssh.before.decode("utf-8"), ssh.after.decode("utf-8")))
return False
return ssh
def memory(self):
"""内存监控"""
ssh = self.ssh_command("cat /proc/meminfo")
ssh.expect(pexpect.EOF)
data = re.findall(r"(\d+) kB", ssh.before.decode("utf-8")) # ssh.before结果为bytes类型,使用utf-8解码为string
MemTotal = int(data[0]) // 1024 # 除以1024得到MB,整数