Поиск по блогу

четверг, 8 января 2015 г.

Как подключить системный прокси. In Windows 7 proxycfg.exe has been replaced with the netsh command

Почему "не хочет" работать команда set http_proxy. Именно поэтому. Здесь ссылки, инструкции и примеры для netsh.exe winhttp import proxy source=ie (начинать надо с show proxy). Прокси в Windows можно настроить через WinINET, WinHTTP, использовать WAP - протокол автоматической настройки прокси, или тупо изменить запись в реестре (скриптом).
Здесь ссылки на все случаи проксижизни... и ghbvths команд netsh.

In []:
Начинаес с фрагментов из "объясняющих" статей, плавно переходим к примерам, а в конце приложение с ключами реестра (из первой статьи)

Applications that have their own proxy settings. The settings must be configured in the application itself and the types of proxies that are supported depends on the application. The application is basically doing a lot of down-level tasks by itself, for example directly using the Winsock library to create TCP connections.

Applications using the WinINET library. WinINET is an API that can be leveraged in order to avoid reinventing the wheel. WinINET is the core of Internet Explorer and can also be used by other applications. Almost all functions available in IE (cookie handling, SSL, authentication, pop ups,..) are available. As such applications using the WinINET library directly take over the same proxy settings as the ones configured in Internet Explorer.

Applications using the WinHTTP library. WinHTTP is more suited for non-interactive usage, such as windows services or background tasks that need to communicate over HTTP where no user-interaction is required. It is a lot faster than the WinINET library. WinHTTP is also easily accessed from .NET based applications making it a popular library for .NET Applications. WinHTTP by default does not use the proxy settings from WinINET.

For both WinINET and WinHTTP, the proxy can be configured using different mechanisms:

proxy auto-configuration scripts
auto-discovery
manual configuration

Proxy Configuration for WinHTTP

By default, WinHTTP does not use the WinINET proxy settings that are defined in IE. The developer using WinHTTP can choose to perform an auto-detect of the proxy server to use, or specify a server manually. When a proxy server is not specified, WinHTTP falls back to the default WinHTTP proxy setting. This can be configured using the NETSH.EXE command line utility.

View current WinHTTP default proxy settings: netsh.exe winhttp show proxy

Set a fixed default WinHTTP proxy server and exclude local addresses: netsh.exe winhttp set proxy “”

Import the IE proxy settings of the current user as the default WinHTTP settings: netsh.exe winhttp import proxy source=ie

What about x64 and x86 ? When you want to configure the WinHTTP proxy settings for 32-bit applications on a 64-bit platform, you have to start the netsh.exe utility from the C:\Windows\Syswow64\ folder.

Фрагменты с ключами реестра из этой статьи в конце поста

In Windows 7 proxycfg.exe has been replaced with the netsh command. Netsh.exe is a command-line scripting utility that allows you to, either locally or remotely, display or modify the network configuration of a computer that is currently running. To setup a local machine proxy you would use the following syntax:

open a command prompt in administrative mode (hit start globe, type cmd, then hit Ctrl+Shift + Enter) To set a proxy:

In []:
netsh winhttp set proxy  [proxy server address:port number] [bypass list]

#Example:
netsh winhhtp set proxy "myproxy.proxyaddress.com:8484" "<local>;*.proxyaddress.com"

#To check your proxy server setting:
netsh winhttp show proxy

#To remove the proxy server setting:
netsh winhttp reset proxy

Это ссылка на документацию Майкррсофт...

You can use commands in the netsh winhttp context to configure proxy and tracing settings for Windows HTTP. The Netsh commands for winhttp can be run manually at the netsh prompt or in scripts and batch files.

To run these commands from the command prompt, you must either enter the netsh winhttp context or prepend the context to the command. For example, if you are at the command prompt but have not typed netsh and then winhttp to enter the netsh winhttp context

Web Proxy Auto-Discovery Protocol (WPAD) (протокол автоматической настройки прокси) — метод, используемый клиентами для определения места (URL) расположения конфигурационного файла с использованием технологий DHCP и/или DNS.
После того, как определено местоположение файла конфигурации и сам файл получен, клиент использует его для определения, каким прокси воспользоваться для каждого конкретного URL.
Протокол WPAD только определяет механизм поиска файла конфигурации, а вместе с ним чаще всего используется формат конфигурационного файла, разработанный фирмой Netscape в 1996 для Netscape Navigator 2.0.[1] Впервые протокол WPAD был описан консорциумом компаний Inktomi Corporation, Microsoft Corporation, RealNetworks, Inc., и Sun Microsystems, Inc.. Позже протокол WPAD был официально задокументирован в INTERNET-DRAFT, действие которого закончилось в декабре 1999.[2] Протокол WPAD поддерживается только старшими версиями браузеров. А впервые он был использован в Internet Explorer 5.0.

Приложение (ключи реестра из первой статьи)

Automatically detect settings:

This is enabled by default. When this setting is enabled, the Web Proxy Auto Discovery (WPAD) protocol is used. The proxy will be discovered by checking DHCP option XX or by issuing a DNS query to a WPAD A record in the current domain and top level domains. When an address is returned, that server will be queried to download a proxy autoconfiguration file containing the logic to determine the correct proxy to use for a given URL.

In []:
#How to control Automatically Detect Settings?

Registry Key : HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\
DWORD AutoDetect = 0 or 1

Use a proxy autoconfiguration script

An administrator can also specify the URL to an autoconfiguration script directly. This script is then downloaded and parsed. PAC scripts should have the .pac extension and contain the javascript function FindProxyForURL() that contains the required logic. The script returns either DIRECT or PROXY .

In []:
#How to control the Autoconfiguration Script setting?

Registry Key : HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\
REG_SZ AutoConfigURL = http://<your url>/proxy.pac
REG_DWORD ProxyEnable = 0

Manually specify proxy server

The proxy server(s) to use can also be specified manually, including a list of exceptions.

In []:
#How to control manually specified proxy server?

Registry Key : HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\
REG_SZ ProxyServer = <your proxyserver>:<port>
REG_SZ ProxyOverride = <local>;<your exclusion>
REG_DWORD ProxyEnable = 1

Making WinINET Proxy settings per-machine

The settings for the IE proxy are by default per user. This means that a user always has the ability to change his own proxy settings. In order to force a specific proxy server for all users on a machine, the proxy settings can be made machine-wide. This means only users with administrative rights can change the proxy settings. In order to make the proxy settings machine-wide, the following registry key or GPO must be set:

In []:
#GPO: Computer Configuration\Administrative Templates\Windows 
#Components\Internet Explorer\Make proxy settings per-machine (rather than per user)

Registry Key: HKLM\Software\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
DWORD: ProxySettingsPerUser = 0

The same registry keys can be used as for manually specifying the proxy server, but they have to be set in HKLM instead of HKCU. The machine-level settings can also be changed by running Internet Explorer as Administrator.

What about x64 and x86 ? By default the IE proxy settings are configured per-user. Within the HKCU registry hive, there is no distinction between x86 and x64 so the configured settings apply to both architectures. When the above change is made to apply proxy settings machine-wide, the settings are stored in HKLM\Software\Microsoft\Windows\CurrentVersion\Internet Settings AND in HKLM\Software\Wow6432Node\… When the settings are changed with IE (Run As Administrator) they will be updated in BOTH locations. When you want to set the machine-wide proxy manually you have to update the two locations.

Примеры записи в реестр из In Windows 7, how to change proxy settings from command line?

In []:
#Command to enable proxy usage:
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1 /f

#Command to disable proxy usage:
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f

#Command to change the proxy address:
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d proxyserveraddress:proxyport /f

Идея прямой записи в реестр интересна... Это универсальный механизм... но сейчас не до реестра... хотя

C:\WINDOWS\system32>req /? "req" не является внутренней или внешней командой, исполняемой программой или пакетным файлом.

C:\WINDOWS\system32>help reg Данная команда не поддерживается. Воспользуйтесь параметром "reg /?".

C:\WINDOWS\system32>reg /?

REG <операция> [Список параметров]

<операция> [ QUERY | ADD | DELETE | COPY | SAVE | LOAD | UNLOAD | RESTORE | COMPARE | EXPORT | IMPORT | FLAGS ]

Код возврата: (за исключением REG COMPARE)

0 - Успешно 1 - С ошибкой

Для получения справки по определенной операции введите:

REG <операция> /?

Примеры:

REG QUERY /? REG ADD /? REG DELETE /? REG COPY /? REG SAVE /? REG RESTORE /? REG LOAD /? REG UNLOAD /? REG COMPARE /? REG EXPORT /? REG IMPORT /? REG FLAGS /?

C:\WINDOWS\system32>

In [3]:
!chcp 65001
!REG ADD /?
Active code page: 65001

REG ADD KeyName [/v ValueName | /ve] [/t Type] [/s Separator] [/d Data] [/f]
        [/reg:32 | /reg:64]

  KeyName  [\\Machine\]FullKey
           Machine  Name of remote machine - omitting defaults to the
                    current machine. Only HKLM and HKU are available on remote
                    machines.
           FullKey  ROOTKEY\SubKey
           ROOTKEY  [ HKLM | HKCU | HKCR | HKU | HKCC ]
           SubKey   The full name of a registry key under the selected ROOTKEY.

  /v       The value name, under the selected Key, to add.

  /ve      adds an empty value name (Default) for the key.

  /t       RegKey data types
           [ REG_SZ    | REG_MULTI_SZ | REG_EXPAND_SZ |
             REG_DWORD | REG_QWORD    | REG_BINARY    | REG_NONE ]
           If omitted, REG_SZ is assumed.

  /s       Specify one character that you use as the separator in your data
           string for REG_MULTI_SZ. If omitted, use "\0" as the separator.

  /d       The data to assign to the registry ValueName being added.

  /f       Force overwriting the existing registry entry without prompt.

  /reg:32  Specifies the key should be accessed using the 32-bit registry view.

  /reg:64  Specifies the key should be accessed using the 64-bit registry view.

Examples:

  REG ADD \\ABC\HKLM\Software\MyCo
    Adds a key HKLM\Software\MyCo on remote machine ABC

  REG ADD HKLM\Software\MyCo /v Data /t REG_BINARY /d fe340ead
    Adds a value (name: Data, type: REG_BINARY, data: fe340ead)

  REG ADD HKLM\Software\MyCo /v MRU /t REG_MULTI_SZ /d fax\0mail
    Adds a value (name: MRU, type: REG_MULTI_SZ, data: fax\0mail\0\0)

  REG ADD HKLM\Software\MyCo /v Path /t REG_EXPAND_SZ /d ^%systemroot^%
    Adds a value (name: Path, type: REG_EXPAND_SZ, data: %systemroot%)
    Notice:  Use the caret symbol ( ^ ) inside the expand string



Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий