- Как настроить прокси в Linux
- Как настроить прокси в Linux
- В статье показано как настроить прокси в любой версии ОС Linux.
- Рассмотрим настройку переменных для использования прокси
- Тестирование работы
- Использование HTTP proxy и SOCKS в Linux
- curl: передача данных через proxy
- wget: закачка файлов через proxy
- ssh: доступ к серверам
- Соксификатор dante
- DNS запросы через proxy
- Proxy server
- Contents
- HTTPS MITM proxies
- Environment variables
- Keep proxy through sudo
- Automation with network managers
- About libproxy
- Web proxy options
- Simple Proxy with SSH
- Using a SOCKS proxy
- curl and pacman
- Proxy settings on GNOME3
- Microsoft NTLM proxy
- Configuration
- How to set up proxy using http_proxy & https_proxy environment variable in Linux?
- What is Proxy Server?
- Check current proxy configuration status (https_proxy/https_proxy)
- Set up proxy server using http_proxy environment variable
- Set up proxy without username and password
- Set up proxy with username and password
- Set up proxy with domain, username and password
- Special character (@) handling
- Set up proxy permanently using /etc/environment
- Set up proxy permanently using /etc/profile.d
Как настроить прокси в Linux
Как настроить прокси в Linux
В статье показано как настроить прокси в любой версии ОС Linux.
Прокси-сервер или proxy — в переводе с англ. «представитель» — сервер как комплекс программ в компьютерных сетях, позволяющий клиентам выполнять косвенные запросы к другим сетевым службам. В рамках данного материала прокси понимается сервер выполняющий доступ к глобальной сети интернет.
Проще всего для использования прокси в командной строке, но в зависимости от типа трафика, Вы можете определить переменные окружения http_proxy, https_proxy или ftp_proxy.
Практически все утилиты командой строки, такие как curl, wget, ssh, apt-get, ftp, wget, yum и прочие, используют данные переменные.
Рассмотрим настройку переменных для использования прокси
Используйте следующий синтаксис для настройки таких типов трафика как http, https и ftp из командной строки:
$ export ftp_proxy=»http://proxy-server:port»
$ export http_proxy=»http://proxy-server:port»
$ export https_proxy=»https://proxy-server:port»
Используйте следующий синтаксис, если прокси-сервер требует аутентификацию:
$ export http_proxy=»http://user:pass@proxy-server:port»
$ export https_proxy=»https://user:pass@proxy-server:port»
$ export ftp_proxy=»http://user:pass@proxy-server:port»
Если Ваш пароль содержит спец. символы, Вы должны заменить их на ASCII коды.
Например символ собаки «@», должен быть заменен на «%40» (т. е. p@ss = p%40ss).
Тестирование работы
Используйте следующую команду для проверки текущих переменных прокси:
$ env | grep -i proxy
Можно проверить работу прокси, узнав ваш внешний IP адрес из командной строки:
Источник
Использование HTTP proxy и SOCKS в Linux
В Linux существует много полезных консольных команд, которые при необходимости хотелось бы запустить через proxy. Некоторые приложения имеют встроенную поддержку proxy, а некоторые нет. Далее описано как пользоваться востребованными утилитами через proxy, даже теми, которые этой поддержки не имеют.
curl: передача данных через proxy
curl имеет полноценную поддержку как HTTP proxy так и SOCKS.
Для тестирования возможно использовать proxy сервера из бесплатных списков (socks — sockslist.net, и HTTP proxy — proxyhttp.net). Проверка IP адреса будет производиться с помощью ресурса check-host.net
Часть параметров curl можно записать в файл
С помощью time и curl также можно замерить время отклика сервера:
Результат будет выглядеть так:
wget: закачка файлов через proxy
wget имеет встроенную поддержку proxy. Недостаток лишь в том, что только поддержку HTTP proxy. Для использования совместно с SOCKS рекомендуется использовать соксификатор dante.
Чтобы все время не указывать —proxy-user и —proxy-password можно их прописать в файл
ssh: доступ к серверам
Для доступа к серверам через ssh и proxy также лучше использовать соксификатор dante.
Соксификатор dante
С помощью socksify можно направить через proxy почти любое приложение, не только консольное.
Чтобы все время не вводить данные о proxy можно создать файл /etc/socks.conf
Пример для SOCKS:
Пример для HTTP proxy с авторизацией:
А также экспортировать переменные SOCKS_USERNAME и SOCKS_PASSWORD, если для SOCKS или HTTP proxy требуется авторизация:
DNS запросы через proxy
Часто требуется чтобы и преобразование имен происходило через proxy. Если использовать dante, то запрос на преобразование имен идет и через proxy, и через именной сервер указанный в /etc/resolv.conf . Понять почему же идет два одинаковых запроса вместо одного не удалось. Поэтому можно предложить два варианта:
1) Закомментировать именные сервера в файле /etc/resolv.conf, чтобы преобразование имен шло только через proxy. Это отразится на всей системе.
2) Изменить /etc/resolv.conf и выставить именные сервера необходимой страны, или просто отличные от серверов провайдера. Например установить сервера Google:
Чтобы данные не были перезаписаны именными серверами провайдера (при переподключении), можно запретить обновление списка именных серверов сетевому менеджеру (NetworkManager/wicd) или DHCP-клиенту (спасибо ergil за корректировку).
Или воспользоваться «грубым» методом — запрещением изменения файла /etc/resolv.conf:
Если есть какие-то дополнения, пожалуйста, напишите, это будет полезно узнать и применить.
Источник
Proxy server
In computer networks, a proxy server is a server (a computer system or an application) that acts as an intermediary for requests from clients seeking resources from other servers.
Contents
HTTPS MITM proxies
When debugging HTTPS connections it is sometimes useful to intercept them outside of the browser. In order for the TLS MITM to work you need to trust a certificate authority of the proxy either in your browser or system-wide.
- Charles — Graphical trialware written in Java.
https://www.charlesproxy.com/ || charlesAUR
- Fiddler — Proprietary and graphical, running on Mono.
https://www.telerik.com/fiddler || fiddlerAUR
- mitmproxy — Command-line and web interface, written in Python, also has API.
https://mitmproxy.org/ || mitmproxy
- sslsplit — Works with any TLS connections but cannot act as a HTTP proxy in a browser, written in C.
https://www.roe.ch/SSLsplit || sslsplit
Environment variables
This article or section needs expansion.
/.config/environment.d/*.conf . (Discuss in Talk:Proxy server)
Some programs, such as wget and (used by pacman) curl, use environment variables of the form protocol_proxy to determine the proxy for a given protocol (e.g. HTTP, FTP, . ).
Below is an example on how to set these variables in a shell:
Some programs look for the all caps version of the environment variables.
If the proxy environment variables are to be made available to all users and all applications, the above mentioned export commands may be added to a script, say proxy.sh inside /etc/profile.d/ . The script has to be then made executable. This method is helpful while using a desktop environment like Xfce which does not provide an option for proxy configuration. For example, Chromium browser will make use of the variables set using this method while running XFCE.
Alternatively, there is a tool named proxyman-git AUR which claims to configure system-wide proxy settings easily. It also handles proxy configurations of other software like git, npm, Dropbox, etc. The project is inspired from Alan Pope’s idea of making a script.
Alternatively you can automate the toggling of the variables by adding a function to your .bashrc (thanks to Alan Pope for original script idea)
Omit username or password if they are not needed.
As an alternative, you may want to use the following script. Change the strings YourUserName , ProxyServerAddress:Port , LocalAddress and LocalDomain to match your own data, then edit your
/.bashrc to include the edited functions. Any new bash window will have the new functions. In existing bash windows, type source
/.bashrc . You may prefer to put function definitions in a separate file like functions then add source functions to .bashrc instead of putting everything in .bashrc . You may also want to change the name «myProxy» into something short and easy to write.
Keep proxy through sudo
If the proxy environment variables are set for the user only they will get lost when running commands with sudo (or when programs use sudo internally).
A way to prevent that is to add the following line to a sudo configuration file:
Automation with network managers
- NetworkManager cannot change the environment variables.
- netctl could set-up these environment variables but they would not be seen by other applications as they are not child of netctl.
About libproxy
libproxy (which is available in the extra repository) is an abstraction library which should be used by all applications that want to access a network resource. It still is in development but could lead to a unified and automated handling of proxies in GNU/Linux if widely adopted.
The role of libproxy is to read the proxy settings from different sources and make them available to applications which use the library. The interesting part with libproxy is that it offers an implementation of the Web Proxy Autodiscovery Protocol and an implementation of Proxy Auto-Config that goes with it.
The /usr/bin/proxy binary takes URL(s) as argument(s) and returns the proxy/proxies that could be used to fetch this/these network resource(s).
As of 06/04/2009 libproxy is required by libsoup. It is then indirectly used by the midori browser.
Web proxy options
- Squid is a very popular caching/optimizing proxy
- Privoxy is an anonymizing and ad-blocking proxy
- tinyproxy is a small, efficient HTTP/SSL proxy daemon
- For a simple proxy, ssh with port forwarding can be used
Simple Proxy with SSH
Connect to a server (HOST) on which you have an account (USER) as follows
For PORT, choose some number which is not an IANA registered port. This specifies that traffic on the local PORT will be forwarded to the remote HOST. ssh will act as a SOCKS server. Software supporting SOCKS proxy servers can simply be configured to connect to PORT on localhost.
Using a SOCKS proxy
There are two cases:
- the application you want to use handles SOCKS5 proxies (for example Firefox), then you just have to configure it to use the proxy.
- the application you want to use does not handle SOCKS proxies, then you can try to use tsocks or proxychains-ng .
In Firefox, you can use the SOCKS proxy in the menu Preferences > Network > Settings. Choose Manual Proxy Configuration, and set the SOCKS Host (and only this one, make sure the other fields, such as HTTP Proxy or SSL Proxy are left empty). For example, if a SOCKS5 proxy is running on localhost port 8080, put 127.0.0.1 in the SOCKS Host field, 8080 in the Port field, and validate.
If using proxychains-ng, the configuration takes place in /etc/proxychains.conf . You may have to uncomment the last line (set by default to use Tor), and replace it with the parameters of the SOCKS proxy. For example, if you are using the same SOCKS5 proxy as above, you will have to replace the last line by:
Then, proxychains-ng can be launched with
Where program can be any program already installed on your system (e.g. xterm, gnome-terminal, etc).
If using tsocks, the configuration takes place in /etc/tsocks.conf . See tsocks.conf(5) for the options. An example minimum configuration looks like this:
curl and pacman
You may set the all_proxy environment variable to let curl and pacman (which uses curl) use your socks5 proxy:
Proxy settings on GNOME3
Some programs like Chromium and Firefox can use the settings stored by GNOME. These settings can be modified through the gnome-control-center front end and also through gsettings.
This configuration can also be set to automatically execute when NetworkManager connects to specific networks, by using the proxydriver AUR package.
Microsoft NTLM proxy
In a Windows network, NT LAN Manager (NTLM) is a suite of Microsoft security protocols which provides authentication, integrity, and confidentiality to users.
cntlm AUR from the AUR stands between your applications and the NTLM proxy, adding NTLM authentication on-the-fly. You can specify several «parent» proxies and Cntlm will try one after another until one works. All authenticated connections are cached and reused to achieve high efficiency.
Configuration
Change settings in /etc/cntlm.conf as needed, except for the password. Then run:
This will generate encrypted password hashes according to your proxy hostname, username and password.
Источник
How to set up proxy using http_proxy & https_proxy environment variable in Linux?
Table of Contents
In this article I will share the steps to set up proxy server using https_proxy and https_proxy environment variable.
What is Proxy Server?
A proxy server is a dedicated computer or a software system running on a computer that acts as an intermediary between an endpoint device, such as a computer, and another server from which a user or client is requesting a service. The proxy server may exist in the same machine as a firewall server or it may be on a separate server, which forwards requests through the firewall.
Check current proxy configuration status (https_proxy/https_proxy)
This variable will show if there is a proxy server configured on the system:
If these variables are empty it would mean that there are no proxy servers configured on the system level.
Set up proxy server using http_proxy environment variable
The http_proxy and https_proxy environment variable is used to specify proxy settings to client programs such as curl and wget .
Set up proxy without username and password
Execute the below command with valid SERVER_IP and PORT on the terminal. This will enable proxy configuration for the current session but these values will not be persistent across reboot.
Set up proxy with username and password
You can modify the earlier command to add the username and password value assuming a valid authentication is required to enable the proxy server configuration. But again this command will also enable proxy server for the current session only and will not be persistent across reboots.
Set up proxy with domain, username and password
Assuming you are also required to add domain detail while setting up proxy configuration on your system then use the below command
Special character (@) handling
With more complex and robust handling of special characters in username or password follow How to setup http or https proxy with special characters in username and password
When the username or password uses the @ symbol, add a backslash (\) before the @ — for example:
Set up proxy permanently using /etc/environment
Now as I have highlighted above the above commands will work only for the current active session but will not be available across reboots. So to make these changes persistent define the environment variables in /etc/environment file:
Set up proxy permanently using /etc/profile.d
For bash and sh users, add the export line given above into a new file called /etc/profile.d/http_proxy.sh file:
For csh and tcsh users, use the following command to set the http_proxy variable in a new file called /etc/profile.d/http_proxy.csh file:
The extension of these files determines which shell will read them. The commands are not interchangeable.
Lastly I hope the steps from the article to setup proxy using http_proxy and https_proxy environment variable in Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Источник