欢迎来到代码驿站!

当前位置:首页 >

Windows下DOS实现持续ping显示时间并保存日志

时间:2020-01-01 09:20:12|栏目:|点击:
Windows下DOS实现持续ping显示时间

DOS的脚本实现,部分电脑执行会卡死,按下ctrl+c后提示“过程试图写入的管道不存在。”,在其中加入cd\后部分电脑能正常运行,但兼容性还是不好。有些win7可以以管理员身份执行,就可以解决,但有些又不可以。
@echo off

set /p host=host Address:
set logfile=Log_%host%.log
echo Target Host = %host% >%logfile%
for /f "tokens=*" %%A in ('ping %host% -n 1 ') do (echo %%A>>%logfile% && GOTO Ping)
:Ping
for /f "tokens=* skip=2" %%A in ('ping %host% -n 1 ') do (
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A>>%logfile%
    echo %date% %time:~0,2%:%time:~3,2%:%time:~6,2% %%A
    timeout 1 >NUL
    GOTO Ping)

执行效果图:

Windows下Python实现持续ping显示时间

Python2.7的代码实现,用python实现就没有那么多兼容性问题了,还能跨平台
import os
import sys  
import time
import subprocess
cur_path = os.path.split(os.path.realpath(__file__))[0]

hostname = raw_input("host ip or name:")


def pyping(ipaddress):
    cur_time = time.strftime('%Y_%m_%d-%H:%M:%S',time.localtime(time.time()))
    #ipaddress = '198.252.206.140'  # guess who
    proc = subprocess.Popen(
        ['ping', '-n', '1', ipaddress],
        stdout=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    #if proc.returncode == 0:
        #print('{} is UP'.format(ipaddress))
    ping_ret ='T:%s, R:%s' % (cur_time, stdout.split("\n")[2])
    print ping_ret
    return ping_ret
        

log_path = cur_path + "\\%s_ping_log.txt" % hostname
with open(log_path, "a") as logfile:
    while 1:        
        ret_ping = pyping(hostname)
        logfile.write(ret_ping+'\r\n')
        logfile.flush()
        time.sleep(1)
执行效果如下:


上一篇:微信公众号授权登录、获取用户信息(openid)

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:Windows下DOS实现持续ping显示时间并保存日志

本文地址:http://www.codeinn.net/misctech/2184.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有