Make ssh key github

Make ssh key github

На данный момент, один из самых популярных репозиториев для системы контроля версий GitHub, использует аутентификацию пользователей через открытые SSH-ключи. Это позволяет работать с сервисом без ввода логина и пароля, а также удобно производить контроль доступа к своему репозиторию.

Рассмотрим вариант создания и добавления SSH-ключей к своему GitHub аккаунту.

Подготовка

Для начала скачаем и установим клиент GitHub по ссылке https://git-scm.com

Теперь попробуем клонировать существующий репозиторий c GitHub для понимания одной из самых популярных ошибок, возникающих при начале работы с Git. Для этого откроем установленную консоль Git Bash, нажав правую кнопку мыши и выбрав пункт Git Bash Here.

Не забудем предварительно перейти в подготовленный каталог для удобства экспериментов с Git. В моем случае это будет каталог C:/domains/test.

Введем в консоли Git Bash команду клонирования удаленного репозитория с GitHub:

Именно здесь мы столкнемся с фатальной ошибкой скачивания из-за ограничения доступа к GitHub:

Решим эту проблему созданием публичного ключа для GitHub.

Генерация SSH-ключей для GitHub

  1. Для начала создания ключей введем следующую команду в Git консоль: В данном случае, E-mail будет использован как метка для удобства в дальнейшем использовании.
  2. Далее можно указать путь для сохранения ключей. Или нажать Enter, чтобы установить в место, предлагаемое по умолчанию. В моем случае это будет C:/Users/sbb/.ssh/id_rsa
  3. Теперь Git попросит нас ввести любую ключевую фразу для более надежной защиты вашего пароля. Можно пропустить этот этап просто нажав Enter:

Итак, мы сгенерировали SSH-ключи и теперь перейдем к следующему этапу.

Добавление созданных SSH-ключей в SSH-агент

  1. Сперва убедимся, что SSH-агент включен.
    Введем в консоли Git команду: Это запустит работу агента в фоновом режиме. После ввода этой команды, в консоли должно появиться id запущенного процесса.
    Примерно так:
  2. Добавим SSH-ключ в SSH-агент.
    Если вы хотите использовать уже существующие ключи, вместо только что сгенерированных, тогда нужно заменить id_rsa при вводе команды в консоли именем существующего файла, содержащий приватный ключ.
    В случаем использования только что созданных ключей просто вводим в консоль Git команду: Как результат, должно появиться в консоли следующее:

Следующим шагом будет добавление приватного ключа в GitHub аккаунт.

Добавление нового SSH-ключа в GitHub аккаунт

  1. Первым делом скопируем созданный SSH-ключ в буфер обмена командой: Или можно открыть файл с ключом в любом редакторе и скопировать вручную. Файл находится в директории C:/Users/ВАШЕ_ИМЯ/.ssh/id_rsa.pub
  2. Откроем настройки своего аккаунта на GitHub и перейдем в раздел SSH and GPC keys
  3. Нажмем на кнопку New SSH key
  4. Добавим в поле Title нужное вам название этого ключа, например, My New Key
  5. Вставим из буфера обмена в поле Key наш ключ
  6. И нажмем кнопку Add SSH key

Проверим, что все нами сделано верно, опять введя в консоль Git команду клонирования удаленного репозитория:

Через несколько секунд получим на своем локальном компьютере полную копию нужного нам репозитория.

Таким образом единожды проведя операцию создания публичного SSH-ключа и внеся его в свой профиль на GitHub, мы обеспечим себе удобную и безопасную работу с удаленным репозиторием.

Источник

How to Add SSH Keys to Your GitHub Account

2 Minutes, 31 Seconds to Read

In this tutorial:

GitHub offers a convenient SSH key feature for accessing your repositories on the command line. Instead of using usernames and passwords every time you push to or pull from your repository, you can use your key. In this article we’ll learn how to add SSH keys to your GitHub account.

Why use an SSH key?

Using an SSH key is a convenient and secure way to access your account. It’s convenient because you don’t need to remember a long password. And you can make your actual password so brutally long and secure that no human or bot could guess it. The SSH key works like an actual key that only you possess.

How to Create an SSH Key

In order to use an SSH key with Git, you must first create the key on your computer. If you already have an SSH key, you can skip these steps. In order to check if you have a key, you can run this command:

Follow along with the steps below to create the key and copy its contents. You will need to open your computer’s default terminal application.

  1. Open the terminal app on your computer.
  2. Enter the following command, substituting [email protected] with your email address:
  3. Press Enter to accept the default file location.
  4. Enter a secure passphrase.
  5. Press Enter.
  6. Enter this command to display the contents of your public key:
  7. Copy the contents of your key to your clipboard (we will need it later).

It’s important to remember that the SSH key has two parts: a private key and a public key. As the name suggests, the private key is only for private use. Never ever share your private key with anyone (with exceptions made for your system administrator or other trusted people within your organization). This will be important later.

How to Add an SSH Key to your Github Account

Now we have already seen why you might want to use an SSH key. We also demonstrated how to create an SSH key on your computer.

As mentioned above, we have a private key and a public key. In the steps below you’ll learn how to upload your public key to GitHub.

Читайте также:  Консоль linux как вставить

  1. Log into your GitHub account.
  2. Click your avatar and choose Settings

Источник

arsho / Add SSH Key to Bitbucket OR Github in Ubuntu 16.04.md

Add SSH Key to Bitbucket / Github in Ubuntu 16.04

What does SSH Keys do in Github / Bitbucket?

Set up SSH to reduce the risk of exposing your username and password. Some reasons you might want to use SSH key base authentication:

  • Is more effective if you push and pull from Bitbucket many times a day.
  • Removes the need to enter a password each time you connect.

Url formats of the repository differs from HTTPS to SSH :

  • Operating System : Ubuntu 16.04 LTS (64-bit)

Add SSH Keys in Ubuntu 16.04

The following steps showed the step by step installation guideline.

Set up your default identity

From the terminal, enter ssh-keygen at the command line. The command prompts you for a file to save the key in:

It will create two files; one public key file and one private key file. Both file will have your given name.

Add Key files in local machine

Keep both of the files in

Add the public key to your bitbucket settings

  1. In Bitbucket go to Bitbucket settings>Account settings>SSH keys>Add key
  2. Copy the contents of your public key file using the following command:

N.B.: id_rsa is the name I have given when generating the key files. It might be something else for your case. 3. Copy and paste the public key in the key field in Bitbucket and include proper label. Click Save .

Ensure Bitbucket SSH connects successfully

Return to the terminal window and write:

Give your passphrase which you have given when generating the key files. If your connection is successful then you will get output like following:

Источник

Generating A New SSH Key and Adding It to Github

Sometimes I behave like a crazy weird nerd. The developer instinct has always made me learn new things be it skimming through some random code, a tip or some dev-workflow. There are concepts which I just keep dumping in my brain without trying them. But the only motivation is that if needed I will definitely do it someday.

Each time I clone a GitHub repo I come across the option to clone it via SSH. I had an idea about SSH keys but never came across a situation where I had to generate one and add it to my GitHub account.

Today, I confronted the scenario where I had to connect my GitHub account with an SSH key since my GitHub repo couldn’t be cloned locally. After figuring out the process, I finally did it and thought about writing my experience with you folks.

So, if you’re finding it difficult to create an SSH key and connect it with your GitHub account, then this article is definitely for you.

Let’s start with some basic concepts about SSH keys.

What are SSH Keys?

SSH (Secure Shell), is an encrypted protocol to communicate with servers allowing users to avail several network-services. SSH keys, in turn, provide a secured mechanism against brute force attacks which may occur while logging into a server with a password.

When cloning a GitHub repo, you sometimes come across an error saying:

Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

This calls for the creation of an SSH key. Generating an SSH key results in two long string of characters which includes a public and a private key. The public key is used to unlock any server and then connect it with the client (typically your computer) where the private part of the SSH key resides.

Figuring Out Any Existing SSH Keys

Before you generate an SSH key, you must check if you have any existing SSH keys stored in your computer. To do so, open your terminal, type the following command and hit Enter.

It displays a list of files in your .ssh directory. Go through this list to find the existence of any public SSH keys. By default, public keys are stored with the .pub file extension.

Normally, public keys appear against the following names:

If there aren’t any public keys, it’s time to create a new SSh key which I will teach shortly. On the contrary, if you find an existing public/private key pair (e.g., id_rsa.pub and id_rsa ), you can use it to add to the GitHub account and get started.

I checked for the presence of SSH keys and here’s the GIF:

Generating a New SSH Key

In case, no public key exists or you want to create a new key for your GitHub, type the following command in the terminal and hit Enter.

The process of key generation will start. It asks for the file in which to save the key with other related info. Fill these details. However, you can leave it empty, and it’ll generate your first key with the default name as id_rsa.pub . Remember I didn’t change any defualts here and just pressed enter or return key for all options like password and key path.

Copying the SSH Key

Now it’s time to copy the contents of the SSH key and add to the GitHub account. Type the following:

The SSH key appears as follow. Just copy it!

Adding SSH Key to GitHub

Now heading to the final part where I’ll add the SSH key to my GitHub account. In your GitHub Profile open Settings. Go to the section for SSH and GPG Keys. Click the New SSH key button, write a suitable Title, paste the copied Key and hit the Add SSH key button.

🤜 BOOM! Here you go. You have successfully added your first SSH to GitHub. Now the GitHub repo can be easily cloned. Moreover, you also get a confirmatory email to inform you about the addition of this new key. This is to make sure no unauthorized keys get added.

I am uploading the GIF to explain the aforementioned process.

👩‍🏫 Your Turn!

See how simple and easy it is to create an SSH key. You can generate multiple SSH keys and add to your GitHub account. But I’ll recommend you to keep it as less as possible to support simplicity. Now it’s your turn to replicate the process and share your feedback in the comments section below.

Moreover, you can Share on Twitter with the hashtag #GirlDevMinute or reach out to me through my twitter account (@MaedahBatool).

Источник

How to Generate SSH Keys for GitHub

Git and GitHub are essential tools for every developer. They’re widely used in almost every kind of software development project.

There are other Git hosting services like Gitlab and Bitbucket, but GitHub is the most popular choice for developers. You can even edit your profile to seem more attractive to recruiters.

You can use Git and GitHub to organize your projects, collaborate with other developers, and — of course — at Kinsta.

But because Git and GitHub are related yet different tools, you need to update your workflow with each of them constantly.

We recommend using SSH keys for each one of your machines. So, in this tutorial, you’ll learn what they are, some of their advantages, and how to generate and configure GitHub SSH keys.

Let’s get started!

What Are SSH Keys?

Simply put, SSH keys are credentials used for the SSH (Secure Shell) protocol to enable secure access to remote computers over the internet. Usually, that authentication occurs in a command-line environment.

Kinsta spoiled me so bad that I demand that level of service from every provider now. We also try to be at that level with our SaaS tool support.

Suganthan Mohanadasan from @Suganthanmn

This protocol is based on client-server architecture, which means you as the user (or “client”) need to use special software, called an SSH client, to log into a remote server and execute commands. This is basically what you’re doing when authenticating via a terminal to GitHub.

Git push.

But SSH is not only used for GitHub. It’s broadly used by other platforms like Kinsta, Google Cloud, and Amazon Web services to create a secure channel to access their services.

Now, heading into how SSH keys really work, you need to understand the differences between public and private keys.

Public vs Private Keys

Let’s start with the basics.

The SSH protocol uses a technique of cryptography called asymmetric encryption. This term may sound complicated and weird, but nothing could be further from the truth.

Basically, asymmetric encryption is a system that uses a pair of keys, namely public and private keys.

As you may guess, the public key can be shared with anyone. Its main purpose is to encrypt data, converting the message into secret code or ciphertext. This key is usually sent to other systems — for example, servers — to encrypt the data before sending it over the internet.

On the other hand, the private key is the one that you must keep to yourself. It’s used to decrypt the encrypted data with your public key. Without it, it’s impossible to decode your encrypted information.

This method allows you and the server to keep a safe communication channel for transmitting the information.

Here’s what happens in the background when you connect to a server via SSH:

  1. The client sends the public key to the server.
  2. The server asks the client to sign a random message encrypted with the public key using the private key.
  3. The client signs the message and forwards the result to the server.
  4. A secure connection is established between the client and the server.

It’s important to keep your private keys safe and share them with anyone under no circumstances. They’re literally the key to all the information sent to you.

Using SSH Keys With GitHub

Since August 13, 2021, Github no longer accepts password authentication for command-line access. This means now you need to authenticate via a personal access token or use an SSH key (a little bit more convenient).

Here’s what happens when you try to authenticate with your GitHub password over HTTP in a terminal:

GitHub needs your public key to authorize you to edit any of your repos via SSH.

Let’s see how you can generate SSH keys locally.

How to Generate SSH Keys Locally

Now that you understand a little bit about the SSH protocol and the differences between public and private keys, it’s time to set up the secure SSH channel between your machine and your GitHub repos.

Before we move forward, you should already have a GitHub account, and a terminal/command prompt with Git installed in your system. If you’re running Windows, make sure you installed Git bash, which has all the tools you’ll need to follow along with this tutorial built-in.

The OpenSSH client is the most popular open-source software used to connect via SSH. You won’t need to worry about your operating system because it’s installed by default on Linux, macOS, and Windows 10.

You need to fire up a command prompt on Windows or a terminal on Unix-based systems to generate local SSH keys. Usually, you can do this by searching for “terminal”, “cmd”, or “powershell” in your application panel, then clicking the icon that shows up.

Terminal application search.

If you use Linux, most distros have the shortcut Ctrl + Alt + T to open up a terminal.

After doing this, you should have a window similar to the following image.

Terminal application.

Run the following command to generate a local SSH pair of keys:

It’s time to tell you a secret: No one can really remember this command! Most developers have to Google it every time because:

  1. It’s a really long command, with forgettable, random-seeming numbers.
  2. We use it rarely, so it’s not worth it to commit it to memory most of the time.

However, it’s important to understand each command that we introduce into our terminals, so let’s see what each part of this one means.

Sign Up For the Newsletter

Want to know how we increased our traffic over 1000%?

Join 20,000+ others who get our weekly newsletter with insider WordPress tips!

  • ssh-keygen: The command-line tool used for creating a new pair of SSH keys. You can see its flags with ssh-keygen help
  • -t ed25519: The -t flag is used to indicate the algorithm used to create the digital signature of the key pair. If your system supports it, ed25519 is the best algorithm you can use to create SSH key pairs.
  • -C “email”: The -c flag is used to provide a custom comment at the end of the public key, which usually is the email or identification of the creator of the key pair.

After you’ve typed the command into your terminal, you’ll have to enter the file to which you would like to save the keys. By default, it’s located in your home directory, in a hidden folder named “.ssh”, but you can change it to whatever you like.

Then you’ll be asked for a passphrase to add to your key pair. This adds an extra layer of security if, at any time, your device is compromised. It is not obligatory to add a passphrase, but it’s always recommended.

This is what the whole process looks like:

ssh-keygen command.

As you can see, this command generates two files in the directory you selected (commonly

/.ssh): the public key with the .pub extension, and the private one without an extension.

We’ll show you how to add the public key to your GitHub account later.

Add SSH Key to ssh-agent

The ssh-agent program runs in the background, holds your private keys and passphrases safely, and keeps them ready to use by ssh. It’s a great utility that saves you from typing your passphrase every time you want to connect to a server.

Because of this, you’re going to add your new private key to this agent. Here’s how:

    Make sure ssh-agent is running in the background.

If you get a message similar to this if everything is fine. It means the ssh-agent is running under a particular process id (PID).

Add your SSH private key (the one without extension) to the ssh-agent.

Replace kinsta_keys with the name of your SSH key. If this is the first key you’ve created, it should be named “id_algorithm_used,” for instance, id_ed25519.

Add SSH Key to GitHub Account

The final step is to add your public key to your GitHub account. Just follow these instructions:

  1. Copy your SSH public key to your clipboard. You can open the file where it is located with a text editor and copy it, or use the terminal to show its contents.
  2. Log into GitHub ] and go to the upper-right section of the page, click in your profile photo, and select Settings.

GitHub settings.

Then, in profile your settings, click SSH and GPG keys.

SSH and GPG keys.

Click the New SSH key button.

New SSH key button.

Give your new SSH key on GitHub a Title — usually, the device you’ll use that key from. And then paste the key into the Key area.

Add a new SSH key form.

Add your SSH key.

Add SSH key button.

Test SSH Connection With a Repo Push

It’s time to test everything you’ve done so far. You’re going to change, commit, and push to one of your existing repos using SSH to ensure your connection is set up correctly.

All Kinsta hosting plans include 24/7 support from our veteran WordPress developers and engineers. Chat with the same team that backs our Fortune 500 clients. Check out our plans!

For our example, we will modify the simple HTML site we created in our Git for Web Development tutorial.

First, we’ll need to clone the repository into our local machine. We can go to the repo page on GitHub and copy the SSH address it provides.

SSH clone command.

Then, clone the repo using a terminal:

Now, let’s add a simple

tag in the index.html file:

The simple HTML site.

We’re not touching any JavaScript or CSS to keep this edit simple. But if you’re skilled with JavaScript, you might find a place at Kinsta. Check the coding skills you need to be part of the Kinsta team.

After doing this, commit the changes:

And push them into GitHub just as you’d normally do.

If everything went fine, congratulations! You just set up an SSH connection between your machine and GitHub.

Manage Multiple SSH Keys for Different GitHub Accounts

If you have multiple GitHub accounts — let’s say one for your personal projects and one for your work — it’s difficult to use SSH for both of them. You would normally need separate machines to authenticate to different GitHub accounts.

But this can be solved easily by configuring the SSH config file.

Let’s get into it.

  1. Create another SSH key pair, and add it to your other GitHub account. Keep in mind the name of the file you’re assigning the new key to.
  2. Create the SSH config file. The config file tells the ssh program how it should behave. By default, the config file may not exist, so create it inside the .ssh/ folder:
  3. Modify the SSH config file. Open the config file and paste the code below:

Now, every time you need to authenticate via SSH using your work or secondary account, you tweak a bit the repo SSH address, from:

Summary

Congratulations — you’ve learned most of the practical knowledge you need to connect to GitHub via SSH!

This tutorial discussed the need for the SSH protocol, the differences between public and private keys, how to generate keys, add them to GitHub, and even manage multiple SSH keys for different GitHub accounts. Keep in mind that unless you want to lose access to everything, your private key needs to stay that way: private.

With this knowledge, now you’re ready to develop a flawless workflow with Git and GitHub. Keep coding!

Save time, costs and maximize site performance with:

  • Instant help from WordPress hosting experts, 24/7.
  • Cloudflare Enterprise integration.
  • Global audience reach with 35 data centers worldwide.
  • Optimization with our built-in Application Performance Monitoring.

All of that and much more, in one plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to find the plan that’s right for you.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector