Skip to content

Instantly share code, notes, and snippets.

@lamyj
Created January 7, 2017 09:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamyj/bde0a418e077857978d4de7b4bdfa5b9 to your computer and use it in GitHub Desktop.
Save lamyj/bde0a418e077857978d4de7b4bdfa5b9 to your computer and use it in GitHub Desktop.
Start gpg-agent on macOS
#!/usr/bin/env python
import os
import re
import subprocess
import sys
def main():
# If necessary, run gpg-agent
if not is_running():
subprocess.check_output(["/usr/local/bin/gpg-agent", "--daemon"])
# Once it is running, parse its environment file
env_file = find_environment_file()
environment = parse_environment_file(env_file)
# Set environment for later processes
for name, value in environment.items():
subprocess.check_call(["launchctl", "setenv", name, value])
def find_environment_file():
config_file = os.path.join(os.path.expanduser("~"), ".gnupg", "gpg-agent.conf")
env_file = None
try:
with open(config_file) as fd:
for line in fd.readlines():
line = line.strip()
match = re.match(r"([^ ]+) ([^ ]+)", line)
if match and match.group(1) == "write-env-file":
env_file = match.group(2)
except IOError as e:
raise Exception("Could not open configuration file: {}".format(e))
if env_file is None:
raise Exception("No environment file defined")
return env_file
def parse_environment_file(environment_file):
environment = {}
try:
with open(environment_file) as fd:
for line in fd.readlines():
line = line.strip()
match = re.match(r"([^=]+)=(.*)", line)
if match:
name, value = match.groups()
environment[name] = value
except IOError as e:
raise Exception("Could not open environment file: {}".format(e))
return environment
def is_running():
env_file = find_environment_file()
environment = parse_environment_file(env_file)
gpg_agent_info = environment.get("GPG_AGENT_INFO", "")
running = True
match = re.match(r"([^:]+):([^:]+):([^:]+)", gpg_agent_info)
if match:
pid = int(match.group(2))
try:
os.kill(pid, 0)
except OSError:
running = False
else:
running = False
return running
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment