Git windows proxy setting

Использование git за прокси с аутентификацией

Достаточно часто я оказываютсь в ситуации, когда нужно обратиться к git-репозитарию, находясь за корпоративным файерволом, да еще и с аутентифицирующим прокси.
Бинарный протокол git закрыт наглухо, но, теоретически, есть возможность работать через http. Теоретически, потому что если прокси требует аутентификации — то git полностью отказывается с ним работать, по крайней мере под Windows.
Выход — пустить git через локальный прокси, который будет аутентифицироваться на upstream сам. Для этих целей будем использовать небезызвестный privoxy.

В примере используется допущение, что вы хотите получить доступ к github.com. Доступ будет настроен только к нему, ни к чему больше.
Еще одно допущение — ваш прокси поддерживает базовую (Basic) аутентификацию по http протоколу. Если же включена только NTLM аутентификация, то вместо privoxy потребуется установка cntlm. Этот случай мы не рассматриваем, но там все еще проще.

Шаги:

  1. Ставим себе на машину privoxy. Мой файервол запрещает доступ к privoxy.org, ваш, возможно, тоже. Качаем отсюда
  2. Ставить лучше portable версию, незачем мозолить глаза админам новыми записями в списке установленных программ.
  3. Правим config.txt, добавляем строчку
    forward github.com :
  4. В config.txt добавляем еще строчку
    debug 8 # Вывод информации о HTTP заголовках
  5. Запускаем браузер, ставим в качестве прокси localhost:8118
  6. Заходим на github.com, авторизуемся на прокси, выходим из браузера
  7. Ищем в логах privoxy строчку вида
    Jun 14 18:05:55.577 000017dc Header: scan: Proxy-Authorization: Basic gzMzAcG06T2lkb387XBsZX3gzMzAc2lkJlZG06T=
    Копируем ваш токен в сухое темное место.
  8. Добавляем в user.action строку:
    <+add-header>
    .github.com

Естественно, заменяем токен на ваш.

  • Удаляем из config.txt строку
    debug 8
  • С прокси все, осталось малое — настроить git.
    git config —global http.proxy http: //localhost:8118/
    Пробел только уберите после http:, пришлось добавить, т.к. парсер в ссылку превращает.
  • Вот и все, теперь git сможет работать через аутентифицирующий прокси. Правда, только по протоколу http.

    В качестве бонуса: вы теперь можете вообще забыть о том, что ваш прокси требует ввода пароля, если везде будете пользоваться локальным прокси, а не корпоративным.
    Все, что надо сделать — заменить в user.action строку «.github.com» на «/».

    Приятных вам коммитов!

    Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

    Set proxy for Microsoft Git Provider in Visual Studio

    I have to use http proxy to connect to Git server. I am able to set it through Git Bash and use it too through the following command:

    However, I am using Microsoft Git Provider integration with Visual Studio. And I am not able to set proxy anywhere to connect to Git server. Is there a way that I can save the proxy details for Microsoft Git Provider in Visual Studio?

    4 Answers 4

    There is not a direct way to set a Git proxy in Visual Studio

    You don’t need to setup anything in Visual Studio in order to setup the Git proxy — in fact, I haven’t found any way to do so within Visual Studio directly, and the alternate answer on using devenv.exe.config I was not personally able to get to work.

    However, there is an easy solution

    Visual Studio will install Git for Windows as long as you have Git checkmarked during install (the latest versions have this by default). Once Git for Windows (or Git in general on any OS) is installed, you can easily setup the global Git proxy settings directly at any command line, console, or Powershell window.

    In fact, you can open a command or Powershell prompt directly in Visual Studio with Tools/NuGet Package Manager/Package Manager Console .

    If Git is installed, you can type git at any command line and you’ll get a list of all the git commands. If this does not happen, you can install Git for Windows directly — I would recommend doing that as a part of installing the Git Extensions GUI application, but your mileage may vary.

    The git commands in particular you need are:

    • The proxy address likely is http:// and not https://
    • USER:PASSWORD@ is the user name and password if required for your proxy
    • URL is the full domain name of the proxy
    • PORT is the port of the proxy, and might be different for http and https

    This will setup your proxy in a global config file in your «MyDocuments» folder. The file might be named differently or place somewhere else depending on your OS and other factors. You can always view this file and edit the sections and key/value pairs directly with the following command:

    This will open up the global config in the current editor setup in Git, or possibly the system default text editor. You can also see the config file for any given repo by being in the repo directory and leaving off the —global flag.

    After setting up the proxy, you should see something like the following as a part of the file:

    You can enter these values directly rather than using the config commands, or can delete them to remove the proxy from the config.

    Note: This file is also where the user.name and user.email that are used for commits is stored — see the [user] section.

    Other useful Git configs for proxy

    1. You can also leave off the —global or replace it with —local if you want to setup the proxy for the current local repo (you must be in the repo directory when issuing the command).

    2. In addition, you can setup a proxy for just a specific URL as follows:

    Note that the full URL should be used (i.e. http:// or https:// in the front).

    3. In addition, if you ever have multiple remote repos, say origin and upstream , which need different proxies, you can set a proxy for one specifically.

    4. You can set the proxy to null by substituting «» for the proxy URL. This may be useful if, for example, you want to set the proxy globally, but then exclude a specific URL which is behind your company firewall (such as an enterprise, on premises version of Github), and the proxy doesn’t handle local addresses correctly. This may also be helpful with localhost and other special addresses or direct IP addresses.

    5. You can check what the proxy is for a given URL with the following:

    Using Git on Windows, behind an HTTP proxy, without storing proxy password on disk

    I’m using Git on Windows, on a corporate network where I’m behind an HTTP proxy with Basic authentication. Outbound SSH doesn’t work, so I have to use HTTPS through the proxy.

    I’m aware of how to use git config http.proxy to configure the settings as http://[username]:[password]@[proxy]:[port] .

    However, particularly as this is a shared machine, I’d rather not store my password in my .gitconfig . Additionally, changing my .gitconfig using the git config command leaves my password in my bash history, so even if I remember to clear my .gitconfig at the end of the session, I’ll almost certainly forget to clear my history as well.

    I’ve tried setting http.proxy without a password, in the vain hope that I’d get a prompt asking me for my password when I try to push/pull, but I only get a 407 Proxy Authentication Required. All the information I’ve found online seems to either ignore the issues with having the password saved in plaintext in .gitconfig , or deals with NTLM proxies.

    I’m quite happy to type my proxy details every time I need to connect — the best solution I can see at the moment is writing a wrapper script that will prompt for my password and set that as an environment variable when calling git proper. Is this a decent solution, and are there any security implications to setting an environment variable for a single call in a script? Preferably, are there any built-in settings or existing tools that I can use for this?

    Only use a proxy for certain git urls/domains?

    Is it possible to configure git to use a proxy only for specific domains?

    I’d like to use our corporate proxy to access Github but leave it off for accessing our own internal git repos.

    I’m using bower and it needs to require items both within our firewall and on github so I can’t do this as a per project setting. It needs to be some kind of global configuration option. Any thoughts?

    7 Answers 7

    I usually use the environment variables:

    That is picked up by git when accessing GitHub repo.

    • both http_proxy and https_proxy must use the http:// url of the proxy (no https:// ).
    • always use the fqn (full qualified name) of proxydomain (don’t rely on its short name)

    But for internal repo, all I have to do is define and export one more environment variable:

    • no_proxy=.my.company,localhost,127.0.0.1. 1 , for accessing any repo with an address like myrepo.my.company or localhost.

    You can define NO_PROXY or no_proxy , it doesn’t matter.

    But just in case, I always set HTTP_PROXY , HTTPS_PROXY , http_proxy , https_proxy , NO_PROXY and no_proxy .

    But what is really neat is, starting git1.8.5 (October 2013), you can set http settings per url.

    The » http.* » variables can now be specified per URL that the configuration applies.
    For example,

    would flip http.sslVerify off only when talking to that specified site.

    With only specified, you can get a list of all variables in the section with their values that apply to the given URL. E.g

    All the details are in commit 6a56993b:

    Any of the http.* options above can be applied selectively to some urls.
    For a config key to match a URL, each element of the config key is compared to that of the URL, in the following order:

    • Scheme (e.g., https in https://example.com/ ).
    • Host/domain name (e.g., example.com in https://example.com/ ).
    • Port number (e.g., 8080 in http://example.com:8080/ ).
    • Path (e.g., repo.git in https://example.com/repo.git ).
    • User name (e.g., user in https://user@example.com/repo.git )

    The list above is ordered by decreasing precedence; a URL that matches a config key’s path is preferred to one that matches its user name.
    For example, if the URL is https://user@example.com/foo/bar a config key match of https://example.com/foo will be preferred over a config key match of https://user@example.com .

    All URLs are normalized before attempting any matching (the password part, if embedded in the URL, is always ignored for matching purposes) so that equivalent urls that are simply spelled differently will match properly.

    Environment variable settings always override any matches.
    The urls that are matched against are those given directly to Git commands.
    This means any URLs +visited as a result of a redirection do not participate in matching.

    coin8086 / using-proxy-for-git-or-github.md

    Use Proxy for Git/GitHub

    Generally, the Git proxy configuration depends on the Git Server Protocal you use. And there’re two common protocals: SSH and HTTP/HTTPS. Both require a proxy setup already. In the following, I assume a SOCKS5 proxy set up on localhost:1080 . But it can also be a HTTP proxy. I’ll talk about how to set up a SOCKS5 proxy later.

    When you do git clone ssh://[user@]server/project.git or git clone [user@]server:project.git , you’re using the SSH protocal. You need to configurate your SSH client to use a proxy. Add the following to your SSH config file, say

    This is to make all SSH connections, including those by Git, via the proxy at localhost:1080 .

    If you want to use a HTTP proxy at localhost:1080 , do it like:

    You may want to use a proxy for a specific host, say GitHub. You can do it like this:

    This uses a proxy only for GitHub, so that when you git clone git@github.com:your-name/your-project.git , the proxy works.

    The above SSH configuration involves Linux command nc and ssh config ProxyCommand . Learm more about them if you’re interested.

    When you do git clone http://example.com/gitproject.git or git clone https://example.com/gitproject.git , you’re using the HTTP/HTTPS protocal.

    Git respects http_proxy and https_proxy envrionment variables, so you can simply execute the following command in a shell:

    After that, your git command under the same shell will use the proxy for HTTP/HTTPS connections.

    BTW, Git also has a http.proxy configuration to override those two envrionment variables:

    You can set the http.proxy configuration by git config command(or by editing the git config file directly) instead of export those environment variables.

    Setup a SOCKS5 Proxy

    It’s very easy to setup a SOCKS5 proxy with your SSH Client:

    Execute this command under a shell with user and host replaced with yours. This is to setup a SOCKS5 proxy at port 1080 at localhost.

    A Little More on Git Protocol

    By saying «Git Protocol», I mean a Git Server Protocal called «The Git Protocol». It has a URI like git://server/project.git . Note it starts with a git:// , not ssh:// or http:// or something else.

    It’s not commonly used, so you can skip this. I write this mainly for completeness of Git proxy settings.

    Читайте также:  Windows software and macintosh
    Оцените статью