I know this is probably a petty or odd request. Sometimes I'd run into trouble when remoting in my VMs for some reasons, and I'd have to destroy and create a new one. They'd become non-responsive, even when I rebooted through the LA portal. This happened a couple of times already. Not sure why it went wacky originally. I had pubkey authentication set up and disabled password authentication. However, I'm tired of doing this manually every time. AWS, DigitialOcean, and other VPS providers make this process easier. Although, I do understand the main purpose of LinuxAcademy VMs as they're solely meant to be beaten to death as we lab on it.
If you insist that I'm overthinking it, and I should just leave the VM alone at its default and only spin up a new VM when necessary, then I'll leave it at that. Unless, you're just as curious as I'm, I'd like some helps. I tried to come up with a script for this, but it's more trickier as the script would have to do some heavy-lifting with the interactive commands like 'ssh' and 'su' since this must be done before I can even 'ssh-copy-id'.
Here's a rough script I just started this morning, but I'm now struggling with the 'expect' command as I'm trying to circumvent the 'su root' issue as I can't directly remote in root account using SSH. I'd need root privilege to at least move the default account to the 'wheel' group to perform the administrative tasks. I haven't pasted the 'expect' script yet as I'm still struggling with it. This should make a fun thread.
#!/bin/sh
# EXIT CODES HERE:
# 10 = No private or public key files
# 20 = Host is unavailable
# define variables here
private_key="/home/user/privatekey"
public_key="/home/user/publickey.pub"
# check if both public and private file exists
if [ ! -f "$private_key" ] || [ ! -f "$public_key" ]
then
# Exit program if either files aren't found
echo "Either public or public key do not exist"
exit 10
else
# check to see if host is available
ping -c 1 "$1" &>/dev/null
if [ "$?" = 0 ]
then
# attempt to connect to Academy and set up pubkey authentication
sshpass -p default ssh -o StrictHostKeychecking=no user@"$1" mkdir -m 700 .ssh
sshpass -p default scp "$public_key" user@"$1":~/.ssh/authorized_keys
sshpass -p default ssh -v user@"$1" chmod 400 .ssh/authorized_keys
else
echo "Host is not up or available"
exit 20
fi
# Disable password authentication
# STUCK ON THIS PART AS I NEED ROOT PRIVILEGE
fi
EDIT: Forgot to mention the synopsis.
$./script.sh [ip address or hostname]