Created
November 18, 2020 17:03
-
-
Save TerryGeng/f24f07737ea7ff543838dd82bbbba31a to your computer and use it in GitHub Desktop.
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 | |
set -e | |
HELP=" | |
Usage: $0 -h ROUTER_IP -u USER | |
Copy the ssh public key of current logged-in user to a Huawei router. | |
arguments: | |
-h, --host ROUTER_IP the IP address of the router | |
-u, --user USER the user used to log in the router and who the | |
key is saved to | |
" | |
USERNAME="" | |
HOST="" | |
while [[ $# -gt 0 ]]; do | |
case "$1" in | |
-u|--user) | |
USERNAME="$2" | |
shift | |
shift | |
;; | |
-h|--host) | |
HOST="$2" | |
shift | |
shift | |
;; | |
*) | |
echo "$HELP" | |
exit 1 | |
;; | |
esac | |
done | |
if [ -z "$USERNAME" ] || [ -z "$HOST" ]; then | |
echo "$HELP" | |
exit 1 | |
fi | |
format_key () { | |
ssh-keygen -e -m pem -f ~/.ssh/id_rsa.pub | sed '1d;$d' | tr -d '\n' | base64 -d | xxd -c 24 -g 4 -u | sed -e "s/^.*: //" -e "s/.\{25\}$//g" | |
} | |
if ! KEYBLOCK=$(format_key); then | |
echo "Unable to format the public key of current logged in user. Do you really have a public key?" | |
exit 1 | |
fi | |
KEYNAME="$(whoami)-$(hostname)" | |
echo -n "Password: " | |
read -s -e PASSWORD | |
send_each_line () { | |
echo "$1" | sed -e "s/^/send \"/g" -e "s/$/\\\n\"; expect \"]\"/g" | |
} | |
SEND_KEYBLOCK=$(send_each_line "$KEYBLOCK") | |
cmd=$(cat << EOF | |
set timeout 2 | |
spawn ssh -okexAlgorithms=+diffie-hellman-group1-sha1 $USERNAME@$HOST | |
expect { | |
timeout { send_user "\nSSH connection timeouted! Check the IP address.\n"; exit 1 } | |
eof { send_user "\nSSH connection terminated! Check the network connection.\n"; exit 1 } | |
"*>" { send_user "\nThe public key is already added to the router.\n"; exit 1 } | |
"Are you sure*?" { send "yes\n"; exp_continue } | |
"*assword:" { send "$PASSWORD"; send "\r" } | |
} | |
expect { | |
"*assword:" { send_user "Wrong password!\n"; exit 1 } | |
"Permission denied" { exit 1 } | |
"*>" { send "system-view\n" } | |
} | |
expect { | |
"*>" { send_user "Can not enter system view. Check your permission.\n"; exit 1 } | |
"*]" { send "rsa peer-public-key rsakey-$KEYNAME\n" } | |
} | |
expect "*rsa-public-key]" | |
send "public-key-code begin\n" | |
expect "]" | |
$SEND_KEYBLOCK | |
send "public-key-code end\n" | |
expect "]" | |
send "peer-public-key end\n" | |
expect "]" | |
send "ssh user $USERNAME authentication-type all\n" | |
expect "]" | |
send "ssh user $USERNAME assign rsa-key rsakey-$KEYNAME\n" | |
expect "]" | |
send "quit\n" | |
exit | |
EOF | |
) | |
echo "$cmd" | expect | |
echo "\n" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment