Chapters ▾
-
1. Getting Started
-
1.1
About Version Control -
1.2
A Short History of Git -
1.3
What is Git? -
1.4
The Command Line -
1.5
Installing Git -
1.6
First-Time Git Setup -
1.7
Getting Help -
1.8
Summary
-
1.1
-
2. Git Basics
-
2.1
Getting a Git Repository -
2.2
Recording Changes to the Repository -
2.3
Viewing the Commit History -
2.4
Undoing Things -
2.5
Working with Remotes -
2.6
Tagging -
2.7
Git Aliases -
2.8
Summary
-
2.1
-
3. Git Branching
-
3.1
Branches in a Nutshell -
3.2
Basic Branching and Merging -
3.3
Branch Management -
3.4
Branching Workflows -
3.5
Remote Branches -
3.6
Rebasing -
3.7
Summary
-
3.1
-
4. Git on the Server
-
4.1
The Protocols -
4.2
Getting Git on a Server -
4.3
Generating Your SSH Public Key -
4.4
Setting Up the Server -
4.5
Git Daemon -
4.6
Smart HTTP -
4.7
GitWeb -
4.8
GitLab -
4.9
Third Party Hosted Options -
4.10
Summary
-
4.1
-
5. Distributed Git
-
5.1
Distributed Workflows -
5.2
Contributing to a Project -
5.3
Maintaining a Project -
5.4
Summary
-
5.1
-
6. GitHub
-
6.1
Account Setup and Configuration -
6.2
Contributing to a Project -
6.3
Maintaining a Project -
6.4
Managing an organization -
6.5
Scripting GitHub -
6.6
Summary
-
6.1
-
7. Git Tools
-
7.1
Revision Selection -
7.2
Interactive Staging -
7.3
Stashing and Cleaning -
7.4
Signing Your Work -
7.5
Searching -
7.6
Rewriting History -
7.7
Reset Demystified -
7.8
Advanced Merging -
7.9
Rerere -
7.10
Debugging with Git -
7.11
Submodules -
7.12
Bundling -
7.13
Replace -
7.14
Credential Storage -
7.15
Summary
-
7.1
-
8. Customizing Git
-
8.1
Git Configuration -
8.2
Git Attributes -
8.3
Git Hooks -
8.4
An Example Git-Enforced Policy -
8.5
Summary
-
8.1
-
9. Git and Other Systems
-
9.1
Git as a Client -
9.2
Migrating to Git -
9.3
Summary
-
9.1
-
10. Git Internals
-
10.1
Plumbing and Porcelain -
10.2
Git Objects -
10.3
Git References -
10.4
Packfiles -
10.5
The Refspec -
10.6
Transfer Protocols -
10.7
Maintenance and Data Recovery -
10.8
Environment Variables -
10.9
Summary
-
10.1
-
A1. Appendix A: Git in Other Environments
-
A1.1
Graphical Interfaces -
A1.2
Git in Visual Studio -
A1.3
Git in Visual Studio Code -
A1.4
Git in IntelliJ / PyCharm / WebStorm / PhpStorm / RubyMine -
A1.5
Git in Sublime Text -
A1.6
Git in Bash -
A1.7
Git in Zsh -
A1.8
Git in PowerShell -
A1.9
Summary
-
A1.1
-
A2. Appendix B: Embedding Git in your Applications
-
A2.1
Command-line Git -
A2.2
Libgit2 -
A2.3
JGit -
A2.4
go-git -
A2.5
Dulwich
-
A2.1
-
A3. Appendix C: Git Commands
-
A3.1
Setup and Config -
A3.2
Getting and Creating Projects -
A3.3
Basic Snapshotting -
A3.4
Branching and Merging -
A3.5
Sharing and Updating Projects -
A3.6
Inspection and Comparison -
A3.7
Debugging -
A3.8
Patching -
A3.9
Email -
A3.10
External Systems -
A3.11
Administration -
A3.12
Plumbing Commands
-
A3.1
2nd Edition
4.3 Git on the Server — Generating Your SSH Public Key
Many Git servers authenticate using SSH public keys.
In order to provide a public key, each user in your system must generate one if they don’t already have one.
This process is similar across all operating systems.
First, you should check to make sure you don’t already have a key.
By default, a user’s SSH keys are stored in that user’s ~/.ssh directory.
You can easily check to see if you have a key already by going to that directory and listing the contents:
$ cd ~/.ssh
$ ls
authorized_keys2 id_dsa known_hosts
config id_dsa.pub
You’re looking for a pair of files named something like id_dsa or id_rsa and a matching file with a .pub extension.
The .pub file is your public key, and the other file is the corresponding private key.
If you don’t have these files (or you don’t even have a .ssh directory), you can create them by running a program called ssh-keygen, which is provided with the SSH package on Linux/macOS systems and comes with Git for Windows:
$ ssh-keygen -o
Generating public/private rsa key pair.
Enter file in which to save the key (/home/schacon/.ssh/id_rsa):
Created directory '/home/schacon/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/schacon/.ssh/id_rsa.
Your public key has been saved in /home/schacon/.ssh/id_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local
First it confirms where you want to save the key (.ssh/id_rsa), and then it asks twice for a passphrase, which you can leave empty if you don’t want to type a password when you use the key.
However, if you do use a password, make sure to add the -o option; it saves the private key in a format that is more resistant to brute-force password cracking than is the default format.
You can also use the ssh-agent tool to prevent having to enter the password each time.
Now, each user that does this has to send their public key to you or whoever is administrating the Git server (assuming you’re using an SSH server setup that requires public keys).
All they have to do is copy the contents of the .pub file and email it.
The public keys look something like this:
$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== schacon@mylaptop.local
Инструменты
Git SSH Windows — пошаговое руководство
Дата размещения статьи 08/12/2019 👁31067
Git SSH Windows — пошаговое руководство
Настроим пошагово Git SSH для Windows 10. Это позволит вам выполнять команды git без ввода пароля от своей учетной записи GitHub.
Порядок действий:
- Генерация ключа SSH.
- Добавление SSH-ключа в ssh-agent.
- Добавление ключа SSH в учетную запись GitHub.
Генерация ключа SSH
Откройте bash/терминал. Добавьте следующий текст, подставив свой адрес электронной почты GitHub.
ssh-keygen -t rsa -b 4096 -C "ваша@почта.com"
Будет создан ключ ssh, используя e-mail в качестве метки.
Когда вам будет предложено «Введите файл, в котором вы хотите сохранить ключ», нажмите Enter. Это установит в местоположение по умолчанию.
Enter a file in which to save the key (/c/Users/you/.ssh/id_rsa):[Press enter]
Далее введите безопасную фразу-пароль дважды или просто нажмите Enter.
Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]
Добавление SSH-ключа в ssh-agent
Чтобы запустить ssh-агент введите следующую команду.
На экране отобразится похожая строка.
Agent pid 31724
Добавим свой закрытый ключ SSH в ssh-agent. Если вы создали свой ключ с другим именем (или добавляете существующий ключ с другим именем), замените в команде id_rsa на имя вашего файла закрытого (приватного) ключа.
Ключ будет успешно добавлен в ssh-агент.
Добавление ключа SSH в учетную запись GitHub
Мы сгенерировали у себя на компьютере закрытый ключ SSH и добавили его в ssh-агент. Теперь нам необходимо добавить SSH ключ в учетную запись GitHub.
Сейчас нам необходимо скопировать SSH ключ в буфер обмена.
Способов есть несколько, но я же вам предлагаю следующее решения для Windows 10: введите команду ниже.
Прямо в терминале вы увидите содержимое необходимого файла с ключем. Скопируйте его в буфер.
Теперь зайдите на вашу страницу GitHub » Settings.
Перейдите во вкладку SSH and GPG keys и нажмите на кнопку New SSH key для добавления SSH ключа в вашу учетную запись GitHub.
В поле Title добавьте заголовок для данного ключа. Например, если вы захотите настроить SSH доступ на нескольких устройствах, то вы будите понимать какой ключ принадлежит какому устройству.
В поле Key добавьте свой ssh-ключ, который вы скопировали в буфер обмена на предыдущем шаге.
Нажмите Add SSH key.
Для подтверждения вам потребуется ввести свой пароль от учетной записи GitHub.
На этом настройка SSH для вашего устройства завершена, теперь вы можете работать с git без ввода пароля от своей учетной записи.
Если вам понравилась данная статья, можете прочитать как настроить моментальную загрузку сайта на хостинг и синхронизацию файлов.
JavaScript: Window Location Checkbox Checked — Проверка Состояния Чекбокса ✔️
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.
- Настройка Gulp Babel
- Микроразметка сайта
- Как перенести сайт WordPress на хостинг
- Настройте показ всего текста во время загрузки веб-шрифтов
- Сниппеты в VS Code
- Не удается проверить так как не задан исполняемый PHP-файл
Уровень сложностиПростой
Время на прочтение4 мин
Количество просмотров97K
Предыдущая статья была посвящена «связке» git + gpg. В этой же речь пойдёт о том, как при помощи протокола ssh удобно и безопасно работать с удалёнными git-репозиториями.
Кто этот ваш ssh?
SSH (Secure SHell) — это сетевой протокол, посредством которого два компьютера могут взаимодействовать и обмениваться данными. Важно, что данные при этом шифруются, поэтому протокол ssh считается безопасным.
С помощью ssh можно подключаться к удаленным серверам, выполнять на них команды, копировать и редактировать файлы.
Пакет openssh входит в большинство дистрибутивов Linux по умолчанию. Если по какой-либо причине он отсутствует в вашей системе, вы можете установить его при помощи вашего пакетного менеджера.
Доступ к удалённым репозиториям
Зачем?
С 13 августа 2021 года GitHub убрал возможность использовать личный пароль для получения доступа к репозиториям по https из терминала. Вместо пароля от аккаунта на github.com при выполнении команд git clone, git fetch, git pull, или git push теперь необходимо указывать персональный токен доступа. Такое решение было принято с целью защиты пользователей и предотвращения использования злоумышленниками похищенных или взломанных паролей.
На мой взгляд, доступ к удалённым репозиториям по https (не важно — по паролю или по токену доступа) проигрывает в удобстве и гибкости доступу по ssh. При этом настройка подключения по ssh займёт у вас совсем немного времени — возможно, даже меньше, чем уйдёт на то, чтобы разобраться с токенами в GitHub. Именно поэтому я перешёл на использование ssh для всех удалённых репозиториев (расположенных не только на GitHub) даже раньше, чем GitHub перешёл на использование токенов вместо паролей.
Как?
Теперь рассмотрим конкретные шаги, которые необходимо выполнить, чтобы настроить работу с удалёнными репозиториями при помощи ssh. Я буду показывать все действия в терминале Linux.
Получаем ssh-ключи
Если у вас уже имеется пара ключей, которые вы хотите использовать для доступа к удалённым репозиториям, убедитесь, что файл с приватным ключом имеет права доступа rw------- и при необходимости установите их командой:
chmod 600 ~/.ssh/personal_key
Если у вас ещё нет пары ssh-ключей (приватного и публичного), их необходимо сгенерировать при помощи утилиты ssh-keygen.
ssh-keygen -t ed25519
Через флаг -t задаём алгоритм, на основе которого будут сгенерированы ключи. GitHub, GitLab и Yandex рекомендуют использовать ed25519.
Название файла, в который будет сохранён ключ, можно оставить дефолтным.
Далее по желанию можно задать пароль на генерируемый ключ. Если вы сделаете это, ssh будет требовать его при каждом использовании ключа. Чтобы не вводить пароль каждый раз, можно немного настроить ssh-agent — менеджер ключей для ssh.
После чего в терминал будет выведено «изображение» вашего ключа из ASCII-символов (красивое), а в папке ~/.ssh/ появятся два файла: id_ed25519 и id_ed25519.pub с приватным и публичным ключами соответственно. Для удобства работы эти файлы можно переименовать:
mv ~/.ssh/id_ed25519 ~/.ssh/personal_key
mv ~/.ssh/id_ed25519.pub ~/.ssh/personal_key.pub
Настраиваем ssh config
Чтобы ssh мог автоматически использовать правильные ключи при работе с удалёнными репозиториями, необходимо задать некоторые настройки. А именно — добавить в файл ~/.ssh/config следующие строки:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/personal_key
IdentitiesOnly yes
где:
-
gihub.com— url сервиса, с которым будем работать (указываем одинаковым вHostиHostName). -
~/.ssh/personal_key— путь до файла с приватным ключом, который необходимо использовать для подключения.
Очевидно, аналогичные настройки можно произвести не только для GitHub’a, но и для иных сервисов (например, GitLab’a), добавив соответствующие строки в файл конфигурации.
Указываем публичный ключ на GitHub
Для того чтобы GitHub (или иной сервис) мог авторизовать ваше подключение, необходимо указать в настройках аккаунта публичный ssh-ключ, который вы будете использовать для доступа к репозиториям (также можно указать несколько ключей).
На github.com эта процедура делается следующим образом:
-
Переходим в «Settings» -> «SSH and GPG keys» (прямая ссылка).
-
Нажимаем «New SSH key».
-
В поле «Key» вставляем содержимое файла
personal_key.pub(либоid_ed25519.pub, если вы не переименовывали файлы). -
Нажимаем «Add SSH key».
Во всех остальных сервисах действия будут аналогичными.
При первом подключении по ssh необходимо будет добавить github.com (либо адрес того сервиса, который вы используете) в список доверенных хостов:
The authenticity of host 'github.com (140.82.121.4)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com' (RSA) to the list of known hosts.
Everything up-to-date
Готово! Теперь вы можете использовать ssh для доступа к удалённым репозиторям.
Имейте в виду, что при использовании протокола ssh пути до ваших удалённых репозиториев будет отличаться от путей, которые соответствовали протоколу https. Чтобы склонировать репозиторий с GitHub по ssh, вам нужно будет выбрать вкладку «ssh» в меню клонирования репозитория, после чего использовать указанный путь аналогично обычному «https-пути» (например, указать в качестве аргумента команды git clone).
Как сменить адрес удалённого репозитория
Если у вас уже есть репозиторий, синхронизация которого с удалённым сервером происходила по протоколу https, а теперь вы хотите использовать ssh, вам необходимо будет сменить адрес удалённого репозитория, выполнив следующую команду в локальном репозитории:
git remote set-url origin git@serviceurl:username/reponame.git
где:
-
serviceurl— url сервиса, на котором находится удалённый репозиторий (например,github.comилиgitlab.com). -
username— ник владельца репозитория. -
reponame— название репозитория.
Проверить, что изменения прошли корректно, можно путём выполнения команды
git remote -v
в локальном репозитории. Если в выводе содержатся строки вида:
origin git@serviceurl:username/reponame.git (fetch)
origin git@serviceurl:username/reponame.git (push)
с путями до вашего удалённого репозитория, значит, всё сделано правильно.
Полезные ссылки
-
Видео «Как правильно настроить SSH для GitHub / GitLab»
-
Статья «Как работать с несколькими GitHub-аккаунтами на своей локальной машине»
-
Статья «Как эффективно работать с несколькими SSH-ключами»
-
Статья «Протокол SSH и авторизация с помощью ключей»
-
GitHub docs: «Connecting to GitHub with SSH»
Выводы
Используйте протокол ssh для доступа к удалённым git-репозиториям. Это безопасно и удобно!
How to create an SSH Key
SSH keys are generated through a public key cryptographic algorithm, the most common being RSA or DSA. At a very high level SSH keys are generated through a mathematical formula that takes 2 prime numbers and a random seed variable to output the public and private key. This is a one-way formula that ensures the public key can be derived from the private key but the private key cannot be derived from the public key.
SSH keys are created using a key generation tool. The SSH command line tool suite includes a keygen tool. Most git hosting providers offer guides on how to create an SSH Key.
Generate an SSH Key on Mac and Linux
Both OsX and Linux operating systems have comprehensive modern terminal applications that ship with the SSH suite installed. The process for creating an SSH key is the same between them.
1. execute the following to begin the key creation
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This command will create a new SSH key using the email as a label
2. You will then be prompted to «Enter a file in which to save the key.»
You can specify a file location or press “Enter” to accept the default file location.
> Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]
3. The next prompt will ask for a secure passphrase. A passphrase will add an additional layer of security to the SSH and will be required anytime the SSH key is used. If someone gains access to the computer that private keys are stored on, they could also gain access to any system that uses that key. Adding a passphrase to keys will prevent this scenario.
> Enter passphrase (empty for no passphrase): [Type a passphrase]
> Enter same passphrase again: [Type passphrase again]
At this point, a new SSH key will have been generated at the previously specified file path.
4. Add the new SSH key to the ssh-agent
The ssh-agent is another program that is part of the SSH toolsuite. The ssh-agent is responsible for holding private keys. Think of it like a keychain. In addition to holding private keys it also brokers requests to sign SSH requests with the private keys so that private keys are never passed around unsecurly.
Before adding the new SSH key to the ssh-agent first ensure the ssh-agent is running by executing:
$ eval "$(ssh-agent -s)"
> Agent pid 59566
Once the ssh-agent is running the following command will add the new SSH key to the local SSH agent.
ssh-add -K /Users/you/.ssh/id_rsa
The new SSH key is now registered and ready to use!
Generate an SSH Key on Windows
Windows environments do not have a standard default unix shell. External shell programs will need to be installed for to have a complete keygen experience. The most straight forward option is to utilize Git Bash. Once Git Bash is installed the same steps for Linux and Mac can be followed within the Git Bash shell.
Windows Linux Subsystem
Modern windows environments offer a windows linux subsystem. The windows linux subsystem offers a full linux shell within a traditional windows environment. If a linux subsystem is available the same steps previously discussed for Linux and Mac can be followed with in the windows linux subsystem.
Summary
SSH keys are used to authenticate secure connections. Following this guide, you will be able to create and start using an SSH key. Git is capable of using SSH keys instead of traditional password authentication when pushing or pulling to remote repositories. Modern hosted git solutions like Bitbucket support SSH key authentication.
Share this article
OpenSSH, the open source version of the Secure Socket Shell (SSH) tools, is a standard part of the Windows 10 and Windows Server 2019 operating systems. This greatly simplifies how to connect to GitHub with SSH on Windows.
Step-by-step Windows GitHub SSH example
To connect to GitHub with SSH from Windows, follow these steps:
- Open PowerShell
- Run the ssh-keygen command to create SSH keys
- Copy the value of the SSH public key
- Save the public key in your GitHub account settings
- Perform a Git clone operation using your repo’s SSH URL
Create SSH Keys for GitHub
To start, store a public SSH key on GitHub. This is validated against a locally stored private key that Git uses to validate and establish a connection. GitHub SSH keys are created with the ssh-keygen tool that comes prepackaged with updated versions of Windows.
In Windows PowerShell, issue the following ssh-keygen command to create GitHub SSH keys:
PS C:\github\ssh\example> ssh-keygen -o -t rsa -C "[email protected]"
You will be asked for an optional passphrase. It’s permissible to click enter and leave this blank.
| ssh-keygen flags | Purpose | Suggested |
|---|---|---|
| -C | Comments or metadata to add to the public key | Email address |
| -t | The type of GitHub SSH key to create | RSA |
| -o | Use the newest OpenSSH format | Leave blank |
You will also be asked for a location to save the GitHub SSH keys on Windows. Again, just click enter to accept the default location, which is the .ssh folder under the user’s home directory.
| Git and SSH tutorials |
|---|
|
Need to setup SSH for GitHub, GitLab, or CodeDeploy? These SSH Key tutorials will help:
These quick tutorials will get you working with Git and the secure shell in no time. |
The Windows GitHub SSH keys live in the .ssh folder under the current user’s home directory. The following directory listing under the .ssh folder of a user named Cameron shows the two files created by the ssh-keygen tool:
PS C:\Users\Cameron\.ssh> dir LastWriteTime Name ------------- ---- 1/1/2022 id_rsa 1/1/2022 id_rsa.pub
GitHub SSH config
Open the SSH public key in a text editor such as Notepad++, perform a Select All, and copy the key.
Copy the public GitHub SSH key and store this value as a registered SSH key in your GitHub account.
With the SSH key copied, log into GitHub, navigate to your account settings, and paste the public key as a new SSH key.
To obtain a secure, GitHub SSH Windows connection, you must register the public key in your online account settings.
SSH to GitHub on Windows
With the SSH keys generated, and the public key registered in your GitHub account, you can now use Git to connect to GitHub over SSH on Windows.
Simply copy the SSH URL from the GitHub page of the repository you wish to clone, and then provide that SSH link to the Git clone command:
PS C:\github\ssh\example> git clone [email protected]:cameronmcnz/java-jakarta-ee.git Cloning GitHub SSH Windows into ‘java-jakarta-ee’… Host authenticity cannot be established. Do you still want to connect(yes or no)? yes Receiving objects: 100% (55/55),5.78 MiB | 1.32 MiB/s, Windows GitHub SSH done. Resolving deltas: 100% (66/66), Windows GitHub SSH done.
Notice the initial git clone with GitHub SSH on Windows complains about being unable to establish the host authenticity. That warning message is expected. Just type yes and allow the GitHub SSH clone operation to continue.
Once the remote repository is cloned, you can continue to use Git as you normally would, issue commits, add submodules, rebase branches and push back and forth with GitHub. All operations that use the network will automatically use an SSH connection.
And that’s how easy it is to connect to GitHub over SSH on Windows based machines.
