Last active
August 31, 2024 15:55
-
-
Save emabrey/034c399f087263a6ab6cc860a314a486 to your computer and use it in GitHub Desktop.
WSL SSH Key Copier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#enable nullglob on startup if not enabled | |
shopt -q nullglob || shopt -s nullglob; | |
# Turns the given value into an array and verifies that the array has more than zero elements | |
# to check if the globbed file directory given exists | |
# requires nullglob to be or it will enable/disable during the function execution | |
glob_exists() { | |
shopt -q nullglob || (echo "nullglob must be enabled for glob_exists to work." && return 1); | |
# shellcheck disable=SC2206 | |
#disable warning because we actually want uncontrolled glob expansion for this unusual use case | |
arr=( $1 ) | |
[ ${#arr[@]} != 0 ] | |
} | |
if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then | |
echo "Skipping ssh key copy since this is an SSH session"; | |
else | |
#Setup host user profile variables | |
win_userprofile="$(cmd.exe /c "<nul set /p=%UserProfile%" 2>/dev/null)" | |
#win_userprofile_drive="${win_userprofile%%:*}:" | |
#userprofile_mount="$(findmnt --noheadings --first-only --output TARGET "$win_userprofile_drive")" | |
win_userprofile_dir="${win_userprofile#*:}" | |
#userprofile="${userprofile_mount}${win_userprofile_dir//\\//}" | |
#Copy ssh keys from windows to linux | |
windows_ssh_dir="/mnt/c/$(echo "${win_userprofile_dir:1}" | sed 's/\\/\//g' | sed 's/://')/.ssh"; | |
echo "Copying ssh keys from $windows_ssh_dir"; | |
if [ -d "$windows_ssh_dir" ]; then | |
cp --recursive --update "$windows_ssh_dir" ~; | |
else | |
echo "Unable to copy .ssh directory from Windows to Linux." | |
fi | |
if [ -d "$HOME/.ssh" ]; then | |
chmod 700 ~/.ssh; | |
#By default all files are given restrictive owner only permissions | |
if glob_exists "$HOME/.ssh/*"; then | |
chmod -R 600 ~/.ssh/*; | |
else | |
echo "The .ssh copy succeeded but there were no files in the .ssh folder"; | |
fi | |
#Make a more permissive permission for public keyfiles, if there are any | |
if glob_exists "$HOME/.ssh/*.pub"; then | |
chmod -R 644 ~/.ssh/*.pub; | |
fi | |
#Make a more permissive permission for config files for ssh service | |
if [ -f "$HOME/.ssh/authorized_keys" ]; then | |
chmod 644 ~/.ssh/authorized_keys; | |
fi | |
if [ -f "$HOME/.ssh/known_hosts" ]; then | |
chmod 644 ~/.ssh/known_hosts; | |
fi | |
if [ -f "$HOME/.ssh/config" ]; then | |
chmod 644 ~/.ssh/config; | |
fi | |
else | |
echo "Unable to find .ssh directory for permissions fixes. Perhaps the copy failed?"; | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment