如何使用批处理文件列出URL列表的最终重定向?

问题描述

我有一个文本文件中的URL列表,我想将其读取到批处理文件中,并为每个URL输出最终的重定向我有一个可以正确处理一个URL的脚本,一个可以在列表中循环打印原始URL的脚本,但是需要帮助将它们组合以输出文本文件中每个URL的重定向URL。

单个URL流程:

curl -Ls -o /dev/null -w %{url_effective} https://www.example.com

输出到文本文件

@echo off
for /f "tokens=* delims=," %%a in (urls.txt) do (
set URL=%%a
)
echo %URL% >> results.txt
pause

我还想在循环中的每个URL之间放置5秒钟的暂停时间,这样我就不会使服务器过载。有人可以帮我把这些碎片拼在一起吗?

理想情况下,输出将如下所示:

https://www.example1.com,https://www.example-redirect.com/page1
https://www.example2.com,https://www.example-redirect.com/page2
https://www.example3.com,https://www.example-redirect.com/page3
https://www.example4.com,https://www.example-redirect.com/page4

解决方法

我建议将此注释批处理文件代码用于此任务。

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Check the existence of the file in directory of the batch file
rem which should contain the list of urls to process.
if not exist "%~dp0url.txt" (
    echo/
    echo ERROR: File url.txt is missing in directory: "%~dp0"
    echo/
    goto EndBatch
)

rem Delete the errors file on existing from a previous batch file execution.
del "%~dp0Errors.txt" 2>nul

rem Process the list of urls with writing into the results file those urls
rem which are redirected to a different url and into the errors file those
rem urls which could not be processed successfully by curl at all. An
rem existing results file is always overwritten on execution of FOR loop.
(for /F "usebackq delims=" %%I in ("%~dp0url.txt") do (
    set "UrlValid="
    for /F "delims=" %%J in ('curl.exe -Ls -o /dev/null -w %%{url_effective} "%%I" 2^>nul') do (
        set "UrlValid=1"
        if not "%%I" == "%%J" echo %%I,%%J
    )
    if not defined UrlValid >>"%~dp0Errors.txt" echo %%I
    %SystemRoot%\System32\timeout.exe /T 5 /NOBREAK >nul
)) >"%~dp0Results.txt"

rem Delete the results file if being an empty file. The errors file
rem is created only if there is at least one error with a url.
if exist "%~dp0Results.txt" for %%I in ("%~dp0Results.txt") do if %%~zI == 0 del "%~dp0Results.txt"

:EndBatch
endlocal

我不知道curl.exe在使用发布的命令行时会输出什么,因为我的计算机上没有安装此程序,也没有阅读其文档。我想它只输出最终的URL。另外,我不知道curl.exe在无效网址或发生错误的网址上输出的错误。

请阅读批处理文件的注释,这些注释以命令rem开头。

要了解所使用的命令及其工作方式,请打开command prompt窗口,在其中执行以下命令,并非常仔细地阅读每个命令显示的所有帮助页面。

  • call /? ...说明%~dp0 ...驱动器和参数0的路径,该参数是始终以反斜杠结尾的完整批处理文件路径。
  • del /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • rem /?
  • set /?
  • setlocal /?
  • timeout /?

请阅读有关Using command redirection operators的Microsoft文档,以获取对>>>2>nul的解释。当Windows命令解释器在执行内部命令>必须在内部 FOR 命令行上使用脱字符号^进行转义,以将其解释为文字字符。 strong> FOR ,它将在后台以curl.exe开始的单独命令过程中执行嵌入的%ComSpec% /c命令行,并在'中添加命令行作为附加参数。

PS:我建议您看看免费的Xenu's Link Sleuth