dotfiles/stowers/shell-utils/dot-local/bin/devc-ssh

43 lines
1.5 KiB
Bash
Executable file

#!/bin/bash
CONTAINER="docker"
if ! command -v docker &>/dev/null; then
CONTAINER="podman"
fi
if [[ "$#" -lt 1 ]]; then
echo "Usage: $0 <container id>" >&2
exit 1
fi
container_id="$1"; shift
# We expect a devcontainer to run an SSH server on 2222/tcp
# and to have this port exposed. We find the host binding
# to SSH to that container.
if ! ssh_port="$(${CONTAINER} inspect --format '{{ (index (index .NetworkSettings.Ports "2222/tcp") 0).HostPort }}' "${container_id}" 2>/dev/null)"; then
echo "[!] Could not get SSH host port for container '${container_id}'" >&2
exit 1
fi
ignore_hostkey=("-oUserKnownHostsFile=/dev/null" "-oStrictHostKeyChecking=false")
if ! ssh "${ignore_hostkey[@]}" -oPasswordAuthentication=no -p "${ssh_port}" -T dev@localhost 'exit'; then
docker exec -it "${container_id}" /bin/bash -c 'echo "dev:dev" | chpasswd'
echo "[+] Changed password of container user to 'dev'"
if command -v sshpass &>/dev/null; then
sshpass -p"dev" ssh-copy-id -p "${ssh_port}" dev@localhost
elif command -v expect &>/dev/null; then
expect -c "spawn $(which ssh-copy-id) -p ${ssh_port} dev@localhost; interact -o -nobuffer -re .*assword.* return; send \"dev\r\n\"; send -- \"\r\"; expect eof;"
else
echo "[?] Could not find application to automatically copy SSH key."
echo " Please enter the password 'dev' manually below."
ssh-copy-id -p "${ssh_port}" dev@localhost
fi
fi
ssh "${ignore_hostkey[@]}" \
-p "${ssh_port}" \
dev@localhost "$@"