How to set a per-user resolv.conf

Solution 1:

Local filesystem namespaces are your friend, though they do require root permissions to set up.

sudo unshare --mount bash -s <<'EOF'
  mount --bind /path/to/your/resolv.conf /etc/resolv.conf
  sudo -u username-to-run-as command-to-run-with-alternate-resolv-conf 
EOF

If you want a script which will run an arbitrary command with your updated resolv.conf, consider:

#!/bin/bash
## usage: with-custom-resolver /path/to/resolv.conf cmd arg1 arg2 ...
## ...note that this requires root.

script=""
add_cmd() {
  local cmd_str
  printf -v cmd_str '%q ' "$@"
  script+="$cmd_str"$'\n'
}

resolv_conf=$1; shift

[[ $EUID = 0 ]] || { echo "Must be run as root" >&2; exit 1; }
[[ -e $resolv_conf ]] || { echo "No file found at: $resolv_conf" >&2; exit 1; }

add_cmd mount --bind "$resolv_conf" /etc/resolv.conf
add_cmd exec "$@"
unshare --mount sh -e -c "$script"

Thus, this could be used as:

with-custom-resolver your-resolv.conf sudo -u someuser some-command arg1

Solution 2:

Simple answer -- NO....

However, if you were to setup a different virual machine for each user, you might have a chance at doing what you want.

Seems a little pointless however.

Solution 3:

To test a DNS server, you do not need to change the resolver configuration. You just need to change the DNS server in the host, nslookup or dig command.

host www.google.com 8.8.8.8

You can also use a chroot environment or Linux Containers (LXC) to have a different resolv.conf file.