1. 程式人生 > >使用Python在windows環境下獲取Linux伺服器的磁碟、記憶體等資訊

使用Python在windows環境下獲取Linux伺服器的磁碟、記憶體等資訊

最近想持續監伺服器的測硬碟容量,但是又不想在伺服器上東搞西搞,發現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}************\n".format(HostIP, aa[0]))
# 輸入Email地址和口令:
from_addr = "[email protected]"
password = "mlp123456"
# SMTP伺服器地址:
smtp_server = "smtp.163.com"
# 收件人地址:
to_addr = "[email protected]"

msg = MIMEText(u"************【注意】{0}伺服器硬碟容量目前已使用{1}************\n".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"{}硬碟容量目前已使用{}\n".format(HostIP, aa[0]))

except Exception as ex:
print "\tError %s\n" % 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,湊活能用