Script to find Computer Name and use in a search

Vernaf
New Contributor II

Hi All,
I am trying to find a script that can
1. find the Computer Name 2.look for a Certificate in the System keychain based on the Computer name. 3. Export that Certificate to a file I can import later on. I tried "security find-certificate -c" option but that assumes I already knew the name I was searching for.

Thanks,
Frantz Verna

3 REPLIES 3

mm2270
Legendary Contributor III

Getting the computer name in a script is easy enough. Using that to locate a certificate in the System keychain is also not hard. I'm not sure on the exporting though. Looking at the security man page, specifically at the export function, I don't necessarily see an easy way to export just the one certificate. It feels like there should be a way, but it's not very clear, and in fact it may not be allowed from a script (easy enough to do using Keychain Access.app).

Maybe an internet search on "export certificate from keychain Mac script" with yield something useful though.

Vernaf
New Contributor II

OK I'll take a script for finding the computer name and using that to locate a cert in the system keychain if you have one! I've been searching for the single export feature with no luck but I may be able to Import a single certificate from a file.

Thanks.

mm2270
Legendary Contributor III
#!/bin/bash

## Get the computer name
computerName=$(scutil --get ComputerName)

## Search the System keychain for a certificate with a matching name
keychainSearch=$(security find-certificate -c "$computerName" /Library/Keychains/System.keychain)

The above should locate a cert in the System.keychain that matches the name of the computer, if there is one. I'll let you take it from here to see how you want to handle the rest