持续ping的一个脚本

Zss 发表于:

客户现场可能存在arp的病毒,导致网络时长中断,pc中记录的mac地址时长被更新掉,所以一直ping着让他一直更新

多进程打包称exe注意,加入import multiprocessing,multiprocessing.freeze_support(),和导入模块mu

mu模块为:

import os
import sys

try:

    if sys.platform.startswith('win'):
        import multiprocessing.popen_spawn_win32 as forking
    else:
        import multiprocessing.popen_fork as forking
except ImportError:
    import multiprocessing.forking as forking

if sys.platform.startswith('win'):

    class _Popen(forking.Popen):
        def __init__(self, *args, **kw):
            if hasattr(sys, 'frozen'):
                os.putenv('_MEIPASS2', sys._MEIPASS)
            try:
                super(_Popen, self).__init__(*args, **kw)
            finally:
                if hasattr(sys, 'frozen'):
                    if hasattr(os, 'unsetenv'):
                        os.unsetenv('_MEIPASS2')
                    else:
                        os.putenv('_MEIPASS2', '')

    forking.Popen = _Popen
#coding:gbk
from subprocess import PIPE,Popen
import os,re,time,mu,multiprocessing
from multiprocessing import Pool


def init():
    try:
        print('--------------->>  持续ping工具  <<----------------')
        print(' ')
        print('    在当前脚本本件夹的ping_ip.ini文件中添加ip')
        print(' ')
        print('-------------------------------------------------')
        time.sleep(2)
        if not os.path.isfile('ping_ip.ini'):
            with open('ping_ip.ini','a+') as f:
                f.write('第二行开始填写需要ping的ip\n')
                f.write('192.168.4.11\n')
                f.write('192.168.3.2\n')
        with open('ping_ip.ini', 'a+') as f:
            text = f.read()
            ip_list = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',text)
            return ip_list
    except Exception as e:
        print 'error msg:',e

def ping_task(ip):
    cmd = 'ping %s -n 1'%ip
    result = Popen(cmd,shell=True,stdout=PIPE)
    ping_result = result.stdout.readlines()[2]
    txt = '时间:%s IP:%s 结果:%s'%(time.strftime("%Y-%m-%d-%X"),ip,ping_result)
    print txt
    with open('ping_log.txt','a+') as f:
        f.write(txt)
    time.sleep(0.2)

if __name__ == '__main__':
    multiprocessing.freeze_support()
    ip_list = init()
    while 1:
        print('------------------------------------------')
        pool = Pool(len(ip_list))
        for i in ip_list:
            pool.apply_async(ping_task,(i,))
        pool.close()
        pool.join()
        time.sleep(1)