1384

I know how to include a username and password in an HTTPS Git URL like this:

git clone https://username:password@host 

But I'd like to know how to provide a username and password to an SSH remote like this:

git clone [email protected] 

I've tried like this:

git clone username:password@[email protected] git clone git@username:[email protected] git clone [email protected]@username:password 

But they haven't worked.

6

19 Answers 19

1997

Based on Michael Scharf's comment:

You can leave out the password, so that it won't be logged in your Bash history file:

git clone https://[email protected]/username/repository.git 

It will prompt you for your password.

Alternatively, you may use:

git clone https://username:[email protected]/username/repository.git 

This way worked for me from a GitHub repository.

Sign up to request clarification or add additional context in comments.

33 Comments

It is not advisable to put the password in the URL for this file is saved on the .git/config . Is not safe, it is better to use ssh key
@MrDuk no problem, escape it (as %40 iirc).
You can leave out the password: git clone https://[email protected]/username/repository.git. git will ask you and it will not be saved in .git/config nor in your bash history
you can also type 'space' at the beginning of the line so that linux won't store the command in history
Another option I like is using and auth token instead of the username to get past any prompts git clone https://<token>@github.com/username/repository.git
|
308

The user@host:path/to/repo format tells Git to use ssh to log in to host with username user. From git help clone:

An alternative scp-like syntax may also be used with the ssh protocol:

[user@]host.xz:path/to/repo.git/

The part before the @ is the username, and the authentication method (password, public key, etc.) is determined by ssh, not Git. Git has no way to pass a password to ssh, because ssh might not even use a password depending on the configuration of the remote server.

Use ssh-agent to avoid typing passwords all the time

If you don't want to type your ssh password all the time, the typical solution is to generate a public/private key pair, put the public key in your ~/.ssh/authorized_keys file on the remote server, and load your private key into ssh-agent. Also see Configuring Git over SSH to login once, GitHub's help page on ssh key passphrases, gitolite's ssh documentation, and Heroku's ssh keys documentation.

Choosing between multiple accounts at GitHub (or Heroku or...)

If you have multiple accounts at a place like GitHub or Heroku, you'll have multiple ssh keys (at least one per account). To pick which account you want to log in as, you have to tell ssh which private key to use.

For example, suppose you had two GitHub accounts: foo and bar. Your ssh key for foo is ~/.ssh/foo_github_id and your ssh key for bar is ~/.ssh/bar_github_id. You want to access [email protected]:foo/foo.git with your foo account and [email protected]:bar/bar.git with your bar account. You would add the following to your ~/.ssh/config:

Host gh-foo Hostname github.com User git IdentityFile ~/.ssh/foo_github_id Host gh-bar Hostname github.com User git IdentityFile ~/.ssh/bar_github_id 

You would then clone the two repositories as follows:

git clone gh-foo:foo/foo.git # logs in with account foo git clone gh-bar:bar/bar.git # logs in with account bar 

Avoiding ssh altogether

Some services provide HTTP access as an alternative to ssh:

warning: Adding your password to the clone URL will cause Git to store your plaintext password in .git/config. To securely store your password when using HTTP, use a credential helper. For example:

git config --global credential.helper cache git config --global credential.https://github.com.username foo git clone https://github.com/foo/repository.git 

The above will cause Git to ask for your password once every 15 minutes (by default). See git help credentials for details.

2 Comments

This is the best explanation of how git works with SSH. My understanding is that when you specify [email protected]:path/to/repo.git, it effectively tells git that the user is git itself and that it should go grab your credentials (public key) from the ssh-agent for the Host "githost.com".
Brilliant, I've only one github but used since I have 2 emails for different projects in other repos, replacing [email protected] with the custom name which locates the relevant IdentityFile for the particular email works perfectly!
160

Follow these arguments to replace with your special cases if they are creating an issue:

 ! # $ & ' ( ) * + , / : ; = ? @ [ ] %21 %23 %24 %26 %27 %28 %29 %2A %2B %2C %2F %3A %3B %3D %3F %40 %5B %5D 

So for example:

Actual URL: https://usern@me:p@ssword@git/reponame.git

Solution URL to use: https://usern%40me:p%40ssword@git/reponame.git

3 Comments

