嵌套的for循环,设置变量和批处理脚本中的if else

2024-09-29 01:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个批处理脚本,它将在一个文件中写入特定的IP地址。 我有一个txt文件(由一个python脚本创建)有一个IP地址列表(每一行一个),现在我需要使用for循环ping这些IP,检查TTL值是否在100到128(windows主机)之间,并将IP地址写入一个新文件。我一直在尝试调整设置变量和for循环,但这一切变得太复杂,无法运行。
到目前为止我已经达到:
EDIT:更正以下命令

for /f %i in (ip.txt) do ping -n 1 %i | find "TTL"

这将给我多行Ping输出,这里只显示单行(我使用的是4.2.2.2,例如)

^{pr2}$

如果我ping到单个IP,我可以选择TTL字段,但不能选择TTL的确切值

for /f "tokens=6 delims= " %a in ('ping -n 1 4.2.2.2 ^| find "TTL"') do echo %a

{45}给出了比较所需的值。 我读过关于setlocal enabledelayedexpansion的文章,这很有用,但是我不能将这些都组合成一行,使用set变量和使用IF-ELSE循环。
Plz对如何实现IP选择进行了简单描述。

制作批处理脚本后由我编辑解决方案:
此批处理脚本将pingIP.txt文件文件。找到TTL值,如果TTL值等于128,它将运行一个命令NBTSTAT-a ip地址(用于查找组信息),并将其存储在nbt_查询中_操作文本文件。
在对每个IP地址启动NBTSTAT命令之前,将搜索此文件中的现有结果,如果在该文件中找不到特定IP的结果,则NBTSTAT将激发。
注意,变量应该用括起来引用!字符,!TTL!, !防护等级1!, !错误等级!。此外,还要感谢RGuggisberg先生提供的指导。在

@echo off
setlocal EnableDelayedExpansion
for /f %%i in (ips.txt) do (
for /f "tokens=6 delims= " %%a in ('ping -n 1 %%i ^| find "TTL"') do (
    for /f "tokens=2 delims==" %%b in ('echo.%%a') do set ttl=%%b
    echo %%i has TTL:- !ttl!
    if !TTL! == 128      (set ip1=%%i
                 echo        SELECTED IP- !ip1! TTL- !TTL!
                 findstr /c:!ip1! nbt_query_op.txt
                 if not !ERRORLEVEL! ==0 echo !ip1!>>nbt_query_op.txt && nbtstat -A !ip1! | find "GROUP">>nbt_query_op.txt
                     )
                                          )
)


谢谢,


Tags: 文件in命令echoiptxt脚本for
3条回答

所以,我的答案似乎与我所寻求的答案有所不同。这是我刚写完的python2.x版本。虽然它在执行方面不是非常复杂和隐蔽(弹出大量的CMD窗口,写入文件,然后读取以形成结果)。但还是完成了任务。我想我得对DOS命令做更多的研究,并开始学习VB脚本;)。哈哈。
感谢@RGuggisberg和@Hackoo的支持

import os
import re
cwd = os.getcwd()
ip_file = cwd+"\\ip.txt"     ## IPs written in this file, one in each line, or the filename can be taken through command-line args (more portable)
ip = []
win_hosts = []
for line in open(ip_file).readlines():
    ip.append(line.rstrip())
del_cmd = "del "+cwd+"\\response.txt"    ## Delete response.txt file
os.system(del_cmd)                       ## as PING output keeps appending to it
for i in ip:
    cmd = "ping -n 1 "+str(i)+' | find "TTL" >> response.txt'    ## write PING response to response.txt
    os.system(cmd)
response_file = cwd+"\\response.txt"
for line in open(response_file).readlines():
    regs = r'Reply from\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*TTL=(\d{1,3})'   ## Regular Expression to catch IP and TTL-value
    obj = re.search(regs,line.rstrip('\n'))  ## also right-strip any possible new-lines, it'll probably be '\r\n' on Linux host
    if obj:
        ip = obj.group(1)
        ttl = obj.group(2)
        print ip," has TTL= ",ttl
        ttl = int(ttl)
        if (127<ttl<129):                ## change this to (54<ttl<65) to get Linux hosts
            win_hosts.append(ip)         ## Add the windows hosts to win_hosts list
print "\n[+][+] Windows Hosts = ",str(win_hosts)

我的ip.txt文件文件有:在

^{pr2}$

结果是:

>>> 
192.168.1.1  has TTL=  30
192.168.1.2  has TTL=  64
192.168.1.4  has TTL=  64
192.168.1.5  has TTL=  128

[+][+] Windows Hosts =  ['192.168.1.5']

我不太记得了,但无法获得对命令模块子进程模块的支持(,尽管它们在Linux-box上完美地工作)。如果有人知道如何将结果存储到任何列表/字典/变量中,请更新plz。我不喜欢在CMD中使用输出重定向。在

这会满足你的要求。在迁移到第一个示例时根据需要进行修改。在

for /f "tokens=6 delims= " %a in ('ping -n 1 4.2.2.2 ^| find "TTL"') do for /f "tokens=2 delims==" %b in ('echo.%a') do echo %b

顺便说一句,你帖子中的第一个FOR循环是不完整的。我想你是说

^{pr2}$

您可以在vbscript中执行以下操作:

strHost = "4.2.2.2"
if Ping(strHost) = True then
    Wscript.Echo "Host " & strHost & " contacted"
Else
    Wscript.Echo "Host " & strHost & " could not be contacted"
end if
'***************************************************************************************
Function Ping(strHost)
    dim objPing, objRetStatus
    set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
      ("select * from Win32_PingStatus where address = '" & strHost & "'")
    for each objRetStatus in objPing
        if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode <> 0 then
            Ping = False
            WScript.Echo "Status code is " & objRetStatus.StatusCode
        else
            Ping = True
            Msg = Msg & " Pingging " & strHost & vbCrlf & vbCrlf 
            Msg = Msg & "Bytes = " & objRetStatus.BufferSize & vbCrlf 
            Msg = Msg & "Time (ms) = " & objRetStatus.ResponseTime & vbCrlf 
            Msg = Msg & "TTL (s) = "  & objRetStatus.ResponseTimeToLive 
        end if
    next
    Wscript.echo Msg
End Function 
'***************************************************************************************

编辑:2016年6月30日19:11

我用这个文件测试:文件.txt在

4.2.2.2
www.google.com
www.google.fr
www.facebook.com
www.stackoverflow.com
www.yahoo.com
www.yahoo.fr
www.developpez.net

此批处理文件:

^{pr2}$

我得到了这样的输出结果:

TTL for "4.2.2.2" is : 
53
TTL for "www.google.com" is : 
51
TTL for "www.google.fr" is : 
51
TTL for "www.facebook.com" is : 
81
TTL for "www.stackoverflow.com" is : 
53
TTL for "www.yahoo.com" is : 
48
TTL for "www.yahoo.fr" is : 
48
TTL for "www.developpez.net" is : 
48

相关问题 更多 >