Http proxy server linux

How to set up proxy using http_proxy & https_proxy environment variable in Linux?

In this article I will share the steps to set up proxy server using https_proxy and https_proxy environment variable.

How to set up proxy using http_proxy & https_proxy environment variable in Linux?

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:

# echo $http_proxy # echo $https_proxy

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.

# export http_proxy=http://SERVER:PORT/

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.

# export http_proxy=http://USERNAME:PASSWORD@SERVER:PORT/

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

# export http_proxy=http://DOMAIN\\USERNAME:PASSWORD@SERVER:PORT/

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

Читайте также:  Linux ubuntu или manjaro

When the username or password uses the @ symbol, add a backslash (\) before the @ — for example:

export http_proxy=http://DOMAIN\\USERN\@ME:PASSWORD@SERVER:PORT
export http_proxy=http://DOMAIN\\USERNAME:P\@SSWORD@SERVER:PORT

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:

# echo "http_proxy=http://proxy.example.com:3128/" >> /etc/environment

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:

# echo "export http_proxy=http://proxy.example.com:3128/" > /etc/profile.d/http_proxy.sh

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:

# echo "setenv http_proxy http://proxy.example.com:3128/" > /etc/profile.d/http_proxy.csh

The extension of these files determines which shell will read them. The commands are not interchangeable.

Replace http_proxy with https_proxy in the export argument to enable proxy over SSL/TLS. This information will be provided by the Network Team who have provided the proxy server related details.

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.

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

4 thoughts on “How to set up proxy using http_proxy & https_proxy environment variable in Linux?”

Your example “Set up proxy permanently using /etc/environment” should use a double redirect (>>) to APPEND instead of a single redirect (>) to OVERWRITE the environment file. If someone were to copy/paste your example, they would overwrite any other existing environment settings in their /etc/environment file! # echo “http_proxy=http://proxy.example.com:3128/” >> /etc/environment Reply

Читайте также:  Linux узнать температуру видеокарты

I would like to set up a proxy in debian10 via environment file.
The username, password, however, includes a comma (,)
How does that affect the phrasing? Reply

Источник

Использование 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

# Проверить HTTP proxy curl --proxy 11.22.33.44:5555 check-host.net/ip # Тоже самое, но если для HTTP proxy требуется авторизация curl --proxy 11.22.33.44:5555 -U username:password check-host.net/ip # Проверить socks4 curl --socks4 11.22.33.44:5555 check-host.net/ip # Проверить socks5 curl --socks5 11.22.33.44:5555 check-host.net/ip # Тоже самое, только преобразование имен идет также через SOCKS # (подробнее о преобразовании имен можно прочитать ниже в подразделе "DNS запросы через proxy") curl --socks5-hostname 11.22.33.44:5555 check-host.net/ip 

Часть параметров curl можно записать в файл ~/.curlrc:

socks5 = 11.22.33.44:5555 proxy-user = username:password user-agent = "Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1" 

С помощью time и curl также можно замерить время отклика сервера:

# Без proxy: time curl check-host.net/ip # С proxy: time curl --socks5 11.22.33.44:5555 check-host.net/ip # Или любого сайта: time curl habrahabr.ru 

Результат будет выглядеть так:

real 0m0.307s user 0m0.000s sys 0m0.004s 

wget: закачка файлов через proxy

wget имеет встроенную поддержку proxy. Недостаток лишь в том, что только поддержку HTTP proxy. Для использования совместно с SOCKS рекомендуется использовать соксификатор dante.

 # Скачать файл через proxy: http_proxy="http://33.22.44.44:8080" wget http://www.google.com/favicon.ico Тоже самое, но для HTTPS https_proxy="http://33.22.44.44:8080" wget https://www.google.com/favicon.ico # Использовать proxy с авторизацией http_proxy="http://33.22.44.44:8080" wget --proxy-user=user --proxy-password=password http://www.google.com/favicon.ico 

Чтобы все время не указывать —proxy-user и —proxy-password можно их прописать в файл ~/.wgetrc:

proxy-user = username proxy-password = password user-agent = Mozilla/5.0 (X11; Linux i686; rv:7.0.1) Gecko/20100101 Firefox/7.0.1 

ssh: доступ к серверам

Для доступа к серверам через ssh и proxy также лучше использовать соксификатор dante.

Читайте также:  Linux usb to serial port

Соксификатор dante

apt-get install dante-client # пример для Debian-based систем 
# Если требуется зайти по ssh на сервер SOCKS_PASSWORD="" SOCKS_SERVER="11.22.33.44:1080" socksify ssh myserver # Тоже самое, только если для подключения к соксу требуется авторизация SOCKS_USERNAME="user" SOCKS_PASSWORD="password" SOCKS_SERVER="11.22.33.44:1080" socksify ssh myserver # Пример с использованием IRC клиента - irssi SOCKS_PASSWORD="" SOCKS_SERVER="11.22.33.44:1080" socksify irssi # Тоже самое, только с использованием HTTP proxy с поддержкой метода CONNECT HTTP_CONNECT_PROXY="http://11.22.33.44:8080" socksify irssi 

С помощью socksify можно направить через proxy почти любое приложение, не только консольное.

Чтобы все время не вводить данные о proxy можно создать файл /etc/socks.conf
Пример для SOCKS:

Пример для HTTP proxy с авторизацией:

А также экспортировать переменные SOCKS_USERNAME и SOCKS_PASSWORD, если для SOCKS или HTTP proxy требуется авторизация:

export SOCKS_USERNAME="username" export SOCKS_PASSWORD="password" 

DNS запросы через proxy

Часто требуется чтобы и преобразование имен происходило через proxy. Если использовать dante, то запрос на преобразование имен идет и через proxy, и через именной сервер указанный в /etc/resolv.conf . Понять почему же идет два одинаковых запроса вместо одного не удалось. Поэтому можно предложить два варианта:
1) Закомментировать именные сервера в файле /etc/resolv.conf, чтобы преобразование имен шло только через proxy. Это отразится на всей системе.
2) Изменить /etc/resolv.conf и выставить именные сервера необходимой страны, или просто отличные от серверов провайдера. Например установить сервера Google:

nameserver 8.8.8.8 nameserver 8.8.4.4 

Чтобы данные не были перезаписаны именными серверами провайдера (при переподключении), можно запретить обновление списка именных серверов сетевому менеджеру (NetworkManager/wicd) или DHCP-клиенту (спасибо ergil за корректировку).

Или воспользоваться «грубым» методом — запрещением изменения файла /etc/resolv.conf:

sudo chattr +i /etc/resolv.conf 

Если есть какие-то дополнения, пожалуйста, напишите, это будет полезно узнать и применить.

Источник

Оцените статью
Adblock
detector