From a4dca13893cdb224e89d2c1448e44805529d1876 Mon Sep 17 00:00:00 2001 From: "xiongdian.me" Date: Sat, 21 Jan 2023 15:10:43 +0800 Subject: [PATCH] zshrc: piv-agent now can re-use agents --- .zshrc2 | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/.zshrc2 b/.zshrc2 index b32430e..0a1ab7f 100644 --- a/.zshrc2 +++ b/.zshrc2 @@ -113,21 +113,41 @@ fi gbes() { git for-each-ref --sort=-committerdate refs/heads refs/remotes --format="%(authordate:format:%y-%m-%d.%a %H:%M %z)|%(color:red)%(objectname:short)|%(color:yellow)%(refname:short)%(color:reset)|%(color:reset)%(authorname): %(color:green)%(subject)" --color=always | column -ts"|" | less -FX } piv-agent() { - eval $(ssh-agent -k) + local agent_file="/tmp/piv-agent-$(whoami)" + if [[ -f $agent_file ]]; then + source $agent_file + fi # they are: ubuntu, macos, respectively local SO_PATHS=( "/usr/lib64/opensc-pkcs11.so" "/usr/local/lib/opensc-pkcs11.so" ) - for i in ${SO_PATHS[*]}; do - if [[ -f "$i" ]]; then - echo "using: $i" - eval $(ssh-agent -P "$i") - ssh-add -s "$i" - echo "now available keys:" - ssh-add -l - return 0 + local SO_FILE + for SO_FILE in ${SO_PATHS[*]}; do + if [[ -f "$SO_FILE" ]]; then + break fi done - echo "opensc-pkcs11.so not found" - return 1 + if [[ ! -f "$SO_FILE" ]]; then + echo "error: opensc-pkcs11.so not found" + return 1 + fi + if ! ps -p "$SSH_AGENT_PID" > /dev/null; then + echo "launch agent using: $SO_FILE" + ret=$(ssh-agent -P "$SO_FILE") + echo "$ret" > $agent_file + eval "$ret" + if ! ps -p $SSH_AGENT_PID > /dev/null; then + echo "failed to launch agent" + return 1 + fi + else + echo "using existing agent: $SSH_AGENT_PID" + fi + if ! ssh-add -l > /dev/null; then + echo "no keys found in this agent, let's add some" + ssh-add -s "$SO_FILE" + fi + pgrep ssh-agent | grep -v $SSH_AGENT_PID | xargs kill -9 + echo "now available keys:" + ssh-add -l } # key bindings