Rather than fooling around with that, use this command: MYPASS=`echo -n "$ORIGPASS" | jq -sRr @uri`
This looks like an answer for a different question.
Afters hours I finally found this - Thanks a lot!
94

In the comments of Bassetassen's answer, plosco mentioned that you can use git clone https://<token>@github.com/username/repository.git to clone from GitHub at the very least. I thought I would expand on how to do that, in case anyone comes across this answer like I did while trying to automate some cloning.

GitHub has a very handy guide on how to do this, but it doesn't cover what to do if you want to include it all in one line for automation purposes. It warns that adding the token to the clone URL will store it in plaintext in .git/config. This is obviously a security risk for almost every use case, but since I plan on deleting the repository and revoking the token when I'm done, I don't care.

1. Create a Token

GitHub has a whole guide here on how to get a token, but here's the TL;DR.

  1. Go to Settings > Developer Settings > Personal Access Tokens (here's a direct link)
  2. Click "Generate a New Token" and enter your password again. (here's another direct link)
  3. Set a description/name for it, check the "repo" permission and hit the "Generate token" button at the bottom of the page.
  4. Copy your new token before you leave the page

2. Clone the repository

The same as the command plosco gave, git clone https://<token>@github.com/<username>/<repository>.git, just replace <token>, <username> and <repository> with whatever your information is.

If you want to clone it to a specific folder, just insert the folder address at the end like so: git clone https://<token>@github.com/<username>/<repository.git> <folder>, where <folder> is, you guessed it, the folder to clone it to! You can of course use ., .., ~, etc. here like you can elsewhere.

3. Leave No Trace

Not all of this may be necessary, depending on how sensitive what you're doing is.

  • You probably don't want to leave that token hanging around if you have no intentions of using it for some time, so go back to the tokens page and hit the delete button next to it.
  • If you don't need the repository again, delete it rm -rf <folder>.
  • If do need the repository again, but don't need to automate it again, you can remove the remote by doing git remote remove origin or just remove the token by running git remote set-url origin https://github.com/<username>/<repository.git>.
  • Clear your bash history to make sure the token doesn't stay logged there. There are many ways to do this, see this question and this question. However, it may be easier to just prepend all the above commands with a space in order to prevent them being stored to begin with.

Note that I'm not a professional, so the above may not be secure in the sense that no trace would be left for any sort of forensic work.

3 Comments

https://<token>@github.com was not accepted with my portal, I had to use https://oauth2:<token>@github.com
@MushyPeas This answer using just <token> worked fine for me using a Personal Access Token.
> However, it may be easier to just prepend all the above commands with a space in order to prevent them being stored to begin with. < That is not foolproof! Depending on the settings of HISTCONTROL even commands beginning with a space might be stored in the history. See also this SO answer.
53

A 13 Aug 2021 post you must use

To generate a token:

SettingsDeveloper settingsPersonal access tokensGenerate new token*

  • Git Push

After successful cloning, the next time when you do git push, you won't have to mention the username again. You can confirm this by opening the .git/config file in Notepad. It will show:

[remote "origin"] url = https://username:[email protected]/username/repo.git 

1 Comment

This worked for me, I did the below: Step 1: Your GitHub Profile → Settings → Developer settings → Personal access tokens → Tokens (classic) → Generate new token (copy the token) - set it’s expiry to permanent Step 2: git clone github.com/abcd/xyz.git Username for 'github.com': write_your_username Password for '[email protected]': paste your token ** this is just a one time thing to authenticate
36

Though there are many answers, I faced the repeated issue when username or password had special characters in them.

URL encode your username and password for Git, and then use it as part of URL itself (when there isn't any security concern).

Say, the URL encoded value of the username:

'user+1' is user%2B1

And the URL encoded value of the password:

'Welcome@1234' is Welcome%401234

Then your Git clone URL would look like,

git clone https://user%2B1:Welcome%401234@actual-git-url-for-the-repo works perfectly, whereas,

git clone https://user+1:Welcome@1234@actual-git-url-for-the-repo gives you 403 errors.

Just in case, if you want to URL encode online: URL Encode and Decode - Online

Comments

26

To clone a repository, first you should generate an access token (you can't use your login password anymore) and then clone the repository with this generated token.

Generate access token:

GitHub:
SettingsDeveloper settingsPersonal access tokensGenerate new token

Bitbucket:
SettingsPersonal Bitbucket settingsApp passwordsCreate app password

Clone the repository:

GitHub:

git clone https://YOUR-USERNAME:[email protected]/YOUR-USERNAME/YOUR-REPOSITORY 

Bitbucket:

git clone https://[email protected]/YOUR-REPOSITORY 

It will prompt you for the generated token.

Comments

18

I solved this problem in the following way:

enter image description here

7 Comments

never a good idea to type your password in command line. Did you know your system may store command line history in a file? (Ex: Linux has an hidden file named .bash_history)
Correct. Whenever I do this, or something like this, which at times can be very convenient, I always delete the command I used from the history (history -d).
@FrancescoMarchetti-Stasi you don't need to delete the command, just use a space at the beginning of the command and it will never get stored in the history.
Yes--I learnt it only a couple of months ago, after almost 30 years on Unix systems... shame on me :)
...unless you are on a corporate server which stores commands you type even so. Passwords on the command line are never a good idea.
|
15

On Windows, the following steps should retrigger the GitHub login window when git cloneing:

  • Search start menu for "Credential Manager"
  • Select "Windows Credentials"
  • Delete any credentials related to Git or GitHub

Result

Comments

14

If you're using http/https and you're looking to FULLY AUTOMATE the process without requiring any user input or any user prompt at all (for example: inside a CI/CD pipeline), you may use the following approach leveraging git credential.helper

GIT_CREDS_PATH="/my/random/path/to/a/git/creds/file" # Or you may choose to not specify GIT_CREDS_PATH at all. # See https://git-scm.com/docs/git-credential-store#FILES for the defaults used git config --global credential.helper "store --file ${GIT_CREDS_PATH}" echo "https://alice:${ALICE_GITHUB_PASSWORD}@github.com" > ${GIT_CREDS_PATH} 

where you may choose to set the ALICE_GITHUB_PASSWORD environment variable from a previous shell command or from your pipeline config etc.

Remember that "store" based git-credential-helper stores passwords & values in plain-text. So make sure your token/password has very limited permissions.


Now simply use https://[email protected]/my_repo.git wherever your automated system needs to fetch the repo - it will use the credentials for alice in github.com as store by git-credential-helper.

Comments

11

I prefer to use GIT_ASKPASS environment for providing HTTPS credentials to Git.
Provided that login and password are exported in USR and PSW variables, the following script does not leave traces of password in history and disk, plus it is not vulnerable to special characters in the password:

GIT_ASKPASS=$(mktemp) && chmod a+rx $GIT_ASKPASS && export GIT_ASKPASS cat > $GIT_ASKPASS <<'EOF' #!/bin/sh exec echo "$PSW" EOF git clone https://${USR}@example.com/repo.git 

NB: Note the single quotes around the heredoc marker 'EOF' which means that temporary script holds literally $PSW characters, not the password / expanded value of PSW variable

5 Comments

if you escape dollar sign - \$PSW you'll avoid unnecessarily embedding password into temporary file
@Marcin that's exactly what my recipe is avoiding: the temporary file referred in GIT_ASKPASS holds just the name of PSW variable, not its value
The $PSW in <<EOT is interpolated before file is created unless you escape dollar sign
@MarcinWisnicki Please tell the name and version of your shell. It works perfectly in Ubuntu Dash (/bin/sh) 0.5.11 and Bash 5.1.8 (but is expected to work in earlier versions of both as well). Please check if you put single quotes around EOF in cat >$GIT_ASKPASS <<'EOF' as provided in the listing
thanks, the qoutes around EOF made all the difference!
5

Use:

git config --global core.askpass 

Run this first before cloning the same way, and it should be fixed!

1 Comment

Setting global configuration is never a good idea as it could mess up other clones.
4

Git Custom Helper Script at Clone Time:

Using Only Environment Variables

tl;dr

One-liner

git -c credential.username=${CI_GIT_USER} -c credential.helper='!f() { test \"$1\" = get && echo "password=${CI_GIT_PASSWORD}"; }; f' clone --branch $CI_GIT_BRANCH $CI_GIT_URL $CI_GIT_ROOT 

Multi-liner

git -c credential.username=${CI_GIT_USER} \ -c credential.helper='!f() { test \"$1\" = get && echo "password=${CI_GIT_PASSWORD}"; }; f' \ clone --branch $CI_GIT_BRANCH $CI_GIT_URL $CI_GIT_ROOT 

Custom git credential.helper scripts

From the git credentials docs:

https://git-scm.com/docs/gitcredentials#_custom_helpers

# or you can specify your own shell snippet [credential "https://example.com"] username = your_user helper = "!f() { test \"$1\" = get && echo \"password=$(cat $HOME/.secret)\"; }; f" 

Not great since it is loading from a file but this could interpolate an environment variable.

Git Config at Clone Time

A little known fact is specifying git config when the git repo is not even created yet eg, cloning. You can specify git -c key=value clone <git_url_here>

I know this because I have had to get git to accept self-signed certificate authorities at clone time for server and client challenges.

https://git-scm.com/docs/git#Documentation/git.txt--cltnamegtltvaluegt

Why does the custom script work?

A git credential.helper needs to responds to either get, store or erase commands and reads from the stdout stream.

!f() { test \"$1\" = get && echo \"password=${CI_GIT_PASSWORD}\"; }; f 
  • test \"$1\" = get this checks if the command was get
  • && control operator will only run the next command if the prior command had an exit status that is Truthy (which weirdly has to be zero because that means EXIT_SUCCESS), a non-zero exit code is Falsey (Usually some failure code).
  • echo \"password=${CI_GIT_PASSWORD}\"; the stdout stream has a key=value response.
  • !f() { ... }; f This whole outside wrapper defines the command and runs it.

https://git-scm.com/docs/gitcredentials#Documentation/gitcredentials.txt-codegetcode

Resources

1 Comment

This answer is much underappreciated!
3

The organization that I work for uses Atlassian's Bitbucket product (not GitHub), essentially their version of GitHub so that repositories can be secured completely on premise. I was running into a similar problem as @coordinate, in that my password was required for a new repository I checked out. My credentials had been saved globally for all Bitbucket projects, so I'm not sure what prompted the loss of credentials.

In short, I was able to enter the following Git command (supplying only my username), which then prompted Git's Credential Manager to prompt me for the password, which I was then able to save.

git clone https://[email protected]/git/[organization]/[team]/[repository.git] 

Note: the bracketed directory sub-paths simply refer to internal references, and will vary for you!

Comments

2

HTTPS Git URLs

git clone https://user:password@host 

Including the password in the Git URL is considered bad practice because it risks inadvertent credentials exposure in config files and command history. It also breaks if the password changes.

More secure and more reliable is to use a credential-generating helper such as Git Credential Manager (included in Git for Windows) or git-credential-oauth (included in several Linux distributions).

The first time you authenticate, the helper opens a browser window to the host. Subsequent authentication within storage lifetime is non interactive.

SSH Git URLs

SSH authentication requires an SSH key. This file is thousands of bytes; you can't include it in the URL. You can include the username in the URL:

git clone ssh://user@host 

If the SSH key is protected by a passphrase, you can use ssh-agent to remember it.

Comments

2

Clone has been made simple to receive in your local directory using terminal windows via Personal Access Tokens. More over one can define the access permissions related to token in your GitHub settings.

Here is an example using Personal Token to receive the clone of a repo that is private:

git clone -b main https://[GITHUB_PERSONAL_TOKEN]@github.com/[GITHUB_ORG OR GITHUB_USERNAME]/[GITHUB_REPO].git 

Comments

1

In case you have the credentials stored in any kind of credential-helper, but not configured the credential helper to be active globally, you can clone like this:

git clone https://git.example.com/ns/repo.git --config=credential.helper=store 

This sets the credential-helper configuration locally (for the new repository only) before cloning.

Comments

-1

Most of the time this works well.

git clone https://username:[email protected]/username/repository.git 

However, there is another scenario when someone invites you to their organization's repository. And let’s say this is how the repository URL will look like.

https://github.com/organization/repo.git 

Now in this scenario, the following URL

https://username:[email protected]/username/repository.git

will not work. You need to make some modifications to it in the following way.

https://username:[email protected]/organization/repository.git 

Comments

-1

You need only no verify ssl:

git -c http.sslVerify=false clone https://github.com/organization/repo.git 

1 Comment

Disabling the SSL certificate validation is evil. Sometimes it may be needed for self-signed certificates but shoult never be required for publicly available services like GitHub.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.