Skip to content

Instantly share code, notes, and snippets.

@alice1017
Last active May 8, 2018 15:12
Show Gist options
  • Select an option

  • Save alice1017/f8647dc547a837c3c0a50fa842ea0da7 to your computer and use it in GitHub Desktop.

Select an option

Save alice1017/f8647dc547a837c3c0a50fa842ea0da7 to your computer and use it in GitHub Desktop.
(ssh-agent by delegator.py -> ssh-add by os.system -> kill ssh-agent process by os.kill) by Python
#!/usr/bin/env python
# coding: utf-8
import os
import delegator as dg
from signal import SIGKILL
from termcolor import colored
RUN = colored("RUN", "cyan")
SET = colored("SET", "green")
KILL = colored("KILL", "red")
LOG = (lambda flag, msg: "{0} {1}".format(flag, msg))
def isint(obj):
try:
int(obj)
return True
except ValueError:
return False
def ssh_agent():
proc = dg.run("ssh-agent")
print LOG(RUN, "ssh-agent")
envs = proc.out.strip().split("\n")[:-1]
print LOG(SET, "environs")
for environ in envs:
try:
define, export = environ.strip(";").split(";")
except ValueError:
break
key, value = define.split("=")
os.environ[key] = value
colored_key = colored(key, "white")
colored_value = colored(value, "white")
print " {0}='{1}'".format(colored_key, colored_value)
return os.environ.get("SSH_AGENT_PID")
def ssh_add(key):
colored_key = colored(key, "blue")
print LOG(RUN, "ssh-add '{0}'".format(colored_key))
os.system("ssh-add {0}".format(key))
def kill_ssh_agent(pid):
if isint(pid):
os.kill(int(pid), SIGKILL)
print LOG(KILL, "ssh-agent(pid {0})".format(pid))
if __name__ == '__main__':
pid = ssh_agent()
ssh_add("~/.ssh/github")
kill_ssh_agent(pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment