Git proxy settings windows

Использование 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 будет скрыт псевдонимом.

    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.

    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?

    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:

    Getting Git to work with a proxy server — fails with “Request timed out”

    How do I get Git to use a proxy server?

    I need to check out code from a Git server, but it shows «Request timed out» every time. How do I get around this?

    Alternatively, how can I set a proxy server?

    20 Answers 20

    • change proxyuser to your proxy user
    • change proxypwd to your proxy password
    • change proxy.server.com to the URL of your proxy server
    • change 8080 to the proxy port configured on your proxy server

    Note that this works for both http and https repos.

    If you decide at any time to reset this proxy and work without proxy:

    Finally, to check the currently set proxy:

    This worked for me, in windows XP behind a corporate firewall.

    I didnt have to install any local proxy or any other software besides git v1.771 from http://code.google.com/p/msysgit/downloads/list?can=3

    proxyuser= the proxy user I was assigned by our IT dept, in my case it is the same windows user I use to log in to my PC, the Active Directory user

    proxypwd= the password of my proxy user

    proxy.server.com:8080 = the proxy name and port, I got it from Control Panel, Internet Options, Connections, Lan Settings button, Advanced button inside the Proxy Server section, use the servername and port on the first (http) row.

    mygithubuser = the user I use to log in to github.com

    mygithubpwd = the password for my github.com user

    repoUser = the user owner of the repo

    repoName = the name of the repo

    Set a system variable named http_proxy with the value of ProxyServer:Port . That is the simplest solution. Respectively, use https_proxy as daefu pointed out in the comments.

    Setting gitproxy (as sleske mentions) is another option, but that requires a «command», which is not as straightforward as the above solution.

    If the command line way of configuring your proxy server doesn’t work, you can probably just edit .gitconfig (in the root of your profile, which may hide both in C:\Documents and Settings and on some network drive) and add this:

    YMMV though, this only covers the first step of the command line configuration. You may have to edit the system git configuration too and I have no idea where they hid that.

    As an alternative to using git config —global http.proxy address:port , you can set the proxy on the command line:

    The advantage is the proxy is not persistently set. Under Bash you might set an alias:

    If you are using ubuntu, then do the following .

    Step 1 : Install corkscrew

    Step 2 : Write a script named git-proxy.sh and add the following

    Step 3 : Make the script executable

    Step 4 : Set up the proxy command for GIT by setting the environment variable

    Now use the git commands,such as

    Faced same issue because of multiple .gitconfig files in windows, followed below steps to fix the same:

    Step 1: Open Git BASH

    Step 2: Look for .gitconfig , executing following command:

    Step 3: Copy the below content in .gitconfig :

    There’s something I noticed and want to share here:

    The method above will not work for SSH URLs (i.e., git@github.com: /

    And things will not change if we set SSH over the HTTPS port (https://help.github.com/en/articles/using-ssh-over-the-https-port) because it only changes the port (22 by default) the SSH connection connects to.

    Try to put the following to the

    For the git protocol (git://. ), install socat and write a script such as:

    make it executable, put it in your path, and in your

    /.gitconfig set core.gitproxy to the name of that script.

    I work on Windows XP at work(state/gov), so I did my research and found this here and it worked for me. Hope this helps 🙂

    The http_proxy Environment Variable

    If you use a proxy server or firewall, you may need to set the http_proxy environment variable in order to access some url from commandline. Example : Installing ppm for perl or applying rpm in linux ,updating ubuntu

    Set the http_proxy variable with the hostname or IP address of the proxy server: http_proxy=http:// [proxy.example.org]

    If the proxy server requires a user name and password, include them in the following form: http_proxy=http:// [username:password@proxy.example.org]

    If the proxy server uses a port other than 80, include the port number: http_proxy=http:// [username:password@proxy.example.org:8080]

    Windows XP

    1. Open the Control Panel and click the System icon.
    2. On the Advanced tab, click on Environment Variables.
    3. Click New in the System variables panel.
    4. Add http_proxy with the appropriate proxy information (see examples above).
    Читайте также:  Не перемещаются иконки по рабочему столу windows
    Оцените статью