- 4.3 Git на сервере — Генерация открытого SSH ключа
- Генерация открытого SSH ключа
- Generating a new SSH key and adding it to the ssh-agent
- Help us make these docs great!
- Generating a new SSH key and adding it to the ssh-agent
- Help us make these docs great!
- Using Git with SSH keys
- Make sure an SSH client in installed
- Check for existing SSH keys
- Generate a new SSH key pair
- Add the private SSH key to the ssh-agent
- Add the public SSH key to your account
- GitHub
- GitLab
- Bitbucket
- Test connecting via SSH
- GitHub
- GitLab
- Bitbucket
- Clone a repository using SSH
- GitHub
- GitLab
- Bitbucket
- Reconfigure existing repositories to use SSH
- References
- Did you like it? What about sharing?
- Comments
- About
- Donate
4.3 Git на сервере — Генерация открытого SSH ключа
Генерация открытого SSH ключа
Как отмечалось ранее, многие Git-серверы используют аутентификацию по открытым SSH-ключам. Для того чтобы предоставить открытый ключ, каждый пользователь в системе должен его сгенерировать, если только этого уже не было сделано ранее. Этот процесс аналогичен во всех операционных системах. Сначала вам стоит убедиться, что у вас ещё нет ключа. По умолчанию пользовательские SSH ключи сохраняются в каталоге
/.ssh домашнем каталоге пользователя. Вы можете легко проверить наличие ключа перейдя в этот каталог и посмотрев его содержимое:
Ищите файл с именем id_dsa или id_rsa и соответствующий ему файл с расширением .pub . Файл с расширением .pub — это ваш открытый ключ, а второй файл — ваш приватный ключ. Если указанные файлы у вас отсутствуют (или даже нет каталога .ssh ), вы можете создать их используя программу ssh-keygen , которая входит в состав пакета SSH в системах Linux/Mac, а для Windows поставляется вместе с Git:
Сначала программа попросит указать расположение файла для сохранения ключа ( .ssh/id_rsa ), затем дважды ввести пароль для шифрования. Если вы не хотите вводить пароль каждый раз при использовании ключа, то можете оставить его пустым или использовать программу ssh-agent . Если вы решили использовать пароль для приватного ключа, то настоятельно рекомендуется использовать опцию -o , которая позволяет сохранить ключ в формате, более устойчивом ко взлому методом подбора, чем стандартный формат.
Теперь каждый пользователь должен отправить свой открытый ключ вам или тому, кто администрирует Git-сервер (подразумевается, что ваш SSH-сервер уже настроен на работу с открытыми ключами). Для этого достаточно скопировать содержимое файла с расширением .pub и отправить его по электронной почте. Открытый ключ выглядит примерно так:
Источник
Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key generation
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
If you don’t want to reenter your passphrase every time you use your SSH key, you can add your key to the SSH agent, which manages your SSH keys and remembers your passphrase.
Generating a new SSH key
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
This creates a new SSH key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key,» press Enter. This accepts the default file location.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
First, check to see if your
/.ssh/config file exists in the default location.
If the file doesn’t exist, create the file.
/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.
Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
Note: If you see an error like this
add an additional config line to your Host * section:
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
Ensure the ssh-agent is running. You can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
Insert your hardware security key into your computer.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error invalid format or feature not supported, you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.
When you are prompted, touch the button on your hardware security key.
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
When you are prompted to type a passphrase, press Enter.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Источник
Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key generation
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
If you don’t want to reenter your passphrase every time you use your SSH key, you can add your key to the SSH agent, which manages your SSH keys and remembers your passphrase.
Generating a new SSH key
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
This creates a new SSH key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key,» press Enter. This accepts the default file location.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
First, check to see if your
/.ssh/config file exists in the default location.
If the file doesn’t exist, create the file.
/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.
Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
Note: If you see an error like this
add an additional config line to your Host * section:
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Note: The -K option is Apple’s standard version of ssh-add , which stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.
If you don’t have Apple’s standard version installed, you may receive an error. For more information on resolving this error, see «Error: ssh-add: illegal option — K.»
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
Ensure the ssh-agent is running. You can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
Insert your hardware security key into your computer.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error invalid format or feature not supported, you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.
When you are prompted, touch the button on your hardware security key.
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
When you are prompted to type a passphrase, press Enter.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Help us make these docs great!
All GitHub docs are open source. See something that’s wrong or unclear? Submit a pull request.
Источник
Using Git with SSH keys
Have you seen the ad that should be here?
Today’s post is for developers. If you use the Git version control system with a service such as GitHub, GitLab or Bitbucket to host and manage your projects source codes, you know that by default Git connects to remotes using the HTTPS protocol, which requires you to enter username and password every time you run a command such as git pull or git push .
Using the SSH protocol, you can connect and authenticate to servers to use their services. The three mentioned services allow Git to connect via SSH instead of HTTPS. Connecting with public key encryption dispenses typing username and password for every Git command.
You are going to see in this post how to use GitHub, GitLab and Bitbucket with SSH.
Make sure an SSH client in installed
In order to connect using the SSH protocol, an SSH client must be installed on your system. If you use openSUSE, it should be already installed by default.
Just to make sure, open the terminal and run:
That command should output the version number of the SSH client being used:
In case the system informs that the ssh command was not found, you can install the OpenSSH client running:
Check for existing SSH keys
To connect using the SSH protocol, you need an SSH key pair (one private and the other public). If you have never used SSH, you can safely skip this topic and move on to the next. If you have ever used SSH (for instance, to remotely access a server), probably you already have an SSH key pair, in which case you don’t need to generate a new key pair.
To see if existing SSH keys are present, run:
That command should list the contents of the
/.ssh folder, in which the SSH client stores its configuration files:
If you receive an error that there is no
/.ssh directory or there are no files in it, don’t worry: it means you haven’t created an SSH key pair yet. If that is the case, proceed to the next topic.
By default, public SSH keys are named:
/.ssh folder, I have an SSH key pair ( id_rsa.pub is the public key and id_rsa is the private key) created a year ago ( Jul 18 2018 ).
For security reasons, it is recommended that you generate a new SSH key pair at least once a year. If you already have an SSH key pair that was created more than a year ago, it is recommended that you proceed to the next topic.
If you already have an SSH key pair and want to reuse it, you can skip the next topic.
Generate a new SSH key pair
To generate a new SSH key pair, run the following command (replace your_email@example.com with your email address):
It asks you where to save the private key ( id_rsa ).
Press Enter to accept the default location.
If you already have a private key, it asks whether it should overwrite:
If that happens, type y and press Enter.
Then, enter and re-enter a passphrase (think of it as a kind of password):
The SSH key pair is created in
The whole interaction should look similar to the following:
Add the private SSH key to the ssh-agent
If you don’t want to type your passphrase each time you use your SSH keys, you need to add it to the ssh-agent, which is a program that runs in background while you are logged in to the system and stores your keys in memory.
To start the ssh-agent in background, run the following:
That command outputs the ssh-agent process identifier:
Then, add your SSH private key to the ssh-agent:
Type your passphrase and press Enter:
The command confirms that the private SSH key has been added to the ssh-agent:
Add the public SSH key to your account
Once you have an SSH key and have added it to the ssh-agent, you can set up connecting via SSH. Let’s see how to do that for each of the three servers: GitHub, GitLab and Bitbucket.
In all the three cases, the process is similar. Start by copying your public SSH key (
/.ssh/id_rsa.pub ) file contents to the clipboard using the xclip command:
xclip is a command line utility that allows access to the graphical interface clipboard from the terminal. If it is not installed, you can install it running:
GitHub
Using a browser, go to the GitHub home page at github.com and sign in to your account.
In the upper-right corner of the page, click your profile photo, then click Settings:
In the user settings sidebar, click SSH and GPG keys. Then click New SSH key.
Fill in the Title field with a descriptive label for the new key (for example, the name of your computer) and paste your public key into the Key field. Finally, click Add SSH key:
Now the key appears in the list of SSH keys associated with your account:
GitLab
Using a browser, go to the GitLab home page at gitlab.com and sign in to your account.
In the upper-right corner of the page, click your profile photo, then click Settings:
In the User Settings sidebar, click SSH Keys.
Paste your public key in the Key field. Fill in the Title field with a descriptive label for the new key (for example, the name of your computer). Finally, click Add key:
Now the key appears in the list of SSH keys associated with your account:
Bitbucket
Using a browser, go to the Bitbucket home page at bitbucket.org and log in to your account.
In the lower-left corner of the page, click your profile photo, then click Bitbucket settings:
In the Settings sidebar, in the Security section, click SSH keys. Then, click Add key.
Fill in the Label field with a descriptive label for the new key (for example, the name of your computer) and paste your public key into the Key field. Finally, click Add key:
Now the key appears in the list of SSH keys associated with your account:
Test connecting via SSH
GitHub, GitLab and Bitbucket allow you to test whether SSH connection has been set up correctly before actually using it with Git.
GitHub
After you’ve added your SSH key to your GitHub account, open the terminal and run:
That command attempts an SSH remote access to GitHub.
If that is the first time you connect to GitHub via SSH, the SSH client asks you if it can trust the public key of the GitHub server:
Type yes and press Enter. The SSH client adds GitHub to the list of trusted hosts:
Once added to the list of known hosts, you won’t be asked about GitHub’s public key again.
As this remote access via SSH is provided by GitHub just for testing, not for actual use, the server informs that you have successfully authenticated and terminates the connection:
If you completed the test successfully, now you can use SSH with GitHub.
The whole interaction should look similar to the following:
GitLab
If you have added your SSH key to your GitLab account, the test is very similar:
If you completed the test successfully, now you can use SSH with GitLab.
Bitbucket
If you have added your SSH key to your Bitbucket account, the test is very similar:
If you completed the test successfully, now you can use SSH with Bitbucket.
Clone a repository using SSH
Now that we’ve got our SSH keys set up, let’s see how to clone a Git repository using SSH instead of HTTPS.
GitHub
At GitHub, go to a project’s repository, click Clone or download and copy the URL to clone the repository using SSH:
The URL of a GitHub repository looks like:
Open the terminal and run the git clone command passing the copied URL as argument.
Tip: to paste into the terminal, use Ctrl + Shift + V.
Note that now Git clones the repository without asking for a password:
GitLab
At GitLab, go to a project’s repository, click Clone and copy the URL to clone the repository using SSH:
The URL of a GitLab repository looks like:
Open the terminal and run the git clone command passing the copied URL as argument:
Note that now Git clones the repository without asking for a password.
Bitbucket
At Bitbucket, go to a project’s repository, click Clone and copy the command to clone the repository using SSH:
Note that, differently from GitHub and GitLab that present the URL, Bitbucket presents the entire git clone command, including the URL.
The URL of a Bitbucket repository looks like:
Open the terminal, paste and run the command you copied from Bitbucket:
Note that now Git clones the repository without asking for a password.
Reconfigure existing repositories to use SSH
The repositories we clone from now on using SSH will continue to use SSH for future Git commands such as git pull and git push . But existing local repositories, previously cloned with HTTPS, will continue to use HTTPS, unless we set them up to use SSH.
To do that, open the terminal and change the current directory to a local repository.
List the existing remote repositories and their URLs with:
That command should output something like:
Change your remote repository’s URL with:
Run git remote -v once more to verify that the remote repository’s URL has changed:
Great. That done, Git will use SSH, instead of HTTPS, to synchronize that local repository with its remote equivalent.
References
I hope those tips can be useful to you as they have been to me since I started using Git. If you have any questions or trouble, don’t hesitate to comment! See you!
And always remember: have a lot of fun…
Did you like it? What about sharing?
Comments
About
The Linux Kamarada Project aims to spread and promote Linux as a robust, secure, versatile and easy to use operating system, suitable for everyday use be at home, at work or on the server. The project focuses mainly on distribution and documentation.
Have you seen the ad that should be here?
Donate
You can make a one-time donation quickly with PayPal:
Источник