檢測80端口
一、前言主要以Python和Shell方式在Centos7.9操作系統上編寫腳本。腳本大概思路是通過netstat、grep、wc判斷80端口的行數,行數為0
一、前言
主要以Python和Shell方式在Centos7.9操作系統上編寫腳本。腳本大概思路是通過netstat、grep、wc判斷80端口的行數,行數為0則啟動httpd服務。
二、腳本思路
- 使用
netstat -lntp監聽所有端口 - 使用
grep ':80'只篩選出80端口 - 使用
wc -l統計出包含80端口的行數 - 判斷包含80端口的行數是否為0,如果是0,則由163郵箱發送告警消息到qq郵箱
三、環境模擬
3.1 準備工作
1.關閉防火墻
(1)臨時關閉防火墻
$ systemctl stop firewalld
(2)永久關閉防火墻
$ systemctl disable firewalld
2.關閉selinux
(1)臨時關閉selinux
$ setenforce 0
(2)永久關閉selinux
$ sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
3.安裝netstat
$ yum install net-tools
3.2 模擬環境搭建
1.安裝 Apache
$ yum install httpd -y
2.關閉Apache
$ systemctl stop httpd
四、腳本編寫
4.1 Shell腳本
1.編寫python腳本
$ vim 6-mail.py nimport smtplibnfrom email.mime.text import MIMETextnnsender = "123456789@163.com"npassword = "AAAAAAAAAAAAA"nreceiver = "123456789@qq.com"nnmessage = MIMEText("告警信息:80端口未開啟,已自動開啟80端口")nmessage["Subject"] = "告警信息"nmessage["From"] = sendernmessage["To"] = receivernnsmtp_server = smtplib.SMTP("smtp.163.com", 25)nsmtp_server.login(sender, password)nsmtp_server.sendmail(sender, receiver, message.as_string())nsmtp_server.quit()
上面代碼詳細分析:
(1)導入庫
import smtplibnfrom email.mime.text import MIMEText
- smtplib 庫:提供了基本的 SMTP 功能
- email 庫:提供了復雜的郵件內容構造功能
(2)定義了三個變量:sender、password 和 receiver。分別存儲了發件人的郵件地址、密碼以及收件人的郵件地址。
sender = "123456789@163.com"npassword = "AAAAAAAAAAAA"nreceiver = "123456789@qq.com"
注意這里的password不是郵箱登錄密碼。而是授權碼!
(3)利用 MIMEText 庫構造了郵件的內容
message = MIMEText("告警信息:80端口未開啟,已自動開啟80端口")nmessage["Subject"] = "告警信息"nmessage["From"] = sendernmessage["To"] = receiver
MIMEText("告警信息:系統出現故障,請立即處理")` 構造了一個文本郵件message["Subject"] = "告警信息"設置了郵件的主題message["From"] = sender設置了發件人的郵件地址,這里指163郵箱message["To"] = receiver設置了收件人的郵件地址,這里指qq郵箱
(4)登錄執行發郵件并退出163郵箱
smtp_server = smtplib.SMTP("smtp.163.com", 25)nsmtp_server.login(sender, password)nsmtp_server.sendmail(sender, receiver, message.as_string())nsmtp_server.quit()
2.編寫shell腳本
$vim 6.sh n#!/bin/bashnwhile :ndon num=`netstat -lntp | grep ':80' | wc -l`n if [ $num -eq 0 ]n thenn systemctl start httpdn python3.8 6-mail.pyn fin sleep 30ndone
上面netstat參數說明如下:
- -l:僅列出在監聽的服務狀態
- -n:直接使用IP地址,不通過域名服務器
- -t:顯示TCP傳輸協議的連線狀況
- -p:顯示正在使用Socket的程序識別碼和程序名稱
上面wc參數說明如下:
- -l:統計行數
上面代碼詳細分析:
(1)創建了一個無限循環。: 是一個 shell 內置命令,不執行任何操作,因此循環將始終為真。
while :
(2)使用 netstat 命令顯示網絡連接及其狀態,使用 grep 過濾輸出以顯示包含 :80 的行。最后,使用 wc -l 計算過濾行的數量。結果存儲在 num 變量中。
don num=`netstat -lntp | grep ':80' | wc -l`
(3)檢查 num 變量的值是否等于 0。如果值為 0,則表示端口 80 上沒有運行服務。
if [ $num -eq 0 ]
(4)前面的條件為真,這一行使用 systemctl 命令啟動 Apache Web 服務器。并運行一個 Python 腳本(6-mail.py),該腳本可能用于發送電子郵件通知。
systemctl start httpdn python3.8 6-mail.py
(5)fi 關閉 if 語句,sleep 30 命令在重新啟動循環之前暫停腳本 30 秒。
fin sleep 30ndone
3.執行shell腳本
$ bash 6.sh
4.登錄qq郵箱,查看告警信息郵件,這里我就不截圖了。







