Script to Generate/Upload ssh key to remote system

This is script who will generate or upload ssh key to remote system

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/bin/bash
# This was written only for simple usage
#Valentin Hristev
 
### Enter username and IP(or hostname) for REMOTE machine
echo -n "Enter remote username: "
read USR
echo -n "Remote username is set to $USR  "
case $usr in
esac
echo ""
 
echo -n "Enter remote ip/host address: "
read HOST
echo -n "Remote ip/host is set to $HOST  "
case $usr in
esac
 
#echo -n "Default SSH port is 22 if you want to change it please open ssh_gen with your favourite text editor and change "PORT=" PORT_NUMMER"
 
echo -n "Enter PORT: "
read PORT
echo -n "Remote port is $PORT  "
case $usr in
esac
 
echo -n "Your config is :User = $USR  Host = $HOST Port = $PORT "
 
#PORT="22"
NEWKEY="yes"
 
# Generate SSH keys RSA
makekey () {
if [ $NEWKEY == "yes" ]; then
ssh-keygen -t rsa -f ~/.ssh/identity
fi
}
 
# Check for file "authozed_keys" if file is not there create it.
 
checkfile () {
if [ -f ~/.ssh/authorized_keys ]; then
touch ~/.ssh/authorized_keys
fi
}
 
# Check for ".ssh" if dir is not there create it.
upload () {
cat ~/.ssh/identity.pub | ssh -p $PORT $USR@$HOST 'sh -c "if [ ! -d .ssh ] ; then mkdir .ssh ; chmod 700 .ssh ; fi
cat - >>~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"'
echo "Done..................... "
}
 
## Main Menu
press_enter () {
echo ""
echo -n "Press Enter to continue"
read
clear
}
 
selection=
until [ "$selection" = "0" ]; do
echo ""
echo "*******PROGRAM MENU"**********
echo "1 - Generate & Upload New Key"
echo "2 - Upload Old Key"
echo ""
echo "0 - exit "
echo ""
echo -n "Enter choose: "
read selection
echo ""
case $selection in
1 ) checkfile ; makekey ; upload ;;
2 ) upload ;;
0 ) exit ;;
 
    * ) echo "Please enter 1, 2 or 0"; press_enter
 
esac
done
 
exit 0
 
#END

Here is script in action