105 lines
2.6 KiB
Python
105 lines
2.6 KiB
Python
#!/usr/bin/python
|
|
import os
|
|
import subprocess
|
|
|
|
|
|
class JoinFailed(Exception):
|
|
pass
|
|
|
|
|
|
def _make_env():
|
|
env = os.environ.copy()
|
|
for k in list(env.keys()):
|
|
if k == 'LANG' or k.startswith('LC_'):
|
|
del env[k]
|
|
env['LANG'] = 'en_US.UTF-8'
|
|
return env
|
|
|
|
|
|
def is_domain_member():
|
|
cmd = ['net', 'ads', 'status', '-P']
|
|
with open(os.devnull, 'w+') as null:
|
|
p = subprocess.Popen(cmd, stdin=null, stdout=null, stderr=null)
|
|
return p.wait() == 0
|
|
|
|
|
|
def join_domain(username, password):
|
|
cmd = ['net', 'ads', 'join', '-U', username]
|
|
p = subprocess.Popen(
|
|
cmd,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
env=_make_env(),
|
|
)
|
|
output = p.communicate(password.encode('utf-8'))[0]
|
|
if p.wait() != 0:
|
|
raise JoinFailed(output.decode('utf-8'))
|
|
|
|
|
|
def leave_domain(username, password):
|
|
cmd = ['net', 'ads', 'leave', '-U', username]
|
|
p = subprocess.Popen(
|
|
cmd,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT,
|
|
env=_make_env(),
|
|
)
|
|
output = p.communicate(password.encode('utf-8'))[0]
|
|
if p.wait() != 0:
|
|
raise JoinFailed(output.decode('utf-8'))
|
|
|
|
|
|
def main():
|
|
module = AnsibleModule(
|
|
argument_spec=dict(
|
|
username=dict(
|
|
required=True,
|
|
),
|
|
password=dict(
|
|
required=True,
|
|
no_log=True,
|
|
),
|
|
state=dict(
|
|
choices=[
|
|
'joined',
|
|
'unjoined',
|
|
],
|
|
default='joined',
|
|
)
|
|
),
|
|
supports_check_mode=True,
|
|
)
|
|
|
|
username = module.params['username']
|
|
password = module.params['password']
|
|
state = module.params['state']
|
|
|
|
changed = False
|
|
if is_domain_member():
|
|
if state == 'unjoined':
|
|
changed = True
|
|
if not module.check_mode:
|
|
if not password:
|
|
module.fail_json(msg='Need password to leave domain')
|
|
try:
|
|
leave_domain(username, password)
|
|
except JoinFailed as e:
|
|
module.fail_json(message=e.args[0])
|
|
elif state == 'joined':
|
|
changed = True
|
|
if not module.check_mode:
|
|
if not password:
|
|
module.fail_json(msg='Need password to join domain')
|
|
try:
|
|
join_domain(username, password)
|
|
except JoinFailed as e:
|
|
module.fail_json(msg=e.args[0])
|
|
|
|
module.exit_json(changed=changed)
|
|
|
|
|
|
from ansible.module_utils.basic import *
|
|
main()
|