PC et serveurs : SSH, Key Pair creation et setup sur le serveur ou PC remote - commandes shell usuelles - Linux

Creation et installation d'une pair de clé privée et public, pour connexion SSH.

Pour Linux.

Création SSH Key pair

To connect to the remote PC or server, by SSH, without using a user password.

See : "How To Set up SSH Keys on a Linux / Unix System"
Author: Vivek Gite Last updated: January 16, 2025.

https://www.cyberciti.biz/faq/how-to-set-up-ssh-keys-on-linux-unix/

Beaucoup d'infos et de trucs utiles, dans l'article.
Dont :

  • "What are ssh-agent and ssh-add, and how do I use them?"
  • "Disable the password based login on a server"
  • "How to add or replace a passphrase for an existing private key?"

Résumé. Pour installation d'un SSH key, sur un pc ou server distant

Ces commandes sont le minimum usuel à utiliser et appliquer, pour créer la clé SSH sur la machine cliente, et l'envoyer sur le PC ou serveur distant.

Ces commandes sont idempotents (comme lors de l'utilisation de tasks Ansible...).
Même pour la création de la clé, qui pourrait effacer la précédente : Si la clé existe déjà, la création est annulée.
=> à utiliser sans modération... en tout cas, sans craindre d'executer une commande, si les clés SSH sont déjà là sur le client, et le PC ou serveur remote...

Si un fichier de clé existe déjà, la création est annulée, et l'envoie sur le PC ou serveur distant aussi.
Les messages indiquent alors : "ERROR : ..."

Vous pouvez alors, soit supprimer la clé existante, soit contourner les vérifications, et imposer la création de la clé SSH.
Pour cela, récupérez les commandes utiles, avec les variables, mais sans toute la soupe de "if .... else...".

SSH_KEY_FILE_NAME_USER_ID="user-toto"
SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME="myserver.titi.com"
SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL="svr_titi"

SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE="no_passphrase"
OR ... SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE=""

SSH_KEY_FILE_NAME_COMMENT_LABEL_TOUSE=$([ "x${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}" == "x" ] && echo "" || echo "_${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}")
SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE=$([ "x${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}" == "x" ] && echo "" || echo ". With : ${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}.")
SSH_KEY_FILE_NAME_WITHOUT_EXT="id_${SSH_KEY_FILE_NAME_USER_ID}_for_ssh_rsa_key_for_${SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL}${SSH_KEY_FILE_NAME_COMMENT_LABEL_TOUSE}"
echo -e "\n\ncheck : key file name : ${SSH_KEY_FILE_NAME_WITHOUT_EXT} \ncheck : key specific comment : ${SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE} \n\n"

echo -e "\n\nCréation de la clé SSH. \n"

if [ ! -f "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}" ]; then
ssh-keygen -t rsa -b 4096 -f "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}" -C "SSH key for user ${SSH_KEY_FILE_NAME_USER_ID} on ${SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL} remote pc or server. ${SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE}"
echo -e "\n\nKey created : ${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}.\n"
SSH_KEY_NEWLY_CREATED="true"
else
SSH_KEY_NEWLY_CREATED="false"
echo -e "\n\nERROR : Key file yet exists. Use the command with out the 'if' test, to overwrite. \n"
fi

ll ${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}

echo -e "\n\Copie de la clé SSH sur le PC ou serveur distant. \n"

if [ "x${SSH_KEY_NEWLY_CREATED}" = "xtrue" ]; then
ssh-copy-id -i "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}.pub" "${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"
echo -e "\n\nKey sent to : ${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}.\n"
else
echo -e "\n\nERROR : Key file yet exists. It is not a new key file. It is not sent to the remote PC or Server. \n"
fi

Et pour tester :

if [ "x${SSH_KEY_NEWLY_CREATED}" = "xtrue" ]; then
echo -e "\n\nTest with the key.\n"
else
echo -e "\n\nWARN : Key file yet exists. No key has been create. This test will use the former key. \n"
fi
echo "ssh -i ""${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}"" ""${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"" "
echo -e "\nOr : \nssh ""${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}""\n"

Ci-après, les mêmes choses, mais avec explications, variantes, et indications complémentaires.

Init the variables, usefull for easy creation of the SSH Key

Initialisation de variable (nom en "SSH_KEY_") en console Shell, pour faciliter la création et l'envoi des clés SSH.
Cela permet aussi de normaliser les noms et éléments d'informations, pour une clé.
Et de standardiser la création, d'une fois sur l'autre.

SSH_KEY_FILE_NAME_USER_ID="user-toto"
SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME="myserver.titi.com"
SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL="svr_titi"

SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE="no_passphrase"
OR ... SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE=""

Ci-dessous, des commandes qui fabrique les variables complémentaires (dérivées des trois premières).
Vous pouvez copier et coller le bloc de code directement...
Une vérification (check) est présentée à la fin du bloc de commande.

SSH_KEY_FILE_NAME_COMMENT_LABEL_TOUSE=$([ "x${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}" == "x" ] && echo "" || echo "_${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}")
SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE=$([ "x${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}" == "x" ] && echo "" || echo ". With : ${SSH_KEY_FILE_NAME_COMMENT_LABEL_BASE}.")
SSH_KEY_FILE_NAME_WITHOUT_EXT="id_${SSH_KEY_FILE_NAME_USER_ID}_for_ssh_rsa_key_for_${SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL}${SSH_KEY_FILE_NAME_COMMENT_LABEL_TOUSE}"
echo -e "\n\ncheck : key file name : ${SSH_KEY_FILE_NAME_WITHOUT_EXT} \ncheck : key specific comment : ${SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE} \n\n"

Création de la clé SSH

Création de la clé SSH :

if [ ! -f "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}" ]; then
ssh-keygen -t rsa -b 4096 -f "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}" -C "SSH key for user ${SSH_KEY_FILE_NAME_USER_ID} on ${SSH_KEY_FILE_NAME_REMOTE_PC_OR_SVR_LABEL} remote pc or server. ${SSH_KEY_SPECIFIC_COMMENT_LABEL_TOUSE}"
echo -e "\n\nKey created : ${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}.\n"
SSH_KEY_NEWLY_CREATED="true"
else
SSH_KEY_NEWLY_CREATED="false"
echo -e "\n\nERROR : Key file yet exists. Use the command with out the 'if' test, to overwrite. \n"
fi

ll ${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}

Copie de la clé SSH sur le PC ou serveur distant

Utilisation de ssh-copy-id.
S'il existe sur le PC ou serveur client.

if [ "x${SSH_KEY_NEWLY_CREATED}" = "xtrue" ]; then
ssh-copy-id -i "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}.pub" "${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"
echo -e "\n\nKey sent to : ${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}.\n"
else
echo -e "\n\nERROR : Key file yet exists. It is not a new key file. It is not sent to the remote PC or Server. \n"
fi

See the article about :
"copy the public key in remote server as authorized_keys in ~/.ssh/ directory".
And the use of scp.

And if scp does not exist on the client machine, then, copy the file to the remote PC or server, without scp.
With that code (tricky and nice).

## First create .ssh directory on server ##
ssh vivek@server1.cyberciti.biz "umask 077; test -d .ssh || mkdir .ssh"

## cat local id.rsa.pub file and pipe over ssh to append the public key in remote server ##
cat $HOME/.ssh/id_rsa.pub | ssh vivek@server1.cyberciti.biz "cat >> .ssh/authorized_keys"

Test de la clé SSH

Pour tester, utilisez les commandes :

ssh "${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"
ssh "${SSH_KEY_FILE_NAME_USER_ID}@your-server-ip-address"
ssh -i "${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}"${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"

Ou bien, taper cela, pour avoir la commande sans les variables :

if [ "x${SSH_KEY_NEWLY_CREATED}" = "xtrue" ]; then
echo -e "\n\nTest with the key.\n"
else
echo -e "\n\nWARN : Key file yet exists. No key has been create. This test will use the former key. \n"
fi
echo "ssh -i ""${HOME}/.ssh/${SSH_KEY_FILE_NAME_WITHOUT_EXT}"" ""${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}"" "
echo -e "\nOr : \nssh ""${SSH_KEY_FILE_NAME_USER_ID}@${SSH_KEY_REMOTE_PC_OR_SVR_HOST_NAME}""\n"

Ensuite, vous pouvez consulter les informations à propos de ssh-agent, et ssh-add, et comment les utiliser.
Voir dans l'article, le chapitre :
"What are ssh-agent and ssh-add, and how do I use them ?"



Mis-sur-site : 05/04/2025 / Mis-à-jour : 07/04/2025


Creative Commons License  Cette page du site www.Cool-Raoul.com vous est proposée par cool-raoul.com sous la licence Creative Commons Attribution-ShareAlike 4.0 International License.