Wednesday 13 June 2012

Automating Installing/Importing pfx (certificate) from command line (certutil) on remote servers.

A few days ago I had to sit and install a new certificate to a number of servers. These servers did not exist in an AD environment so using group policy was not an option.
However I thought I could some how script this. I have written a few batch files in the past to execute on a remote server and to do this I used the sysinternals tool psexec. So all I needed was how to import from the command line.
I found that certutil.exe ( a free ms tool) which appears to come with windows 2003 server+ could probably some how do what I wanted. However just using the help I could not see a command to import a pfx, however after trawling Google for a while I found that there is a command but it just does not appear to be list in the certutil help (certutil /?).
So I used the following command
certutil –f –p –importpfx
-f : force overwrite of certificate
-p: Password of the pfx file
This command will install the certificate into the personal store of the computer account. There are additional commands to install to other stores and locations, such as “–user My” which put it into the personal store if the user, and –addstore ca. Please look up these as I only include here as a quick reference.
This command worked a treat on the local machine, so now it was just a matter of getting it to run remotely.
psexec –u –p \\ certutil -f –p –importpfx
-u: remote server username.
-p: remote server user password.
I used the psexec command and stored the pfx file in location accessible to all servers (a unc path).
Now all I needed to was to loop through all the servers, I did this by setting up a file with all the servers listed in it. Then created two batch files one to loop through the server list and pass each server to the second batch file which contained the psexec statement above.
BatchFile1
FOR /F "tokens=1 delims= " %%G IN (.\serverlist.txt) DO batchFile2.bat %%G
This command loops through the serverlist.txt file, %%G will be the servername retrieved from the serverlist.txt file and then passed to the batchfile2.bat
BatchFile2
psexec –u –p  \\%1 certutil -f –p –importpfx
This command takes the first parameter passed to the file (%1, the servername) and runs it via psexec on the server.
p.s
Windows2000, I found that the certutil for windows2000 moaned about the –p parameter. I got round that by copying the following files from a windows 2003 server to a temporary location on the windows 2000 servers. the call to the certutil then had to be the full path (it couldnot rely on the system path).
certreq.exe, certutil.exe, certcli.dll, certadm.dll
psexec –u –p  \\%1 c:\templocation\certutil -f –p –importpfx
Browser Name:
Browser Version:
Browser Code Name:
User-Agent: