我正在尝试制作一个批处理脚本,它将在一个文件中写入特定的IP地址。 我有一个txt文件(由一个python脚本创build)有一个IP地址列表(每个新行一个),现在我需要ping每个IP使用for循环,检查TTL值是否在100到128之间(Windows主机)并将IP地址写入新文件。 我一直在努力调整设置variables和循环,但这一切都变得太复杂,无法运行。
到目前为止,我已经达到:
编辑:纠正下面的命令
for /f %i in (ip.txt) do ping -n 1 %i | find "TTL"
这会给我多行Ping输出,这里只显示单行(我刚刚使用4.2.2.2)
Reply from 4.2.2.2: bytes=32 time=1 ms ttl=45
如果我ping到单个IP,我可以selectTTL字段,但不是TTL的确切值
for /f "tokens=6 delims= " %a in ('ping -n 1 4.2.2.2 ^| find "TTL"') do echo %a
它给我的价值TTL=45而我需要45比较。 我读了关于setlocal enabledelayedexpansion这是有用的,但我不能将这些全部合并成一行,并使用setvariables,并使用IF-ELSE循环。
Plz对如何实现IPselect做了一些说明。
在Windows中使用python安装字体
Serverside FTP批处理脚本
传输文件使用scp
在制作完成后,由我编辑脚本解决scheme: –
这个批处理脚本将ping ips.txt文件中给出的每个IP地址。 findTTL值,如果TTL值等于128,它将运行命令NBTSTAT -A ip-address (用于查找GROUP信息)并将其存储在nbt_query_op.txt文件中。
在每个IP地址发出NBTSTAT命令之前,这个文件将被search到现有的结果,如果在文件中没有find特定IP的结果,NBTSTAT将被触发。
请注意 , variables应引用! 人物, !TTL! ,!ip1! !!ERRORLEVEL! 。 此外,还要感谢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 ) ) )
谢谢,
KRISS
通过batch file运行循环
子串操作中的延迟variables扩展
在shift之后使用`%*`
为什么%processor_architecture%总是返回x86而不是AMD64
在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 '***************************************************************************************
编辑:在30/06/2016 @ 19:11
我测试了这个文件:file.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
这个批处理文件:
@echo off Title Get TTL from IP adress set vbsfile=%Tmp%%~n0.vbs set IP_File=E:vb-pingip.txt set LogFile=Log.txt If Exist %LogFile% Del %LogFile% For /f %%a in ('Type %IP_File%') Do ( echo TTL for "%%a" is : & Call:VBS "%%a" ( echo TTL for "%%a" is : & Call:VBS "%%a" )>> %LogFile% ) echo. color 0A echo Hit any key to open the LogFile "%LogFile%" pause>nul Start "" %LogFile% Exit /b :VBS ( echo wscript.echo TTL(WScript.Arguments(0^)^) echo '********************************************************************************************************** echo Function TTL(strHost^) echo dim objPing,objRetStatus echo set objPing = Getobject("winmgmts:{impersonationLevel=impersonate}"^).ExecQuery _ echo ("select * from Win32_PingStatus where address = '" ^& strHost ^& "'"^) echo for each objRetStatus in objPing echo if IsNull(objRetStatus.StatusCode^) or objRetStatus.StatusCode ^<^> 0 then echo Ping = False echo WScript.Echo "Status code is " ^& objRetStatus.StatusCode echo else echo Ping = True echo TTL = objRetStatus.ResponseTimetoLive echo end if echo next echo End Function echo '********************************************************************************************************** )> "%vbsfile%" Cscript /Nologo "%vbsfile%" "%~1" Exit /b
我得到的结果是这样的:
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
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循环是不完整的。 我想你的意思
for /f %i in (ip.txt) do ping -n 1 %i | find "TTL"
所以,我的答案似乎变成了一个比我所寻求的有所不同的。 这是在Python 2.x我刚写完。 虽然它在执行方面不是非常复杂和隐蔽(弹出大量的CMD窗口并写入文件,然后读取以形成结果)。 但仍然完成了工作。 我想我将不得不做更多的研究DOS命令,并开始学习VB脚本;)。 大声笑。
谢谢@Ruggisberg和@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 froms(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 'rn' 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文件有: –
192.168.1.1 192.168.1.2 192.168.1.4 192.168.1.5
其结果是: –
>>> 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']
我不记得但不能得到命令模块 (Windows不支持)和子进程模块 ( 尽管他们在Linux上完美的工作 )的支持。 如果有人有任何想法如何将结果存储到任何列表/字典/变量,PLZ更新。 我不喜欢在CMD中使用输出重定向。
试一试这个批处理文件,以获得具有IP地址的同一行中的TTL值
@echo off Title Get TTL from IP adress set vbsfile=%Tmp%%~n0.vbs set IP_File=E:vb-pingip.txt set LogFile=Log.txt If Exist %LogFile% Del %LogFile% For /f %%a in ('Type %IP_File%') Do ( Call:VBS "%%a" & echo %%a ( Call:VBS "%%a" & echo %%a)>> %LogFile% ) echo. color 0A echo Hit any key to open the LogFile "%LogFile%" pause>nul Start "" %LogFile% Exit /b :VBS ( echo WScript.StdOut.Write TTL(WScript.Arguments(0^)^) echo '********************************************************************************************************** echo Function TTL(strHost^) echo dim objPing,objRetStatus echo set objPing = Getobject("winmgmts:{impersonationLevel=impersonate}"^).ExecQuery _ echo ("select * from Win32_PingStatus where address = '" ^& strHost ^& "'"^) echo for each objRetStatus in objPing echo if IsNull(objRetStatus.StatusCode^) or objRetStatus.StatusCode ^<^> 0 then echo Ping = False echo WScript.Echo "Status code is " ^& objRetStatus.StatusCode echo else echo Ping = True echo TTL = objRetStatus.ResponseTimetoLive echo end if echo next echo End Function echo '********************************************************************************************************** )> "%vbsfile%" Cscript /Nologo "%vbsfile%" "%~1" Exit /b
所以,我为所有不属于我的组织域的Windows客户端创建了完整的扫描脚本。 已经很长时间了,但我想把它张贴在这里。
这个脚本依赖于初始客户端扫描nmap的 ping-sweep。 由于使用多处理模块创建脚本不能在windows上运行,所以最好的选择是nmap 。 NMAP在几秒钟内对255个主机的全部子网进行ping扫描,并返回在网络中发现的客户端的FQDN(全限定域名)。
注意:您应该在扫描仪PC中定义DNS服务器。
脚本接下来要做的就是把nmap扫描的输出结果写入文件nmap_op.txt 。 然后脚本读取该文件的输出,并使用正则表达式取出IP和FQDN。 如果任何IP没有FQDN,则ping一次,输出写入文件response.txt 。 读取该文件,取出TTL值在100-129之间的IP。
add_to_db函数负责返回实际上不属于Domain的IP列表。 该功能使用3个列表来交叉检查IP,并从数据库文件中的最终列表中删除IP,但随后将其加入到域中,并且当它们联机时不断向数据库添加新的非域IP。
将这个python文件保存在脚本可以写入文件的目录中。 您应该查找两个文件非域ips.txt (所有非域IP)和[subnet_value] -result.txt为最终结果。
python scanner.py 192.168.1.0/24 192.168.2.0/24
您可以添加任意数量的网络进行扫描。 Plz不会改变网络arg的模式。 您只能使用“/”来定义网络的掩码值(不要使用*来代替/)。 对传递的参数没有异常处理。 运行脚本时,其余的输出将被理解。
此外,我正在考虑添加一个或两个更多的功能,以根据其MAC地址的供应商位定义一些IP作为例外。 例如,一些瘦客户端类型的设备(因为它们将只在独立模式下运行)给出了窗口范围的TTL值。
剧本很匆忙,没有任何课程(而且我也不喜欢),所以是最丑的形式;)
import os import time import re import sys import pickle import commands import subprocess def add_to_db(nondomain_ips,pickled_ips,domainIPs): print "NON domain IPs= ",str(nondomain_ips) #raw_input("....") print "PICKLED IPs= ",str(pickled_ips) #raw_input("....") print "Length of PICKLED IPs= ",len(pickled_ips) print "domain IPs:- ",str(domainIPs) #raw_input("....") if (len(pickled_ips) == 0): pickled_ips= nondomain_ips return pickled_ips for new_ip in nondomain_ips: print "comparing- ",str(new_ip) if new_ip not in pickled_ips: print "APPENDING ",str(new_ip)," to PICKLED IPs" pickled_ips.append(new_ip) else: pass for pickled_ip in pickled_ips: #print "CHECKING - ",pickled_ip," in domain and in DB file or not" if pickled_ip in domainIPs: print pickled_ip," JOINED domain,removing from DB file" pickled_ips.remove(pickled_ip) #print "PICKLED IPs:- ",str(pickled_ips) #raw_input("...") return pickled_ips def main(): if (len(sys.argv)<2): print "Wrong args,Give the subnet to scan,Example- nnpython script.py 192.168.1.0/24 192.168.2.0/24 [more subnets...]nnExiting...n" exit(3) print "TOTAL subnetS TO SCAN:- ",len(sys.argv) cwd = os.getcwd() print "Current Directory= ",cwd outfile = cwd+"\nmap_op.txt" for i in range(1,len(sys.argv)): time_Now = time.ctime() net = sys.argv[i] #print i #cmd = "nmap -sn " + str(sys.argv[i]) + " -oG "+str(outfile) cmd = "nmap -sn " + str(net) + " -oG "+str(outfile) print cmd try: os.remove(outfile) except Exception,e: print "Error deleting file",str(e) #raw_input("SENDING -sn SCAN....n") print "SENDING -sn SCAN....n" os.system(cmd) #print "Argv[i]= ",sys.argv[i].split('/')[0] print "Argv[i]= ",net.split('/')[0] result_file = str(cwd)+"\"+net.split('/')[0]+"-result.txt" print "result file= ",result_file #raw_input(" ... ") if os.path.exists(outfile): print outfile," - oG file creatednn-------------------------------------n" fp = open(outfile) hostlist=[] domainIPs = [] nondomain = [] ping_file = cwd+"\response.txt" try: os.remove(ping_file) except Exception,e: e=e for line in fp.readlines(): #print line #reg = r'Host:(.*)).*Status.*Up' reg = r'Host:s(d{1,3})s((.*)).*Status.*Up' res = re.match(reg,line) if res: #print "tt",res.group() ip = res.group(1) if ('()' in res.group(2)): name = 0 nondomain.append([ip,name]) ping_cmd = 'ping -n 1 '+str(ip)+'| find "TTL" >>'+cwd+"\response.txt" os.system(ping_cmd) else: name = res.group(2) domainIPs.append(ip) hostlist.append([ip,name]) else: pass #print "No object" fp.close() ## CLOSE THE NMAP OUTPUT FILE-HANDLE print "[+][+] All HOSTS:- ",str(hostlist),"n" #print "domain IPs:- ",str(domainIPs) print "TOTAL unresolved IPs:- ",nondomain,"n" nondomain_ip = [] #print "nnIP and TTL from RegExpn" regs = r'Reply froms(d{1,3})' for line in open(ping_file).readlines(): #print line obj = re.search(regs,line) if obj: ip = obj.group(1) ttl = obj.group(2) print str(ip)+" --- " + str(ttl) if (100<int(ttl)<129): nondomain_ip.append(ip) #print "non domain IPs = ",str(nondomain_ip) fp_result = open(result_file,'a') fp_result.write("nn"+time_Now+"n") fp_result.write(str(nondomain_ip)) fp_result.close() db_file = cwd+"\dbfile" if not os.path.exists(db_file): fpdb = open(db_file,'w') fpdb.close() if os.path.exists(db_file): print "DB_FILE created" with open(db_file,'rb') as fpdb: try: pickled_ips = pickle.load(fpdb) except Exception,error: print "Error in loading pickeled list" pickled_ips = [] print "Formed new pickled list= ",str(pickled_ips) fpdb.close() new_list = add_to_db(nondomain_ip,domainIPs) #print "nNEW IP-ADDRESSES ESTABLISHED AFTER COMPARING ALL LISTS:- n",str(new_list) with open(db_file,'wb') as fpdb: pickle.dump(new_list,fpdb) fpdb.close() with open(db_file,'rb') as fpdb: ips = pickle.load(fpdb) print "nnttTHE NON-domain IPs:- n",str(ips) with open("non-domain-ips.txt",'wb') as handle: for ip in ips: handle.write(ip) handle.write("rn") handle.close() print "SLEEPING FOR 10 SECONDS..." time.sleep(10) if __name__ == '__main__': while True: main() print "nnnttSCAN COMPLETED...sleep for 5 minutes before running another loop of scan...nnn" time.sleep(300)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。