Skip to content

Instantly share code, notes, and snippets.

@plivox
Last active March 30, 2017 17:10
Show Gist options
  • Save plivox/31d83c254f1f1f492d3128cdd0dde003 to your computer and use it in GitHub Desktop.
Save plivox/31d83c254f1f1f492d3128cdd0dde003 to your computer and use it in GitHub Desktop.
Bash profile file for "GIT for Windows" to run ssh-agent automatically and use Windows Credential Manager.
#
# Description: Bash profile file for "GIT for Windows" to run ssh-agent
# automatically and use Windows Credential Manager.
# Author: Vincent Lauria <[email protected]>
# Data: 20170330
# Version: 0.2
#
# Dependency:
#
# - GIT for Windows
# - Powershell and CredentialManager packages
#
# Usage example:
#
# 1. Run Powershell as Administrator:
# PS > Install-Module CredentialManager -force
# PS > exit
#
# 2. Run Git Bash for Windows and copy this script:
# cp git-for-windows-bash-profile ~/.profile
# source ~/.profile
#
# SSH ask password
if [ "$#" -eq 1 ]; then
exec cat
exit 1
fi
SSH_AGENT_ENV=$HOME/.ssh_agent_env
function get_credential
{
powershell.exe -ExecutionPolicy RemoteSigned \
-Command "Get-StoredCredential -Target $1 -AsCredentialObject | % {\$_.Password}"
}
function set_credential
{
local PASSWORD
while true; do
read -s -p "Enter password for key '$1': " PASSWORD
if ssh_add "$PASSWORD" "$1"; then
powershell.exe -ExecutionPolicy RemoteSigned \
-Command "New-StoredCredential -Target $1 -Persist LocalMachine -Username \$ENV:Username -Pass '$PASSWORD'"
break
else
echo
fi
done
}
function ssh_has_identity
{
local IDENTITY=$(echo $1 | sed 's/.*\/.ssh/.ssh/')
if [[ $(ssh-add -l | grep "$IDENTITY") == "" ]]; then
return 1
else
return 0
fi
}
function ssh_add
{
echo "$1" | SSH_ASKPASS="$HOME/.profile" ssh-add "$2" 2> /dev/null
if ! ssh_has_identity "$2"; then
return 1
fi
}
if [[ $(ps ax | grep -c ssh-agent) = "0" ]]; then
eval $(ssh-agent -s) > /dev/null
# Save ssh agent environment variables
cat <<-EOL > ${SSH_AGENT_ENV}
export SSH_AGENT_PID=$SSH_AGENT_PID
export SSH_AUTH_SOCK=$SSH_AUTH_SOCK
EOL
else
. ${SSH_AGENT_ENV}
fi
for FILE in $(find $HOME/.ssh -maxdepth 1 -type f ! -name '*.pub' -name 'id_*'); do
if ssh_has_identity "$FILE" ; then
continue
fi
CREDENTIAL=$(get_credential "$FILE")
if [[ $CREDENTIAL = "" ]]; then
set_credential "$FILE"
else
if ! ssh_add "$CREDENTIAL" "$FILE"; then
set_credential "$FILE"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment