linux基础 作业篇
1.自动部署反向代理 web nfs
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/python #-*- coding:utf-8 -*- #开发脚本自动部署及监控 #1.编写脚本自动部署反向代理、web、nfs; #!/bin/bash #检测安装nginx function detection_nginx(){ if [ -f /etc/nginx/nginx.conf ] #判断nginx文件是否存在 then echo 'nginx has been installed' exit else then yum install epel-release -y yum install nginx -y echo 'nginx already installed' fi } #改写配置文件 function modify_nginx_conf(){ msg='upstream Pythonweb{ server 192.168.205.129 weight=3;server 192.168.205.129;server 192.168.205.129}' sed -ri "/^http/a $msg" /etc/nginx/nginx.conf #增加upstream sed -ri "/^ *location \/ \{$/a proxy_pass http://Pythonweb\;" /etc/nginx/nginx.conf #修改localtion } systemctl reload nginx #重新加载nginx #检测安装nfs和rpcbind function detection_nfs(){ if [ -d /var/lib/nfs ] then echo 'nfs has been installed' exit else then yum install rpcbind nfs-utils -y echo 'rpcbind nfs-utils already installed' fi } function start_service(){ #创建共享目录 mkdir /share #给用户增加写的权限 chmod -R o+w /share/ #改写nfs的配置文件 echo '/share 192.168.205.0/24(rw,sync,fsid=0)' >> /etc/exports #以追加的方式写入 #启动服务 systemctl start rpcbind.server systemctl start nfs-utils.server #设置开机启动 systemctl enable nfs-server.service systemctl enable rpcbind.service } detection_nginx #执行检测安装nginx函数 modify_nginx_conf #执行改写nginx.conf函数 detection_nfs #执行检测安装nfs函数 start_service #执行启动服务函数
2.监控主机的内存,超过阈值则发送报警邮件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/python #-*- coding:utf-8 -*- 题目:监控主机的内存,超过阈值则发送报警邮件 1.准备发送邮件的代码 #!/usr/bin/python # -*- coding: UTF-8 -*- import sys import smtplib import email.mime.multipart import email.mime.text server = 'smtp.163.com' port = '25' def sendmail(server,port,user,pwd,msg): smtp = smtplib.SMTP() smtp.connect(server,port) smtp.login(user, pwd) smtp.sendmail(msg['from'], msg['to'], msg.as_string()) smtp.quit() print('邮件发送成功email has send out !') if __name__ == '__main__': msg = email.mime.multipart.MIMEMultipart() msg['Subject'] = '你是风儿我是沙,缠缠绵绵回我家' msg['From'] = 'python4_mail@163.com' msg['To'] = 'python4_recvmail@163.com' user = 'python4_mail' pwd = 'sbalex3714' content='%s\n%s' %('\n'.join(sys.argv[1:4]),' '.join(sys.argv[4:])) #格式处理,专门针对我们的邮件格式 txt = email.mime.text.MIMEText(content, _charset='utf-8') msg.attach(txt) sendmail(server,port,user,pwd,msg) #把上述代码放在/usr/bin/my_mail 中 vim /usr/bin/my_mail #把代码拷贝到里面 chmod +x my_mail #给文件my_mail 可以执行的权限 2.新建我自己的脚本监控文件15.sh #!/bin/bash men = 0 #内存使用超过0%就会报警 function monitor_mem(){ mem_total = 'free | awk 'NR==2{print $2}'' \ '' \ mem_use ='free | awk 'NR==2{print $3}'' mem_per = 'echo "scale=2;$mem_use/$mem_total" |bc -l |cut -d. -f2' if [ $mem_per -gt $ mem ] then msg='TIME:$(date +%F_%T)' HOSTNAM:$(hostname) IPADDR:$(ifconfig | awk 'NR==2{print $2}') echo $msg /usr/bin/my_mail $mag fi } #3.编写计划任务 crontab -e -u root * * * * * /root/home/gandong/15.sh restart #每一分钟检测一次