Lxc : how to run sudo command with python?

I’m trying to run sudo commands in python with a sudo user but I’m failing miserably.

    out = xenial_container.attach_wait(lxc.attach_run_command, ['id'])
    logger.debug('sudo id')
    out = xenial_container.attach_wait(lxc.attach_run_command, ['sudo', 'id'])
    logger.debug('id uid 1000')
    out = xenial_container.attach_wait(lxc.attach_run_command, ['id'], uid=1000, gid=1000)
    logger.debug('sudo id uid 1000 clearenv')
    out = xenial_container.attach_wait(lxc.attach_run_command, ['sudo', 'id'], uid=1000, gid=1000, env_policy=lxc.LXC_ATTACH_CLEAR_ENV,)
    logger.debug('sudo id uid 1000 let env')
    out = xenial_container.attach_wait(lxc.attach_run_command, ['sudo', 'id'],
                                       uid=1000, gid=1000)

uid=0(root) gid=0(root) groups=0(root)
DEBUG:tests.test_sudo:sudo id
uid=0(root) gid=0(root) groups=0(root)
DEBUG:tests.test_sudo:id uid 1000
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu)
DEBUG:tests.test_sudo:sudo id uid 1000 clearenv
sudo: no tty present and no askpass program specified
DEBUG:tests.test_sudo:sudo id uid 1000 let env
sudo: unable to run /usr/local/bin/enlightenment_askpass: No such file or directory

so basically sudo id works for the root user, but as soon as I add uid/gid it fails with “sudo: no tty present and no askpass program specified” of “sudo: unable to run /usr/local/bin/enlightenment_askpass: No such file or directory”

I’m under the impression I should pass some env variables with the extra_env_vars kwarg but I’m short of ideas of what to put.
I’m positive ubuntu (uid 1000) is in the sudo group and I’m aware of potentially editing the sudoers file with NOPASSWD but I’d like to avoid that as much as possible.

lxc-attach -n c2882cec-2b55-11e7-a6f1-f832e4beeab7 
root@c2882cec-2b55-11e7-a6f1-f832e4beeab7:/# id ubuntu
uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),27(sudo)

Yes, this is a kernel/glibc/sudo issue which causes you to not have what sudo considers a valid tty when attaching to an LXC container.

We did push a fix to glibc for this but pretty much no distro has received it yet. We may also need a matching patch to sudo itself (@brauner).

In the mean time, you can use the rather gross but effective workaround of instead running:

script -q -e /dev/null sudo

Which will effectively wrap sudo with another layer of pts devices which should make it happy.

1 Like

Right, I put patching sudo on my TODO. :slight_smile: