Bash http_proxy: from a user environment to sudo one
Hi. Sometimes you can’t connect directly to internet, because you have to go through a proxy (i.e. working environment).
Did you ever have to set up an http proxy on linux shell in order to (i.e) download a new package or manually update your distribution with a packet manager?
If so, you need to be a superuser. If you use the “sudo” command, you will probably stumbled across the inability to export variables from the user environment to the “sudo” one.
Something like this:
$ sudo export ... sudo: export: command not found
I’ll start from the beginning: how to set up a proxy on linux shell (in this post I assume that you use the bash shell).
In order to set up an http proxy you have to write the following command:
$ http_proxy="http://username:password@host:port" $ export http_proxy
These simple commands create a variable (http_proxy) and set it to “http://username:password@host:port”. Where:
- username: your username to access to the proxy;
– password: your password to access to the proxy;
– domain: the proxy’s host (i.e. 127.0.0.1 or foo.asd.it);
– port: the proxy’s port.
In line 2, we “export” the “http_proxy” variable, in such way that any subsequent program that we’ll run can use that.
If the proxy doesn’t have an autentication access you can simply write:
$ http_proxy="http://host:port" $ export http_proxy
Obviously you can write the two commands in a only one line:
$ export http_proxy="http://domain:port"
You can set also a ftp proxy, using the “ftp_proxy” variable:
$ export ftp_proxy="http://domain:port"
This is all very nice, but there is a little problem: if you run any subsequent program as “sudo” user, you may not use the variable, because the environment is different from that in which the variable has been defined. Indeed if you try to download a new packet using “apt-get”(or any other packet manager), you need to run it as superuser: so you have to use the “sudo” command. If you try that, you will notice that the program (apt-get) can’t connect to the WAN (World Area Network) and fails.
If you don’t want to login as root ($ sudo -i) every time you need to use the http_proxy variable in “super user mode”, you can simply add the following line to the “/etc/sudoers” file:
Defaults env_keep = "http_proxy ftp_proxy"
You must add the line above this line:
We “keep” the variables “http_proxy” and “ftp_proxy” because we want to export only this two to the “sudo” environment. If you want, you can only export “http_proxy” or add another one.
You can easily modify the sudoers file running this command:
$ sudo visudo
That’s all! I hope this will be useful as it was to me.