How do I provide a username and password when running "git clone [email protected]"?
Asked Answered
B

19

1323

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.

Blastomere answered 7/4, 2012 at 12:5 Comment(6)
You can't. The "git" before the "@" is already a username. From where did you get the repository URL ([email protected])? From where did you get the idea that you have to provide a different username and a password?Toxinantitoxin
My repos URL is from heroku "[email protected]:zxy-helloworld.git". And I use emacs shell to clone and push. If the shell asks for password, emacs will hang. This is a known issue with emacs on Windows: gnu.org/software/emacs/windows/…Blastomere
What if the username is an email? how do you type it? [email protected]@example.com ?Gussi
See GitHub's instruction on how to create a token and that why it's better due to scoping and permissionsRosabella
@Honey the question is not GitHub specific.Chiliasm
Why has this question started to receive new answers after a gap of more than six years?Peach
T
1937

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.

Testerman answered 7/4, 2012 at 12:25 Comment(33)
it doesn't have to be the same by the way. If your colleague created the git repo and you are logging in as another account, they will not be the same.Diplomate
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 keyMeghan
@Zephiro your advice is poor, unless you also tell people to use a strong passphrase on their private key. Otherwise, there is not much difference in having a cleartext password vs an unprotected private key on your hard drive.Corotto
@MrDuk no problem, escape it (as %40 iirc).Pecuniary
@Testerman Works fine for clone. Does not work for pull. #11506624Vested
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 historyGallia
you can also type 'space' at the beginning of the line so that linux won't store the command in historyStealing
this is especially useful for old git versions, who do not ask for both "username" and "password" when cloning a repo on a fresh machineGiga
You can also add a space in front of the command. This way, it won't be stored in your bash history.Selective
Not so easy if the password contains unusual characters.Ass
second username was creating issues removing that worked for me: git clone https://username:[email protected]/repository.gitMcadoo
How to use if my password contains '@' symbolSarsaparilla
@AtulAgrawal See Benjamin Gruenbaum's commentTesterman
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.gitSelfesteem
I had a situation where I was already logged on as another user. I tried the second option of this answer, and it said "Authentication failed." I merely tried it a second time, and it prompted me for the password and worked. <shrug>Bilek
when I use this command on google colab, this error is received: fatal: could not read Password for '[email protected]': No such device or address, and it does not ask me for passwordJapheth
Thanks a ton! Works well for PULL on bitbucket.org as well : git pull https://[user]:[password]@bitbucket.org/[bitbucket-account]/[project].git [branch]Hereunto
I had many different special characters in the password, the percent encoding helped me to include the password as part of URL. Reference: fabianlee.org/2016/09/07/…Smilacaceous
if you use the format git clone https://username:[email protected]/username/repository.git and the error message URL using bad / illegal format or missing URL appears, then this is probably a special character in your password, then use git clone https://[email protected]/username/repository.git to wait for prompt.Advert
Why are you even mentioning the first unsecure method and why do you put it in the first place?Gotthard
@Black, what is exactly unsecured? URLs are encrypted so username and password are secured.Market
@MaksimShamihulau, it will show in your "history" file with your password in clear textGotthard
password would be replaced with private_token with GitLab.Mudcat
my password has @ as a special character , how do i deal with it?Lumber
For Docker users, if you need to use HTTPS during the build phase to pull your project, you can clear the bash history just after with the history -c command.Noway
THE QUESTION IS NOT GITHUB SPECIFIC, and neither should be the answer.Chiliasm
This is now deprecated and Github recommends using Personal Tokens or SSH over this. github.blog/…Imago
This solution worked, I couldn't clone a github repo because my git configs had other credentials. cmd and SourceTree didn't work but using this command I was able to clone successfully.Susysuter
Why, if the question is about SSH, you answer with an HTTPS solution? Is the solution possible for SSH? No? Then write it in your answer and, if you want, tell wahy.Arpent
Hello. How do i insert a password that containts @ ?Halogenate
This should not be done on a shared server as the password will be stored in the git remote URL.Bedabble
thanks bro worked for me, just needed to replace password with <personal access token> of githubBengaline
Replace the @ symbol in your password with %40. Url encode any other special characters. Try urlencoder.io but I'd recommend only putting in the special character(s) and not your whole password. ;)Legatee
N
297

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.

Narine answered 7/4, 2012 at 16:16 Comment(2)
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".Cichlid
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!Vociferate
S
143

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

Sheritasherj answered 11/12, 2019 at 10:51 Comment(2)
Rather than fooling around with that, use this command: MYPASS=`echo -n "$ORIGPASS" | jq -sRr @uri`Captainship
This looks like an answer for a different question.Ledger
C
90

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.

Carreon answered 5/5, 2018 at 18:56 Comment(3)
https://<token>@github.com was not accepted with my portal, I had to use https://oauth2:<token>@github.comInelegant
@Inelegant This answer using just <token> worked fine for me using a Personal Access Token.Roybn
> 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.Chauncey
P
48

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
Partridge answered 31/8, 2021 at 5:19 Comment(1)
A token where? At GitHub? What page specifically? That information ought to be included in the answer (but *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** without *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** "Edit:", "Update:", or similar - the answer should appear as if it was written today).)Peach
S
34

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

Smilacaceous answered 17/4, 2019 at 7:12 Comment(0)
S
22

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.

Scotney answered 25/6, 2022 at 10:24 Comment(0)
S
18

I solved this problem in the following way:

enter image description here

Scaremonger answered 2/7, 2018 at 10:37 Comment(7)
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)Automate
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).Confetti
@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.Antipole
Yes--I learnt it only a couple of months ago, after almost 30 years on Unix systems... shame on me :)Confetti
...unless you are on a corporate server which stores commands you type even so. Passwords on the command line are never a good idea.Leishmaniasis
But the password will be still there in .git/config file. So it is not at all secure.Goat
This ought to be in text form.Peach
B
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

Biggin answered 16/10, 2018 at 11:57 Comment(0)
G
12

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.

Gemini answered 27/4, 2020 at 18:21 Comment(0)
T
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

Towney answered 22/1, 2021 at 16:10 Comment(5)
if you escape dollar sign - \$PSW you'll avoid unnecessarily embedding password into temporary fileSheryllshetland
@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 valueTowney
The $PSW in <<EOT is interpolated before file is created unless you escape dollar signSheryllshetland
@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 listingTowney
thanks, the qoutes around EOF made all the difference!Sheryllshetland
C
5

Use:

git config --global core.askpass

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

Couchant answered 5/9, 2018 at 8:32 Comment(1)
Setting global configuration is never a good idea as it could mess up other clones.Petrina
P
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!

Provo answered 29/10, 2019 at 23:4 Comment(0)
A
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.

Aundreaaunson answered 20/7, 2023 at 14:48 Comment(0)
C
2

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

Chock answered 29/9, 2023 at 6:21 Comment(1)
This answer is much underappreciated!Pontius
A
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.

Apogeotropism answered 10/8, 2022 at 9:40 Comment(0)
M
0

You need only no verify ssl:

git -c http.sslVerify=false clone https://github.com/organization/repo.git
Mikael answered 5/2 at 10:47 Comment(0)
I
0

Clone have been made simple to receive on 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
Imago answered 9/4 at 11:3 Comment(0)
C
-2

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
Catherin answered 30/8, 2023 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.