最近想持续监服务器的测硬盘容量,但是又不想在服务器上东搞西搞,发现python有个paramiko可以连接linux,
# -*- coding: utf-8 -*-
# @Author : mlp
# @File : linux_email.py
import paramiko,re,time,smtplib
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# HostIP = 地址
# username = 登录名
# passwd = 密码
#端口一般默认为22
def run(HostIP, username, passwd):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HostIP, 22, username, passwd)
#连接测试
#ssh.exec_command('ls')
#print(u"%s 连接成功"%HostIP)
#执行命令获取结果
stdin, stdout, stderr = ssh.exec_command('df -h')
#result = stdout.read().decode()
err = stderr.read()
result = stdout.read()
ssh.close()
#print(stdin, err)
#print(stdout.read())
aa = re.findall("[0-9]{1,2}%", result)
#print result #直接查看服务器返回结果
if int(aa[0].strip("%")) >= 50:
#print(u"************【注意】{0}服务器硬盘容量目前已使用{1}************ ".format(HostIP, aa[0]))
# 输入Email地址和口令:
from_addr = "mulipeng666@163.com"
password = "mlp123456"
# SMTP服务器地址:
smtp_server = "smtp.163.com"
# 收件人地址:
to_addr = "1023739289@qq.com"
msg = MIMEText(u"************【注意】{0}服务器硬盘容量目前已使用{1}************ ".format(HostIP, aa[0]), 'plain', 'utf-8')
msg['From'] = "mlp<********@163.com>"
msg['To'] = "***<******@qq.com>"
subject = u'【注意】硬盘容量预警'
msg['Subject'] = Header(subject, 'utf-8')
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
print(u"邮件发送成功")
server.quit()
else:
print(u"{}硬盘容量目前已使用{} ".format(HostIP, aa[0]))
except Exception as ex:
print " Error %s " % ex
if __name__ == '__main__':
print("--------------------------------------------------------------")
print u"开始连接"+time.strftime(u"当前日期:%Y年%m月%d日 %H:%M:%S",time.localtime(time.time()))
#把地址和密码放在下面
serverlist = {“***”:“******”}
for hostip in serverlist:
run(HostIP=hostip, username="root", passwd=serverlist[hostip])
ok,凑活能用