I am trying to run ssh command to another ip namespace. I can do it right now, but it runs as root. I want to run it as a normal user. I want to know if there is a way to enter a non-root shell in another network namespace.

I know you can use this to enter a root shell in another namespace: sudo ip netns exec <namespace> bash

Alternatively, is there a way to run single commands as a non-root user? I know you can run commands as root with this: sudo ip netns exec <namespace> <command>

migrated from stackoverflow.com Oct 25 '13 at 2:53

This question came from our site for professional and enthusiast programmers.


Instead of ssh hostname use ssh username@hostname form. Or you can specify different username by ~/.ssh/config file:

Host foo*
User foobar

The command you are searching for is

su --command=' your command ' new_user_name

The best solution would be a program that can be installed setuid root so it can do the same things "ip netns exec" does to enter the namespace, but then drops root for the actual exec. Unfortunately I can't find such a thing.

The next best solution is a script:

#! /bin/bash
if [[ "$USER" != "root" || "$SUDO_USER" == "" ]]; then
        echo Call this script from sudo
        exit 1
ip netns exec "$NS" sudo -u "$SUDO_USER" $*

Put that in a file that's writable only by root and somewhere in the path e.g. /usr/local/bin/nsexec

Then to start ssh as your own user in a namespace you can do:

sudo nsexec testnamespace ssh

It should be safe to put the script name into your sudoers file so you don't get asked for a password. Since the namespace is the first argument you could even make sure only certain namespaces can be used.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy