Search code examples
pythonmacoskeychainpkcs#12pyopenssl

Running security import command from Python has different behaviour than command line


I am trying to import a pkcs#12 certificate into OS X Keychain using the following command:

security import filename -k ~/Library/Keychains/login.keychain -P password -f pkcs12

In python I use subprocess like this:

  if os.path.isfile(_file) and platform.system() == 'Darwin':
    keychain = os.path.expanduser('~/Library/Keychains/login.keychain')
    command_line = 'security import {} -k {} -P {} -f pkcs12'.format(_file, keychain, password)
    logger.info('Importing {} into OS X KeyChain.'.format(_file))
    return subprocess.call(shlex.split(command_line))

However I get this error message:

security: SecKeychainItemImport: One or more parameters passed to a function were not valid.

I even tried using shell=True but I then I got the security usage back as if I had passed some wrong argument.

Usage: security [-h] [-i] [-l] [-p prompt] [-q] [-v] [command] [opt ...]
...
...

However, when running it from the command line, the command works as expected:

security import <filename> -k <home>/Library/Keychains/login.keychain -P DTWLDHPYNBWBJB3 -f pkcs12
1 identity imported.
1 certificate imported.

Any idea? Is there a restriction when running security from a non interactive console?

Any python library to achieve the same?

Regards


Solution

  • This was actually due to another problem.

    I was using a tmpfile which was not being flushed or closed.

    While the script was running the function could not find any content on that file.

    Once the script ended, the file (which had 'delete=False') was flushed and for this reason the command line was working no problem.

    Solution was to set bufsize=0 :(