吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 4037|回复: 27
收起左侧

[Python 转载] python监控ip-ping是否正常

[复制链接]
choujie1689 发表于 2022-4-16 19:45
本帖最后由 15820394839 于 2022-4-16 20:16 编辑

前几天领导交给我一个任务,让我监控一台服务器是否正常开机,因为服务器有问题,会自动重启,但是需要按F1才能进入,所以有问题时要及时通知机房,于是就写了一个脚本,ping不通自动发邮件提醒机房。纯属新手,因为能力有限,在目录新建了一个count.txt,内容:replacecount=0|1;用来持续判断,然后用crontab按分钟运行;
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
import os
import sys
import smtplib
import pandas as pd
import re
import time
from email.mime.text import MIMEText
     
    #主函数
def ping():
    global ip
 
    ip = '192.168.0.0'
    backinfo =  os.system('ping -c 1 -w 1 %s'%ip) # 实现pingIP地址的功能,-c1指发送报文一次,-w1指等待1秒
 
    if backinfo:
        pring("ip无法ping通")
        print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        print('----------------------------------------------');
        checkcount();
    else:
            #iplist.append(ip)
            #print(iplist)
            print('ip正常')
            print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
            print('----------------------------------------------');
            checkcountrestore();
 
         
def goToma(notice):
    msg_from="111@qq.com"#发送方
    pwe="11111"#授权码
    to="111@qq.com"#接收方
     
    subjedt="这是PYthon发送的提醒邮件"#邮件主题
    content=notice#邮件内容
     
    #构造邮件
    msg=MIMEText(content)#msg邮件对象,也可以发送html格式,比如msg=MIMEText(content,"html","utf-8")
    msg["Subject"]=subjedt
    msg["From"]=msg_from
    msg["To"]=to
     
    #发送邮件
    try:
        ss = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
        ss.login(msg_from, pwe)
        ss.sendmail(msg_from, to, msg.as_string())  # 发送
        print("发送成功!")
    except Exception as e:
        print("发送失败!详情",e)
         
     
def getcount():
    #路径
    path = r"/root/ping/count.txt"
    #读入
    f = open(path, "r", encoding="utf-8")
    #获取内容
    str1 = f.read()
    recount = r'replacecount=(.*?);'
    count=re.findall(recount,str1)
    count=int(count[0]);
    f.close()
    return count
     
def checkcount():
    count = getcount()
    if count == 0:
        goToma('error ip:'+ip+'ping不通了');
        stc1 = "replacecount=0;"
        stc2 = "replacecount=1;"
        writecount(stc1,stc2)
    else:
        exit();
         
def checkcountrestore():
    count = getcount()
    if count == 1:
        stc1 = "replacecount=1;"
        stc2 = "replacecount=0;"
        writecount(stc1,stc2)
        goToma("success ip:"+ip+ "已恢复正常")
    else:
        exit();
         
def writecount(st1,st2):
    #路径
    path = r"/root/ping/count.txt"
    #读入
    f = open(path, "r", encoding="utf-8")
    #获取内容
    str1 = f.read()
    #替换内容
    str2 = str1.replace(st1,st2)
    #重新写入
    ff = open(path, "w")
    #将信息写入缓冲区
    ff.write(str2)
    #刷新缓冲区
    ff.flush()
 
     
if __name__=='__main__':
    ping()

免费评分

参与人数 3吾爱币 +3 热心值 +2 收起 理由
wangmi5200 + 1 + 1 我很赞同!
joylinklab + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
鸣蜩十四 + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

lizf2019 发表于 2022-4-16 20:15
不要用邮件!,要不然对方根本不能及时发现!!,有公网ip服务器的话用socket,程序放服务器,客户端给机房,设置间隔刷新状态
另:可视化推荐用C#
wangmi5200 发表于 2022-4-18 10:38
[Shell] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
import os
import subprocess
import telegram
 
ser = os.system ("ping -c 1 google.com")
 
 
 
if ser:
    print("server is down")
    bot = telegram.Bot(token='换成你tg bot')
    bot.sendMessage(chat_id='你的 tg id', text="服务器 掉线")
 
else:
    print("server is up")
    bot = telegram.Bot(token='换成你tg bot')
    bot.sendMessage(chat_id='你的 tg id', text="服务器 正常")



最好的是 TG 通知
hackerbob 发表于 2022-4-17 11:11
xfmiao 发表于 2022-4-17 10:45
没有任何问题,os.system 结果只有0和1,0是成功,1是失败,if直接判断的不用比较判断成功或者失败,看来 ...

我觉得有问题
os.system是执行cmd命令的,但是它返回的是一个布尔值,但这个布尔值只是命令是否执行成功,哪怕没ping通,只要命令执行成功,就会返回真
执行以下代码,1111.1111.111.11是一个不存在的ip,但依旧返回真
[Python] 纯文本查看 复制代码
1
2
3
4
5
6
7
import os
a = os.system("ping 1111.1111.111.11")
print(a)
if a:
    print("已ping通")
else:
    print("没ping通")

结果:
[Python] 纯文本查看 复制代码
1
2
3
Ping �����Ҳ������� 1111.1111.111.11����������ƣ�Ȼ�����ԡ�
1
已ping通


不存在的ip

不存在的ip

如下图所示

如下图所示
 楼主| choujie1689 发表于 2022-4-16 20:17
lizf2019 发表于 2022-4-16 20:15
不要用邮件!,要不然对方根本不能及时发现!!,有公网ip服务器的话用socket,程序放服务器,客户端给机房 ...

感谢给与的建议
头像被屏蔽
xiadongming 发表于 2022-4-16 20:19
提示: 作者被禁止或删除 内容自动屏蔽
liheping1987 发表于 2022-4-16 20:22
非常棒,大佬
hackerbob 发表于 2022-4-16 20:32
本帖最后由 hackerbob 于 2022-4-18 13:55 编辑

楼主没错,已编辑掉
拾染 发表于 2022-4-16 21:00
可以用thread和信号与槽,这样就不用进行IO操作,可以提升一下性能。
心伤的天堂 发表于 2022-4-16 21:15
  可以用zabbix  smokeping等等。
sxzx 发表于 2022-4-16 21:39
非常棒,大佬
politank 发表于 2022-4-16 22:17

谢谢LZ分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-5-21 03:55

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表