批处理文件 - 循环 ping - 输出到已启动的文件主机
我想制作一个 .bat 文件,它将执行如下所示的 for 循环:
@echo off
FOR /L %%G IN (1, 1, 69) DO (
ping -n 1 192.168.%%G.3
ping -n 1 192.168.%%G.4
)
然后查看输出并仅将成功回复 ping 的 IP 发送到 txt 文件。这可以通过 CMD 批处理文件实现吗?
I would like to make a .bat file that will do a for loop like below:
@echo off
FOR /L %%G IN (1, 1, 69) DO (
ping -n 1 192.168.%%G.3
ping -n 1 192.168.%%G.4
)
Then look through the output and send only the IPs that replied successfully to the ping to a txt file. Is this possible with a CMD batch file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基本上,您使用
&&
添加仅在前一个命令(&&
之前的命令)成功完成时才执行的命令(从技术上讲,返回退出代码0
)。对于相反的情况也有类似的方法。如果您想对命令的不成功结果执行某些操作,请将
||
放在它后面,然后是执行操作的命令。编辑
关于
ping
的一点说明。有时您会从路由器收到主机不可访问的通知。在这种情况下,ping
仍然会退出并显示0
代码(“成功”),因为它确实收到了回复,即使它来自路由器而不是来自实际主机。如果您的主机就是这种情况,并且您不想在输出文件中出现此类误报,则必须解析
ping
的输出以获取一些关键字,以指示 ping 是否是确实成功了。到目前为止,您可以依赖显示汇总统计信息的行:它们仅在回复来自预期主机时才会出现。因此,这是替代方法:
编辑 2
将两种解决方案更改为使用子例程调用,以避免
for
内的%ip%
过早扩展环形。 (也可以通过启用延迟扩展来修复。)还在各处引用
%output%
。Basically, you use
&&
to add the command that is only executed if the previous command (the one before the&&
) completed successfully (technically speaking, returned the exit code of0
).There's a similar approach for the opposite case. If you want to perform some actions on the unsuccessful result of a command, you put
||
after it and then the command implementing your action.EDIT
One note about
ping
. Sometimes you get a notification from the router that the host is not accessible. In this caseping
still exits with0
code ('successful'), because it does get a reply, even if it's from the router and not from the actual host.If that can be the case with your hosts and you don't want to have such false positives in the output file, you'll have to parse the output of
ping
for some keywords indicating whether the pinging was successful indeed. So far you can rely on the lines showing the aggregate stats: they only appear if the reply was from the intended host.So, here's the alternative approach:
EDIT 2
Changed both solutions to use subroutine call in order to avoid premature expansion of
%ip%
inside thefor
loop. (Could also be fixed by enabling delayed expansion instead.)Also quoted
%output%
everywhere.