- Установить переменную среды http_proxy для пользователя домена и передать в windows
- 3 ответа
- Http Client. Default Proxy Свойство
- Определение
- Значение свойства
- Исключения
- Комментарии
- Are HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables standard?
- 2 Answers 2
- wget is not using environment variable based proxy settings
- 2 Answers 2
- VS Code does not use environment variable http_proxy #84845
- Comments
- simue commented Nov 14, 2019 •
Установить переменную среды http_proxy для пользователя домена и передать в windows
Я прочитал много сообщений на эту тему, но, к сожалению, не смог решить мою проблему. Я пытался установить переменные среды http_proxy и https_proxy в окнах, используя командную строку, чтобы получить доступ к веб-прокси моей компании.
Я использую Windows 8.1, в которой настройки прокси уже установлены
Моя система находится внутри company.com домена, поэтому:
Имя пользователя моего домена company\B.amini
И мой пароль домена BA@123
Стоит отметить, что когда я пингуюсь proxy01.company.com , командная строка показывает: Pinging tmg01.company.com [192.168.39.21] и выдает request timeout .
Вопрос:
Теперь, основываясь на приведенной выше информации, мой вопрос:
В чем может быть причина request timeout при проверке адреса прокси?
Идентификационные данные прокси совпадают с учетными данными домена?
Как правильно установить переменную http_proxy в командной строке?
Я пробовал много вариантов, в том числе:
Но во всех случаях выполнение такой команды, как Curl www.google.com -I , приводит к следующей ошибке:
HTTP / 1.1 407 Proxy Authentication Required (Forefront TMG требует авторизации для выполнения запроса. Доступ к фильтру веб-прокси запрещен.)
3 ответа
Обычно хосты не отвечают на эхо-запрос ICMP, поэтому время ожидания ping истекает, это уже ничего не значит (раньше это происходило в тот день, когда все отвечало).
Учетные данные прокси = учетные данные домена? Может быть. Зависит от того, настроен ли прокси для использования учетных записей вашего домена или нет. Поскольку это TMG, я бы сказал, что это очень вероятно.
переменная http_proxy для чего? Браузеры не используют переменные окружения для настройки прокси.
Эта ошибка 407 является аутентификационным вызовом прокси. Вы не получите больше, пока не начнете предоставлять учетные данные, которые примет прокси.
Проблема в @ в вашем пароле, вы должны сидеть так:
Также рекомендуется использовать setx для сохранения
Используйте% 40 вместо @ в пароле. Оно работает!
Http Client. Default Proxy Свойство
Определение
Возвращает или устанавливает глобальный прокси-сервер HTTP. Gets or sets the global Http proxy.
Значение свойства
Прокси-сервер, используемый каждым вызовом, который создает экземпляр HttpWebRequest . A proxy used by every call that instantiates a HttpWebRequest.
Исключения
Передаваемое значение не может быть null . The value passed cannot be null .
Комментарии
Это статическое свойство определяет прокси-сервер по умолчанию, HttpClient используемый всеми экземплярами, если прокси-сервер не задан явно в HttpClientHandler переданном через него конструкторе. This static property determines the default proxy that all HttpClient instances use if no proxy is set explicitly in the HttpClientHandler passed through its constructor.
Экземпляр по умолчанию, возвращаемый этим свойством, инициализирует следующий набор правил в зависимости от платформы: The default instance returned by this property will initialize following a different set of rules depending on your platform:
Для Windows: Считывает конфигурацию прокси-сервера из переменных среды или, если они не определены, из параметров прокси пользователя. For Windows: Reads proxy configuration from environment variables or, if those are not defined, from the user’s proxy settings.
Для macOS: Считывает конфигурацию прокси-сервера из переменных среды или, если они не определены, из параметров прокси-сервера системы. For macOS: Reads proxy configuration from environment variables or, if those are not defined, from the system’s proxy settings.
Для Linux: Считывает конфигурацию прокси-сервера из переменных среды или, если они не определены, это свойство инициализирует ненастроенный экземпляр, который обходит все адреса. For Linux: Reads proxy configuration from environment variables or, in case those are not defined, this property initializes a non-configured instance that bypasses all addresses.
Переменные среды, используемые для DefaultProxy инициализации платформ на платформе Windows и UNIX: The environment variables used for DefaultProxy initialization on Windows and Unix-based platforms are:
- HTTP_PROXY: прокси-сервер, используемый в HTTP-запросах. HTTP_PROXY: the proxy server used on HTTP requests.
- HTTPS_PROXY: прокси-сервер, используемый в запросах HTTPS. HTTPS_PROXY: the proxy server used on HTTPS requests.
- ALL_PROXY: прокси-сервер, используемый для запросов HTTP и (или) HTTPS в случае, если HTTP_PROXY и (или) HTTPS_PROXY не определены. ALL_PROXY: the proxy server used on HTTP and/or HTTPS requests in case HTTP_PROXY and/or HTTPS_PROXY are not defined.
- NO_PROXY: список имен узлов с разделителями-запятыми, которые следует исключить из прокси-сервера. NO_PROXY: a comma-separated list of hostnames that should be excluded from proxying.
В системах, где переменные среды учитывают регистр, имена переменных могут быть строчными или прописными. On systems where environment variables are case-sensitive, the variable names may be all lowercase or all uppercase. Имена в нижнем регистре проверяются первыми. The lowercase names are checked first.
Прокси-сервер может быть именем узла или IP-адресом, при необходимости можно указать двоеточие и номер порта, а также URL-адрес HTTP, при необходимости включая имя пользователя и пароль для проверки подлинности прокси. The proxy server may be a hostname or IP address, optionally followed by a colon and port number, or it may be an http URL, optionally including a username and password for proxy authentication. URL-адрес должен начинаться с http , https а не и содержать текст после имени узла, IP-адреса или порта. The URL must be start with http , not https , and cannot include any text after the hostname, IP, or port.
Are HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment variables standard?
It seems that a lot of programs are designed to read these environment variables to decide what proxy to go through in order to connect to a resource on the internet. Those programs may also have their own, individual proxy settings, but if those are not set, they’ll happily use these environment variables.
I just want to know:
- Are these environment variables standard?
- Is there a written specification (may be by the OS manufacturers?) that recommends the use of these environment variables?
2 Answers 2
I agree with BillThor’s statement that This is more a convention than a standard.
I don’t know the origin of these variables but in case of HTTP on *nix many conventions seem to originate from behavior of libcurl HTTP library and curl command line program.
At https://curl.haxx.se/docs/manual.html there’s description of environment variables related to using HTTP proxy which libcurl/curl understands:
Curl reads and understands the following environment variables:
http_proxy, HTTPS_PROXY, FTP_PROXY
They should be set for protocol-specific proxies. General proxy should be set with
ALL_PROXY
A comma-separated list of host names that shouldn’t go through any proxy is set in (only an asterisk, ‘*’ matches all hosts)
NO_PROXY
If the host name matches one of these strings, or the host is within the domain of one of these strings, transactions with that node will not be proxied.
Please notice that http_proxy is spelled lowercase as the only one among these variables. Some libraries/programs look for lowercase names of these variables whereas others look for upppercase names. To be safe one should define both lowercase and uppercase versions of each variable.
Another issue is that cited description of how host names are matched against NO_PROXY is not precise and does not answer the following questions:
- Should values be fully qualified domain names (FQDN) thus ending with a dot like foo.example.com. or not?
- Should foo.example.com match only this one domain or should it also match any subdomain like bar.foo.example.com ? If the latter then should it also match any subdomain in any subdomain like bar.baz.foo.example.com ?
- Is .foo.example.com (dot at the beginning) allowed and if so then what should it match ?
- Is asterisk ( * ) allowed as part of value ( *.example.com , *example.com ) and if so then how is it treated?
Lack of formal specification leads to confusion and bugs. Here one has to mention libproxy library which aims to provide correct and consistent support for proxy configuration. From project’s home page:
libproxy exists to answer the question: Given a network resource, how do I reach it? It handles all the details, enabling you to get back to programming.
wget is not using environment variable based proxy settings
I have a windows nano server and try to set the proxy settings. The nano server is only in command mode no GUI. I have run in PowerShell
and the IP address from google was shown, so there is some connection. But when I try to run
then I have set the proxy in the PowerShell environment with
but the same problem. When I call wget directly with the proxy settings it works:
How can I get it work that wget uses the global proxy settings? Or are the settings not correctly set? Or need I to install some windows features, that it is working?
I use wget to test the connection later any web request for any program should work.
2 Answers 2
Pretty sure your issue here is that you are not setting environment variables and getting mixed up between cmd exe’s and PowerShell cmdlets. As we read from the (what I hope is) the documentation for wget concerning proxy information:
The standard way to specify proxy location, which Wget recognizes, is using the following environment variables:
Which is exactly what you tried to do here which was a successful operation (no error) but did not work as expected.
Problem is that if you run that in PowerShell set is an alias for Set-Variable . See Get-Alias set .
You are also having an issue with wget as that is an alias of Invoke-WebRequest . That would only be an issue if you had at least PowerShell version 3.0 which you appear to have. In your working example you are using cmdlet syntax ( -Proxy . ).
In both cases ( set and the non-working wget ) the command was ambiguous and PowerShell had to try to match it up to something.
So what we are seeing here is about_Command_Precedence coming into play
If you do not specify a path, Windows PowerShell uses the following precedence order when it runs commands:
Native Windows commands is last on the list! Really though if you are in PowerShell doing this you might as well use PowerShell cmdlets to get your environment variables set (if you insist on using wget ). The only thing I am not sure of is which method you should use the first here should not persist the session where the second method is permanent. Sure the first would suffice but use the second if you want to keep these set on the computer between sessions.
- $env:http_proxy = «ipaddress:8080»
- [Environment]::SetEnvironmentVariable(«http_proxy», «ipaddress:8080», «Machine»)
You can read more on this from TechNet. Also watch your spelling of «address»
If you are going to be using cmd utilities make sure you append .exe and if you don’t specify the full path to the resource then ensure its directory is part of the path environment variable.
VS Code does not use environment variable http_proxy #84845
Comments
simue commented Nov 14, 2019 •
Go to VS Code settings, section Application>Proxy.
See Proxy setting whose clarification is «The proxy setting to use. If not set, will be inherited from the http_proxy and https_proxy environment variables.»
Set environment variable http_proxy.
Do networking stuff. E.g. try to sign in to Azure via Azure Account Extension: Press F1 «>Azure: Sign In».
Get Error notification saying «You appear to be offline. Please check your network connection.» which is generated by Azure Account Extension.
Go to Settings.json, set «http.proxy»: «http://server:port»
Try to log in again.
I consider this a Bug, as the help text in the settings dialogue states that environment variables are loaded and used centrally, when they are not.
Further more, it is not the case that proxy settings can’t be used by the extension since written directly into the settings.json everything works.
VS Code version: Code 1.40.1 (8795a98, 2019-11-13T16:49:35.976Z)
OS version: Windows_NT x64 10.0.17763
System Info
Item | Value |
---|---|
CPUs | Intel(R) Xeon(R) CPU E3-1505M v5 @ 2.80GHz (8 x 2808) |
GPU Status | 2d_canvas: enabled flash_3d: enabled flash_stage3d: enabled flash_stage3d_baseline: enabled gpu_compositing: enabled metal: disabled_off multiple_raster_threads: enabled_on oop_rasterization: disabled_off protected_video_decode: unavailable_off rasterization: enabled skia_renderer: disabled_off surface_control: disabled_off surface_synchronization: enabled_on video_decode: enabled viz_display_compositor: enabled_on viz_hit_test_surface_layer: disabled_off webgl: enabled webgl2: enabled |
Load (avg) | undefined |
Memory (System) | 31.92GB (24.07GB free) |
Process Argv | |
Screen Reader | no |
VM | 0% |
Extensions (9)
Extension | Author (truncated) | Version |
---|---|---|
python | ms- | 2019.10.44104 |
vscode-ai | ms- | 0.6.7 |
azure-account | ms- | 0.8.7 |
team | ms- | 1.161.0 |
azure-iot-edge | vsc | 1.18.0 |
azure-iot-toolkit | vsc | 2.13.0 |
azure-iot-tools | vsc | 0.3.0 |
vscode-iot-device-cube | vsc | 0.1.4 |
vscode-iot-workbench | vsc | 0.10.16 |
The text was updated successfully, but these errors were encountered: