循环遍历bat文件中的每一行

时间:2017-05-26 04:15:42

标签: batch-file

我正在尝试生成证书请求并通过bat文件提交给CA.

我能够只为1个主机名执行此操作,因此我正在执行bat文件以自动生成所有这些。这是我尝试过的。它应该在hostnames.txt文件中逐行循环并替换所有变量。

How do you loop through each line in a text file using a windows batch file?

引用
set CA_SERVER=xxxx
set CA_NAME=xxxx
set LOGFILE=.\RequestCert.log
set LIST=hostnames.txt

if not exist %LIST% (
  echo %DATE% : %TIME% : ERROR : The list of hostnames file %LIST% is 
  missing. Cannot request certificate. Exiting! >> %LOGFILE% )

for /f "tokens=*" %%a in ("%LIST%") do (

  set HOSTNAME=%%a
  echo HOSTNAME
)

我想测试一个简单的echo是否会起作用,但是错误出现了:命令的语法不正确。我从stackoverflow中看到了很多引用,但它无法弄清楚出了什么问题。

以下是修复上述内容后我将要实施的内容。

openssl req -nodes -newkey rsa:2048 -nodes -keyout %HOSTNAME%.key -out 
%HOSTNAME%.csr -subj "/C=SG/ST=/L=xxx/O=xxx/OU=xxx 
/CN=%HOSTNAME%"

certreq -submit -f -config "%CA_SERVER%\%CA_NAME%" -attrib 
CertificateTemplate:SSLCert" %HOSTNAME%.csr

echo Generating certificate request and key for %HOSTNAME%

我知道这已被多次询问但我的似乎没有工作..提前感谢您的帮助!

更新 目前的配置在Gerhard Barnard的帮助下有效。 enter image description here

1 个答案:

答案 0 :(得分:0)

您的文件读取无效的主要原因是for循环中的""

如果您知道%%a是主机名,是否真的需要将%%a重新分配给主机名?

@echo off
set CA_SERVER=xxxx
set CA_NAME=xxxx
set LOGFILE=.\RequestCert.log
set LIST=hostnames.txt

if not exist %LIST% (
       echo %DATE% : %TIME% : ERROR : The list of hostnames file %LIST% is missing. Cannot request certificate. Exiting! >> %LOGFILE% )

FOR /F "tokens=*" %%a in (%LIST%) do (
                               echo %%a
                              )

查看setlocal DELAYEDEXPANSION,否则循环内的变量只会扩展一次。

因此,如果我们要将%%a分配给HOSTNAME,请执行以下操作:

@echo off
setlocal ENABLEDELAYEDEXPANSION
set CA_SERVER=xxxx
set CA_NAME=xxxx
set LOGFILE=.\RequestCert.log
set LIST=hostnames.txt

if not exist %LIST% (
  echo %DATE% : %TIME% : ERROR : The list of hostnames file %LIST% is missing. Cannot request certificate. Exiting! >> %LOGFILE% )

for /f "tokens=*" %%a in (%LIST%) do (
set "HOSTNAME=%%a"
echo !HOSTNAME!
)

完整的脚本。

@echo off
setlocal ENABLEDELAYEDEXPANSION
set CA_SERVER=xxxx
set CA_NAME=xxxx
set LOGFILE=.\RequestCert.log
set LIST=hostnames.txt

if not exist %LIST% (
echo %DATE% : %TIME% : ERROR : The list of hostnames file %LIST% is missing. Cannot request certificate. Exiting! >> %LOGFILE% )

for /F "tokens=*" %%a in (%LIST%) do (
set "HOSTNAME=%%a"
echo !HOSTNAME!
openssl "req -nodes -newkey rsa:2048 -nodes -keyout !HOSTNAME!.key -out !HOSTNAME!.csr -subj "/C=SG/ST=/L=xxx/O=xxx/OU=xxx /CN=!HOSTNAME!"

certreq -submit -f -config "%CA_SERVER%\%CA_NAME%" -attrib CertificateTemplate:SSLCert" !HOSTNAME!.csr

echo Generating certificate request and key for !HOSTNAME!
)