-
Notifications
You must be signed in to change notification settings - Fork 0
/
newssh-key.sh
executable file
·65 lines (51 loc) · 1.98 KB
/
newssh-key.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/bin/bash
# Create ssh-keys, copy it to new server and create alias for ssh
# Check user
while true; do
read -p "Do you want to create keys for user \"$USER\"? Y/n: " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) echo "Please run me from user who will use the keys. Bye! "; exit;;
* ) break;;
esac
done
read -p "Please, enter server address to connect: " srvaddress
# Check that keyfile with this name doesn't exist
[[ -f "$HOME"/.ssh/$srvaddress ]] && echo "Looks like you already have the $HOME/.ssh/$srvaddress file." && read -p "Please, enter name for the keyfiles: " keyfilename
echo "We will create an alias for it."
read -p "Please, enter the simple name of new server: " alias
# Check that this alias doesn't used in ssh config
if grep -Fxq "Host $alias " "$HOME"/.ssh/config
then
echo "Looks like you already use this alias in $HOME/.ssh/config"
read -p "Please use another simple name: " alias
fi
# Create .ssh directory if doesn't exist
[[ ! -d $HOME/.ssh ]] && echo "You don't have .ssh directory, I'll create it for you." && mkdir "$HOME"/.ssh && chmod 700 "$HOME"/.ssh
# Create new variable keyname from keyfilename or srvaddress (if keyfilename is empty)
[[ -n "$keyfilename" ]] && keyname=$keyfilename || keyname=$srvaddress
echo ""
echo "Let's create a key pair. Password can be blank."
echo ""
ssh-keygen -f "$HOME"/.ssh/"$keyname"
echo ""
echo "Now we will copy the public key to $srvaddress"
echo ""
ssh-copy-id -i "$HOME"/.ssh/"$keyname".pub "$srvaddress"
# If ssh-copy-id exit with error
if [ $? -eq 0 ]; then
echo ""
else
echo "ERROR: I can't send public key to $srvaddress. Try it later by yourself."
echo "Simply add the content of $HOME/.ssh/$keyname.pub to $HOME/.ssh/authorized_keys on your new server"
fi
# Add alias to ssh config
{
echo ""
echo "Host $alias"
echo " HostName $srvaddress"
echo " IdentityFile $HOME/.ssh/$keyname"
echo " User $USER"
} >> "$HOME"/.ssh/config
echo "Done!"
echo "Try \"ssh $alias\""