Ask and drop sudo rights at the right moment

This commit is contained in:
Théophile Bastian 2020-03-19 23:32:19 +01:00
parent 4e39260232
commit abe5fc6972
2 changed files with 22 additions and 3 deletions

View file

@ -149,3 +149,14 @@ def run_in_executor(f):
return loop.run_in_executor(None, functools.partial(f, *args, **kwargs)) return loop.run_in_executor(None, functools.partial(f, *args, **kwargs))
return inner return inner
def ensure_sudo_rights():
""" Updates sudo credentials to ensure that the user is logged in afterwards,
without typing in a password """
run_cmd_retry(["sudo", "-v"])
def drop_sudo_rights():
""" Drop sudo credentials """
run_cmd_retry(["sudo", "-k"])

View file

@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from lxc_net import parse_network, libvirt_error from lxc_net import parse_network, libvirt_error, util
import signal import signal
import libvirt import libvirt
import argparse import argparse
@ -16,7 +16,7 @@ def parse_args():
return args return args
def handle_dom(topology, cmd): def handle_dom(topology, cmd, sudo_drop=True):
if not cmd: if not cmd:
print("Missing argument.") print("Missing argument.")
return return
@ -30,13 +30,17 @@ def handle_dom(topology, cmd):
print("Bad id: {}".format(cmd[1])) print("Bad id: {}".format(cmd[1]))
return return
state = cmd[0] == "up" state = cmd[0] == "up"
util.ensure_sudo_rights()
if dom_id: if dom_id:
for dom in dom_id: for dom in dom_id:
topology.dom_setstate_single(dom, state, verbose=True) topology.dom_setstate_single(dom, state, verbose=True)
else: else:
topology.dom_setstate(state, verbose=True) topology.dom_setstate(state, verbose=True)
if sudo_drop:
util.drop_sudo_rights()
elif cmd[0] == "restart": elif cmd[0] == "restart":
handle_dom(topology, ["down"] + cmd[1:]) handle_dom(topology, ["down"] + cmd[1:], sudo_drop=False)
handle_dom(topology, ["up"] + cmd[1:]) handle_dom(topology, ["up"] + cmd[1:])
elif cmd[0] == "help": elif cmd[0] == "help":
print("Available commands: up, down, restart, help") print("Available commands: up, down, restart, help")
@ -97,15 +101,19 @@ def main():
topology = parse_network.YamlTopology(args.topology, conn) topology = parse_network.YamlTopology(args.topology, conn)
util.ensure_sudo_rights()
topology.net_start(verbose=True) topology.net_start(verbose=True)
topology.dom_start(verbose=True) topology.dom_start(verbose=True)
util.drop_sudo_rights()
print("Network running. Press ^C to terminate.") print("Network running. Press ^C to terminate.")
main_loop(topology) main_loop(topology)
util.ensure_sudo_rights()
topology.dom_stop(verbose=True) topology.dom_stop(verbose=True)
topology.net_stop(verbose=True) topology.net_stop(verbose=True)
util.drop_sudo_rights()
if __name__ == "__main__": if __name__ == "__main__":