Move sudo command making to one common function

This commit is contained in:
Daniel Hokka Zakrisson
2013-01-10 06:50:56 +01:00
parent c339434e57
commit 7ecab22302
4 changed files with 27 additions and 35 deletions

View File

@@ -31,6 +31,8 @@ import StringIO
import stat
import termios
import tty
import pipes
import random
VERBOSITY=0
@@ -529,3 +531,19 @@ def compile_when_to_only_if(expression):
else:
raise errors.AnsibleError("invalid usage of when_ operator: %s" % expression)
def make_sudo_cmd(sudo_user, executable, cmd):
"""
helper function for connection plugins to create sudo commands
"""
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop reading
# output until we see the randomly-generated sudo prompt set with
# the -p option.
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
sudocmd = 'sudo -k && sudo -S -p "%s" -u %s %s -c %s' % (
prompt, sudo_user, executable or '$SHELL', pipes.quote(cmd))
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt)