1. 程式人生 > >Set up SSH for Git and Mercurial on Mac OSX/Linux

Set up SSH for Git and Mercurial on Mac OSX/Linux

Up until this point, you have been using the secure hypertext transfer protocol (HTTPS) to communicate between your local system and Bitbucket. When you use HTTPS, you need to authenticate (supply a username and password) each time you take an action that communicates with the Bitbucket server. You can specify the username in the DVCS configuration file; you don't want to store your password there though where anyone can see it. So, this means you must manually type a password when you use HTTPS with  your local repository. Who wants to do that? This page shows you how to use secure shell (SSH) to communicate with the Bitbucket server and avoid having to manually type a password.

Icon

This page shows you how to set up and use a single default SSH identity on either OSX or Ubuntu Linux. If you want set up on Microsoft Windows, we have instructions for Set up SSH for Git and for Set up SSH for Mercurial

Finally, setting up an SSH identity can be prone to error. Allow yourself some time, perhaps as much as an hour depending on your experience, to complete this page. If you run into issues, check out 

Troubleshoot SSH Issues for extra information that may help you along.  You can even skip this whole page and continue to use HTTPS if you want.

Step 1. Read a quick overview of SSH concepts

To use SSH with Bitbucket, you create an SSH identity. An identity consists of a private and a public key which together are a key pair. The private key resides on your local computer and the public you upload to your Bitbucket account. Once you upload a public key to your account, you can use SSH to connect with repositories you own and repositories owned by others, provided those other owners give your account permissions. By setting up SSH between your local system and the Bitbucket server, your system uses the key pair to automate authentication; you won't need to enter your password each time you interact with your Bitbucket repository.

There are a few important concepts you need when working with SSH identities and Bitbucket

  • You cannot reuse an identity's public key across accounts. If you have multiple Bitbucket accounts, you must create multiple identities and upload their corresponding public keys to each individual account. 
  • You can associate multiple identities with a Bitbucket account. You would create multiple identities for the same account if, for example, you access a repository from a work computer and a home computer. You might create multiple identities if you wanted to execute DVCS actions on a repository with a script – the script would use a public key with an empty passphrase allowing it to run without human intervention.
  • RSA (R. Rivest, A. Shamir, L. Adleman are the originators) and digital signature algorithm (DSA) are key encryption algorithms. Bitbucket supports both types of algorithms. You should create identities using whichever encryption method is most comfortable and available to you.

Step 2. Ensure you have an SSH client installed

To use SSH, you need an SSH client on your local system. If you know you have a client installed, skip this section. Otherwise do the following:

  1. Open a terminal on your local system.
  2. Enter the following command to identify which version of SSH you have installed.
    If SSH is installed, you see something similar to the following:

    myhost:~ manthony$ ssh -v
    OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011
    usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
               [-D [bind_address:]port] [-e escape_char] [-F configfile]
               [-I pkcs11] [-i identity_file]
               [-L [bind_address:]port:host:hostport]
               [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
               [-R [bind_address:]port:host:hostport] [-S ctl_path]
               [-W host:port] [-w local_tun[:remote_tun]]
               [[email protected]]hostname [command]
  3. If you have ssh installed, go to the next step. 
    If you don't have ssh installed, install it now.
  4. List the contents of your ~/.ssh directory.
    If you don't have an .ssh directory, don't worry, you'll create it the Step 3 section.  If you have a .ssh directory or you may see something like this:

    myhost:~ manthony$ ls -a ~/.ssh
    known_hosts

    If you have defined a default identity, you'll see the two id_* files:

    myhost:~ manthony$ ls -a ~/.ssh
    .        ..        id_rsa        id_rsa.pub    known_hosts

    In this case, the default identity used RSA encryption (id_rsa.pub). If you want to use an existing default identity for your Bitbucket account, skip the next section and go to enable SSH compression for mercurial.

Step 3. Set up your default identity

By default, the system adds keys for all identities to the /Users/yourname/.ssh directory on Mac OSX, or /home/yourname/.ssh on Linux. This procedure creates a default identity. If you have a default identity and you want to use it for Bitbucket, skip this step and go to step 4.  If you have an existing default identity but you forgot the passphrase, you can also use this procedure to overwrite your default identity and create a fresh one.

Want to Use Multiple Identities?

You can create multiple SSH identities. Doing this is an advanced topic and beyond the scope of this tutorial. For information on how to create multiple identities, see Configure multiple SSH identities for GitBash, Mac OSX, & Linux.

Use the following procedure to create a new default identity.

  1. Open a terminal in your local system.
  2. Enter ssh-keygen at the command line.
    The command prompts you for a file to save the key in. If the .ssh directory doesn't exist, the system creates one for you.
  3. Accept the default location.
  4. Enter and re-enter a passphrase when prompted.
    Unless you need a key for a process such as script, you should always provide a passphrase. The command creates your default identity with its public and private keys. The whole interaction will look similar to the following:

    myhost:~ manthony$ ssh-keygen
    Generating public/private rsa key pair.
    Enter file in which to save the key (/Users/manthony/.ssh/id_rsa): 
    Created directory '/Users/manthony/.ssh'.
    Enter passphrase (empty for no passphrase): 
    Enter same passphrase again: 
    Your identification has been saved in /Users/manthony/.ssh/id_rsa.
    Your public key has been saved in /Users/manthony/.ssh/id_rsa.pub.
    The key fingerprint is:
    4c:80:61:2c:00:3f:9d:dc:08:41:2e:c0:cf:b9:17:69 [email protected]
    The key's randomart image is:
    +--[ RSA 2048]----+
    |*o+ooo.          |
    |.+.=o+ .         |
    |. *.* o .        |
    | . = E o         |
    |    o . S        |
    |   . .           |
    |    .            |
    |                 |
    |                 |
    +-----------------+
  5. List the contents of ~/.ssh to view the key files.

    ls -a ~/.ssh

Step 4. Start the ssh-agent and load your keys

If you are running OSX 10.6.8 or later you can skip this step.  The OSX 10.6.8 system asks for your connection parameters the first time you try to establish a SSH connection.  Then, it automatically starts the ssh-agent for you.  If you don't have OSX 10.6.8 or are running another Linux operating system, do the following:

Open a terminal window and enter the ps -e | grep [s]sh-agent command to see if the agent is running:

myhost:~ manthony$ ps -e  | grep [s]sh-agent
 9060 ??         0:00.28 /usr/bin/ssh-agent -l

If the agent isn't running, start it manually with the following command:

myhost:~ manthony$ ssh-agent /bin/bash

Load your new identity into the ssh-agent management program using the ssh-add command.

$ ssh-add ~/.ssh/id_rsa
Enter passphrase for /Users/manthony/.ssh/id_rsa: 
Identity added: /Users/manthony/.ssh/id_rsa (/Users/manthony/.ssh/id_rsa)
myhost:~ manthony$ 

Use the ssh-add command to list the keys that the agent is managing.

$ ssh-add -l
2048 7a:9c:b2:9c:8e:4e:f4:af:de:70:77:b9:52:fd:44:97 /Users/manthony/.ssh/id_rsa (RSA)

Step 5. Enable SSH compression for Mercurial

When sending or retrieving data using SSH, Git does compression for you. Mercurial does not automatically do compression.  You should enable SSH compression as it can speed up things drastically, in some cases. To enable compression for Mercurial, do the following:

  1. Open a terminal window.
  2. Edit the Mercurial global configuration file (~/.hgrc).
  3. Add the following line to the UI section:

    ssh = ssh -C

    When you are done the file should look similar to the following:

    [ui]
    # Name data to appear in commits
    username = Mary Anthony <[email protected]>
    ssh = ssh -C
  4. Save and close the file.

Step 6. Install the public key on your Bitbucket account

  1. Open a browser and log into Bitbucket.
  2. Choose avatar > Manage Account from the application menu. 
    The system displays the Account settings page.
  3. Click SSH keys.
    The SSH Keys page displays. It shows a list of any existing keys. Then, below that, a dialog for labeling and entering a new key.
  4. Back in your terminal window, copy the contents of your public key file.
    For example, in Linux you can cat the contents.

    cat ~/.ssh/id_rsa.pub

    In Mac OSX the following command copies the output to the clipboard:

    pbcopy < ~/.ssh/id_rsa.pub
  5. Back in your browser, enter a Label for your new key, for example, Default public key.

  6. Paste the copied public key into the SSH Key field:
  7. Press Add key.
    The system adds the key to your account.  Bitbucket sends you an email to confirm addition of the key. 

Step 7. Change your repo from HTTPS to the SSH protocol

The URL you use for a repo depends on which protocol you are using, HTTPS or SSH.  The Bitbucket repository Overview page has a quick way for you to see these URLS for your bb101repo  repo.  On the repo's Overview page look for the Clone button. 

Experiment for a moment, clicking back and forth between the SSH and the HTTPS protocol links to see how the URLs differ.  The table below shows the format for each DVCS based on protocol.

SSH URL format HTTPS URL format
Mercurial ssh://[email protected]/accountname/reponame/

https://accountname@bitbucket.org/accountname/reponame

Git

[email protected]:accountname/reponame.git

or

ssh://[email protected]/accountname/reponame.git

https://accountname@bitbucket.org/accountname/reponame.git

In the SSH format, the accountname appears after [email protected] or [email protected]. In HTTPS format, the accountname before[email protected] or [email protected].

Make the change

Go to a terminal on your local system and navigate to your bb101repo-pratice repo. Then, do the following for Git and Mercurial:

Git users do this:

  1. View your current repo configuration.
    You should see something similar to the following:

    myhost:bb101repo-practice manthony$ cat .git/config
    [core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
        ignorecase = true
    [remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = https://[email protected]/newuserme/bb101repo.git
    [branch "master"]
        remote = origin
        merge = refs/heads/master

    As you can see, the url is using the HTTPS protocol.  There are a number of ways to change this value, the easiest way is just to edit the repo's configuration file.

  2. Edit the ~/repos/bb101repo-pratice/.git/config file with your favorite editor.
  3. Change the url value to use the SSH format for that repo.
    When you are done you should see something similar to the following:

    [remote "origin"]
        fetch = +refs/heads/*:refs/remotes/origin/*
        url = [email protected]:newuserme/bb101repo.git

Mercurial users do this:

  1. View your myquotefork repo configuration.
    You should see something similar to the following:

    myhost:.hg manthony$ cat hgrc
    [paths]
    default = https://bitbucket.org/newuserme/myquotefork
  2. Edit the ~/repos/myquotefork/.hg/hgrc file with your favorite editor.
  3. Change the default value to use the SSH format for that repo.
    When you are done you should see something similar to the following:

    [paths]
    default = ssh://[email protected]/newuserme/myquotefork
  4. Save and close the configuration file.

Step 8. Make a change under the new protocol

  1. Edit the README file in your bb101repo-practice repo.
  2. Add a new line to the file, for example:

    Welcome to My First Repo
    -------------------------------
    This repo is a practice repo I am using to learn bitbucket.
    You can access this repo with SSH or with HTTPS.
  3. Save and close the file.
  4. Add and then commit your change to your local repo.

    git add README
    git commit -m "making a change under the SSH protocol"
  5. Push your changes.
    The system warns  you that it is adding the Bitbucket host to the list of known hosts.

    myhost:bb101repo-practice manthony$ git push 
    Warning: Permanently added the RSA host key for IP address '207.223.240.182' to the list of known hosts.
    Counting objects: 5, done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (2/2), done.
    Writing objects: 100% (3/3), 314 bytes, done.
    Total 3 (delta 1), reused 0 (delta 0)
    remote: bb/acl: newuserme is allowed. accepted payload.
    To [email protected]:newuserme/bb101repo.git
       d3bb337..f0b152f  master -> master
  6. Open the repo Overview in Bitbucket to view your commit.

You are done!

You've completed this tutorial for Bitbucket. At this point, you should have a good beginners knowledge of what you can do in Bitbucket (You should also make sure you have checked https://tutorials.bitbucket.org to see your pull request changes incorporated.)  If you are a Mac user, you might want to see SourceTree a Free Git and Mercurial GUI (Mac OSX). Windows users can try Sourcetree Git GUI on Windows.

The rest of the documentation has more topics and information that can help you make the most of Bitbucket. Please let us know what you thought of this tutorial by logging an issue or by sending an email.  Of course, you can always contribute by commenting on or editing a page directly.

相關推薦

Set up SSH for Git and Mercurial on Mac OSX/Linux

Up until this point, you have been using the secure hypertext transfer protocol (HTTPS) to communicate between your local system and Bitbucket. When you u

Git: set up global user name and email

Git: set up global user name and email [email protected] MINGW64 / $ git config --global user.name "dijk" [email protected] MINGW64

Set Up a Minimal Git Server

Github is well-known and we are enjoying it, but now I will set up a minimal Git server on Ubuntu according to Git on the Server for some reason you h

Set Up a Spark SQL JDBC Connection on Amazon EMR

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

How to set up a Continuous Integration and Delivery (CI/CD) Pipeline

In this project, you will learn how to set up a continuous integration and continuous delivery (CI/CD) pipeline on AWS. A pipeline helps you

Git學習筆記001.Git基本操作 on Mac

1. Git Initialization (1) Make a folder as your local repository. mkdir myRepository (2) Enter the

【轉】Install libimobiledevice on Mac OSX

com app native device blog pre fss command null About the App App name: libimobiledevice App description: Library to communicate with iO

Install plantuml on Mac OSX

About the App App name: plantuml App description: Draw UML diagrams Install the App Press Command+F and type Terminal and press enter

Install ideviceinstaller on Mac OSX

About the App App name: ideviceinstaller App description: Cross-platform library and tools for communicating with iOS devices Install t

Ask HN: I set up my own domain for my email and it's all going to SPAM

Have you implemented DKIM/SPF/DMARC? If you have not, that is a first step.Are you sending from a "consumer" network IP block (cable modem or DSL)? If so,

Set Up and Use EC2 Run Command on EC2 Linux

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

Set Up an HTTP Proxy for Docker and the ECS Agent in Enterprise Linux

docker run --name ecs-agent \ --env=ECS_ENABLE_TASK_IAM_ROLE_NETWORK_HOST=true \ --env=ECS_ENABLE_TASK_IAM_ROLE=true \ --env "NO_PROXY=169.254.1

Mixture of conda2 and conda3 problem and A guidance of environment set-up for windows users

 I write this guidance for windows users. Hopefully, it will be helpful. Download and install miniconda3. py=3.5 and windows Then start Anaconda Pro

Git 出現Branch master set up to track remote branch master問題 與忽略文件上傳

span idea ron details -s 整合 解決 推送 指令 錯誤:在push 到遠程倉庫是一直提示下列錯誤,檢查了使用status檢查了也沒有發現錯誤,最後排查出來是當前分支為((no branch))即右上那個id (┬_┬)。。。。。 原因:

Setting up a EDK II build environment on Windows and Linux:搭建Windows和Linux開發環境[2.2]

set clu cto 無法安裝 urn ems water 了解 源代碼管理 Setting up a EDK II build environment on Windows and Linux:搭建Windows和Linux開發環境[2.2] 2015-07 北

GNS3 0.8.6計算idle pc值時出現Failed to find a working Idle PC value. Can't set up hypervisor on 127.0.0.1等問題

idle 計算 是否 image src bubuko 一個 work find 這學期在學計算機網絡,實驗課要用到gns30.8.6模擬。但是按照老師所給教程在設置idle pc時出現Failed to find a working Idle PC value. Can‘

[Fastai] How to set up fastai library on windows 10? Windows 10如何安裝fastai庫

According to Jeremy’s post: (assume you have gpu with cuda, conda and git installed) clone the git repo git clone https://github.com/

On SDK version 23 and up, your app data will be automatically backed up and restored on app install.

導致這樣的問題是你的menifest檔案中的application 中android:allowBackup=“true”; allowBackup安全風險描述: Android API Level 8及其以上Android系統提供了為應用程式資料的備份和恢復功能,此功能的開關決定於該應

【Benson的專欄】Learning, staying up to date, and working on the latest and greatest in languages and APIs is what k

Learning, staying up to date, and working on the latest and greatest in languages and APIs is what k

Best deals for Oct. 1: Save on Instant Pot, Epson printers, Beats headphones, Echo Show, LEGO, and more

October is here and so are some great sales. We've gathered the best deals on the products you want, including printers, headphones, kitchen gear, video st