#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import time
import paramiko
import smtplib
from email.mime.text import MIMEText
from email.header import Header
ip = "10.x.x.x"
username = "admin"
passwd = "1"
s = ""
for i in range(100):
try:
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, port=22345, username=username, password=passwd)
break
except:
logger.warning("建立paramiko连接失败,请检查网络连接".format(ip))
time.sleep(10)
if i == 99:
s = "连接超时,请手动排查"
if s == "":
stdin, disk_info, stderr = ssh_client.exec_command("df -h") # linux命令*发挥
stdin, stdout, stderr = ssh_client.exec_command("echo 123 > /data/123")
stdin, inputinfo, stderr = ssh_client.exec_command("ls -l /data/123")
stdin, stdout, stderr = ssh_client.exec_command("rm -rf /data/123")
diskin = disk_info.readlines()
inputin = inputinfo.readlines()
ssh_client.close()
try:
disk_result = "OK" if "/dev/sdb1" in "".join(diskin) else "FAILED"
except:
disk_result = "FAILED"
try:
write_result = "OK" if "/data/123" in "".join(inputin) else "FAILED"
except:
write_result = "FAILED"
s = "/data是否挂载在 sdb1下 ----{}\n {}\n\n\n\n/data分区是否可读可写 -----{}\n {}".format(disk_result,"\n ".join(diskin),write_result,"".join(inputin))
mail_host = "xxx"
mail_password = 'xxxx'
sender = "xxx@xxx.com"
receivers = ['1@b.com','2@b.com','3@b.com']
year='年'
month='月'
day='日'
cc=time.localtime(time.time())
date_to = str(cc.tm_year)+year+str(cc.tm_mon)+month+str(cc.tm_mday)+day
message = MIMEText(s, "plain", "utf-8")
message['From'] = Header("from who", 'utf-8')
message['To'] = Header("to who", 'utf-8')
message['Subject'] = Header('{}环境监测'.format(date_to), 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit() # 关闭连接
print("查看邮件,以发送成功")
except smtplib.SMTPException:
print("发送失败")