Pep8 fixes for known_hosts.py (#24029)
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
parent
7c1b8da1a1
commit
9456f93ea8
2 changed files with 72 additions and 70 deletions
|
@ -102,69 +102,68 @@ def enforce_state(module, params):
|
||||||
"""
|
"""
|
||||||
|
|
||||||
host = params["name"]
|
host = params["name"]
|
||||||
key = params.get("key",None)
|
key = params.get("key", None)
|
||||||
port = params.get("port",None)
|
port = params.get("port", None)
|
||||||
path = params.get("path")
|
path = params.get("path")
|
||||||
hash_host = params.get("hash_host")
|
hash_host = params.get("hash_host")
|
||||||
state = params.get("state")
|
state = params.get("state")
|
||||||
#Find the ssh-keygen binary
|
# Find the ssh-keygen binary
|
||||||
sshkeygen = module.get_bin_path("ssh-keygen",True)
|
sshkeygen = module.get_bin_path("ssh-keygen", True)
|
||||||
|
|
||||||
# Trailing newline in files gets lost, so re-add if necessary
|
# Trailing newline in files gets lost, so re-add if necessary
|
||||||
if key and key[-1] != '\n':
|
if key and key[-1] != '\n':
|
||||||
key+='\n'
|
key += '\n'
|
||||||
|
|
||||||
if key is None and state != "absent":
|
if key is None and state != "absent":
|
||||||
module.fail_json(msg="No key specified when adding a host")
|
module.fail_json(msg="No key specified when adding a host")
|
||||||
|
|
||||||
sanity_check(module,host,key,sshkeygen)
|
sanity_check(module, host, key, sshkeygen)
|
||||||
|
|
||||||
found,replace_or_add,found_line,key=search_for_host_key(module,host,key,hash_host,path,sshkeygen)
|
found, replace_or_add, found_line, key = search_for_host_key(module, host, key, hash_host, path, sshkeygen)
|
||||||
|
|
||||||
params['diff'] = compute_diff(path, found_line, replace_or_add, state, key)
|
params['diff'] = compute_diff(path, found_line, replace_or_add, state, key)
|
||||||
|
|
||||||
#We will change state if found==True & state!="present"
|
# We will change state if found==True & state!="present"
|
||||||
#or found==False & state=="present"
|
# or found==False & state=="present"
|
||||||
#i.e found XOR (state=="present")
|
# i.e found XOR (state=="present")
|
||||||
#Alternatively, if replace is true (i.e. key present, and we must change it)
|
# Alternatively, if replace is true (i.e. key present, and we must change
|
||||||
|
# it)
|
||||||
if module.check_mode:
|
if module.check_mode:
|
||||||
module.exit_json(changed = replace_or_add or (state=="present") != found,
|
module.exit_json(changed=replace_or_add or (state == "present") != found,
|
||||||
diff=params['diff'])
|
diff=params['diff'])
|
||||||
|
|
||||||
#Now do the work.
|
# Now do the work.
|
||||||
|
|
||||||
#Only remove whole host if found and no key provided
|
# Only remove whole host if found and no key provided
|
||||||
if found and key is None and state=="absent":
|
if found and key is None and state == "absent":
|
||||||
module.run_command([sshkeygen,'-R',host,'-f',path], check_rc=True)
|
module.run_command([sshkeygen, '-R', host, '-f', path], check_rc=True)
|
||||||
params['changed'] = True
|
params['changed'] = True
|
||||||
|
|
||||||
#Next, add a new (or replacing) entry
|
# Next, add a new (or replacing) entry
|
||||||
if replace_or_add or found != (state=="present"):
|
if replace_or_add or found != (state == "present"):
|
||||||
try:
|
try:
|
||||||
inf=open(path,"r")
|
inf = open(path, "r")
|
||||||
except IOError:
|
except IOError:
|
||||||
e = get_exception()
|
e = get_exception()
|
||||||
if e.errno == errno.ENOENT:
|
if e.errno == errno.ENOENT:
|
||||||
inf=None
|
inf = None
|
||||||
else:
|
else:
|
||||||
module.fail_json(msg="Failed to read %s: %s" % \
|
module.fail_json(msg="Failed to read %s: %s" % (path, str(e)))
|
||||||
(path,str(e)))
|
|
||||||
try:
|
try:
|
||||||
outf = tempfile.NamedTemporaryFile(mode='w+', dir=os.path.dirname(path))
|
outf = tempfile.NamedTemporaryFile(mode='w+', dir=os.path.dirname(path))
|
||||||
if inf is not None:
|
if inf is not None:
|
||||||
for line_number, line in enumerate(inf):
|
for line_number, line in enumerate(inf):
|
||||||
if found_line==(line_number + 1) and (replace_or_add or state=='absent'):
|
if found_line == (line_number + 1) and (replace_or_add or state == 'absent'):
|
||||||
continue # skip this line to replace its key
|
continue # skip this line to replace its key
|
||||||
outf.write(line)
|
outf.write(line)
|
||||||
inf.close()
|
inf.close()
|
||||||
if state == 'present':
|
if state == 'present':
|
||||||
outf.write(key)
|
outf.write(key)
|
||||||
outf.flush()
|
outf.flush()
|
||||||
module.atomic_move(outf.name,path)
|
module.atomic_move(outf.name, path)
|
||||||
except (IOError,OSError):
|
except (IOError, OSError):
|
||||||
e = get_exception()
|
e = get_exception()
|
||||||
module.fail_json(msg="Failed to write to file %s: %s" % \
|
module.fail_json(msg="Failed to write to file %s: %s" % (path, str(e)))
|
||||||
(path,str(e)))
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
outf.close()
|
outf.close()
|
||||||
|
@ -175,7 +174,8 @@ def enforce_state(module, params):
|
||||||
|
|
||||||
return params
|
return params
|
||||||
|
|
||||||
def sanity_check(module,host,key,sshkeygen):
|
|
||||||
|
def sanity_check(module, host, key, sshkeygen):
|
||||||
'''Check supplied key is sensible
|
'''Check supplied key is sensible
|
||||||
|
|
||||||
host and key are parameters provided by the user; If the host
|
host and key are parameters provided by the user; If the host
|
||||||
|
@ -183,26 +183,26 @@ def sanity_check(module,host,key,sshkeygen):
|
||||||
quits, providing an error to the user.
|
quits, providing an error to the user.
|
||||||
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
|
sshkeygen is the path to ssh-keygen, found earlier with get_bin_path
|
||||||
'''
|
'''
|
||||||
#If no key supplied, we're doing a removal, and have nothing to check here.
|
# If no key supplied, we're doing a removal, and have nothing to check here.
|
||||||
if key is None:
|
if key is None:
|
||||||
return
|
return
|
||||||
#Rather than parsing the key ourselves, get ssh-keygen to do it
|
# Rather than parsing the key ourselves, get ssh-keygen to do it
|
||||||
#(this is essential for hashed keys, but otherwise useful, as the
|
# (this is essential for hashed keys, but otherwise useful, as the
|
||||||
#key question is whether ssh-keygen thinks the key matches the host).
|
# key question is whether ssh-keygen thinks the key matches the host).
|
||||||
|
|
||||||
#The approach is to write the key to a temporary file,
|
# The approach is to write the key to a temporary file,
|
||||||
#and then attempt to look up the specified host in that file.
|
# and then attempt to look up the specified host in that file.
|
||||||
try:
|
try:
|
||||||
outf = tempfile.NamedTemporaryFile(mode='w+')
|
outf = tempfile.NamedTemporaryFile(mode='w+')
|
||||||
outf.write(key)
|
outf.write(key)
|
||||||
outf.flush()
|
outf.flush()
|
||||||
except IOError:
|
except IOError:
|
||||||
e = get_exception()
|
e = get_exception()
|
||||||
module.fail_json(msg="Failed to write to temporary file %s: %s" % \
|
module.fail_json(msg="Failed to write to temporary file %s: %s" %
|
||||||
(outf.name,str(e)))
|
(outf.name, str(e)))
|
||||||
rc,stdout,stderr=module.run_command([sshkeygen,'-F',host,
|
|
||||||
'-f',outf.name],
|
sshkeygen_command = [sshkeygen, '-F', host, '-f', outf.name]
|
||||||
check_rc=True)
|
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=True)
|
||||||
try:
|
try:
|
||||||
outf.close()
|
outf.close()
|
||||||
except:
|
except:
|
||||||
|
@ -211,6 +211,7 @@ def sanity_check(module,host,key,sshkeygen):
|
||||||
if stdout == '': # host not found
|
if stdout == '': # host not found
|
||||||
module.fail_json(msg="Host parameter does not match hashed host field in supplied key")
|
module.fail_json(msg="Host parameter does not match hashed host field in supplied key")
|
||||||
|
|
||||||
|
|
||||||
def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
|
def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
|
||||||
'''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
|
'''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line)
|
||||||
|
|
||||||
|
@ -225,16 +226,15 @@ def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
|
||||||
if os.path.exists(path) is False:
|
if os.path.exists(path) is False:
|
||||||
return False, False, None, key
|
return False, False, None, key
|
||||||
|
|
||||||
sshkeygen_command=[sshkeygen, '-F', host, '-f', path]
|
sshkeygen_command = [sshkeygen, '-F', host, '-f', path]
|
||||||
|
|
||||||
# openssh >=6.4 has changed ssh-keygen behaviour such that it returns
|
# openssh >=6.4 has changed ssh-keygen behaviour such that it returns
|
||||||
# 1 if no host is found, whereas previously it returned 0
|
# 1 if no host is found, whereas previously it returned 0
|
||||||
rc,stdout,stderr=module.run_command(sshkeygen_command,
|
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
|
||||||
check_rc = False)
|
|
||||||
if stdout == '' and stderr == '' and (rc == 0 or rc == 1):
|
if stdout == '' and stderr == '' and (rc == 0 or rc == 1):
|
||||||
return False, False, None, key # host not found, no other errors
|
return False, False, None, key # host not found, no other errors
|
||||||
if rc != 0: # something went wrong
|
if rc != 0: # something went wrong
|
||||||
module.fail_json(msg="ssh-keygen failed (rc=%d,stdout='%s',stderr='%s')" % (rc,stdout,stderr))
|
module.fail_json(msg="ssh-keygen failed (rc=%d, stdout='%s',stderr='%s')" % (rc, stdout, stderr))
|
||||||
|
|
||||||
# If user supplied no key, we don't want to try and replace anything with it
|
# If user supplied no key, we don't want to try and replace anything with it
|
||||||
if key is None:
|
if key is None:
|
||||||
|
@ -246,7 +246,7 @@ def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
|
||||||
sshkeygen_command.insert(1, '-H')
|
sshkeygen_command.insert(1, '-H')
|
||||||
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
|
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
|
||||||
if rc not in (0, 1) or stderr != '': # something went wrong
|
if rc not in (0, 1) or stderr != '': # something went wrong
|
||||||
module.fail_json(msg="ssh-keygen failed to hash host (rc=%d,stdout='%s',stderr='%s')" % (rc, stdout, stderr))
|
module.fail_json(msg="ssh-keygen failed to hash host (rc=%d, stdout='%s',stderr='%s')" % (rc, stdout, stderr))
|
||||||
hashed_lines = stdout.split('\n')
|
hashed_lines = stdout.split('\n')
|
||||||
|
|
||||||
for lnum, l in enumerate(lines):
|
for lnum, l in enumerate(lines):
|
||||||
|
@ -263,18 +263,19 @@ def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
|
||||||
found_key = normalize_known_hosts_key(l)
|
found_key = normalize_known_hosts_key(l)
|
||||||
if hash_host is True:
|
if hash_host is True:
|
||||||
if found_key['host'][:3] == '|1|':
|
if found_key['host'][:3] == '|1|':
|
||||||
new_key['host']=found_key['host']
|
new_key['host'] = found_key['host']
|
||||||
else:
|
else:
|
||||||
hashed_host=normalize_known_hosts_key(hashed_lines[lnum])
|
hashed_host = normalize_known_hosts_key(hashed_lines[lnum])
|
||||||
found_key['host']=hashed_host['host']
|
found_key['host'] = hashed_host['host']
|
||||||
key=key.replace(host,found_key['host'])
|
key = key.replace(host, found_key['host'])
|
||||||
if new_key==found_key: # found a match
|
if new_key == found_key: # found a match
|
||||||
return True, False, found_line, key # found exactly the same key, don't replace
|
return True, False, found_line, key # found exactly the same key, don't replace
|
||||||
elif new_key['type'] == found_key['type']: # found a different key for the same key type
|
elif new_key['type'] == found_key['type']: # found a different key for the same key type
|
||||||
return True, True, found_line, key
|
return True, True, found_line, key
|
||||||
# No match found, return found and replace, but no line
|
# No match found, return found and replace, but no line
|
||||||
return True, True, None, key
|
return True, True, None, key
|
||||||
|
|
||||||
|
|
||||||
def normalize_known_hosts_key(key):
|
def normalize_known_hosts_key(key):
|
||||||
'''
|
'''
|
||||||
Transform a key, either taken from a known_host file or provided by the
|
Transform a key, either taken from a known_host file or provided by the
|
||||||
|
@ -284,21 +285,22 @@ def normalize_known_hosts_key(key):
|
||||||
from the end (like the username@host tag usually present in hostkeys, but
|
from the end (like the username@host tag usually present in hostkeys, but
|
||||||
absent in known_hosts files)
|
absent in known_hosts files)
|
||||||
'''
|
'''
|
||||||
k=key.strip() #trim trailing newline
|
k = key.strip() # trim trailing newline
|
||||||
k=key.split()
|
k = key.split()
|
||||||
d = dict()
|
d = dict()
|
||||||
#The optional "marker" field, used for @cert-authority or @revoked
|
# The optional "marker" field, used for @cert-authority or @revoked
|
||||||
if k[0][0] == '@':
|
if k[0][0] == '@':
|
||||||
d['options'] = k[0]
|
d['options'] = k[0]
|
||||||
d['host']=k[1]
|
d['host'] = k[1]
|
||||||
d['type']=k[2]
|
d['type'] = k[2]
|
||||||
d['key']=k[3]
|
d['key'] = k[3]
|
||||||
else:
|
else:
|
||||||
d['host']=k[0]
|
d['host'] = k[0]
|
||||||
d['type']=k[1]
|
d['type'] = k[1]
|
||||||
d['key']=k[2]
|
d['key'] = k[2]
|
||||||
return d
|
return d
|
||||||
|
|
||||||
|
|
||||||
def compute_diff(path, found_line, replace_or_add, state, key):
|
def compute_diff(path, found_line, replace_or_add, state, key):
|
||||||
diff = {
|
diff = {
|
||||||
'before_header': path,
|
'before_header': path,
|
||||||
|
@ -323,20 +325,21 @@ def compute_diff(path, found_line, replace_or_add, state, key):
|
||||||
diff['after'] = ''.join(lines)
|
diff['after'] = ''.join(lines)
|
||||||
return diff
|
return diff
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
|
||||||
module = AnsibleModule(
|
module = AnsibleModule(
|
||||||
argument_spec = dict(
|
argument_spec=dict(
|
||||||
name = dict(required=True, type='str', aliases=['host']),
|
name=dict(required=True, type='str', aliases=['host']),
|
||||||
key = dict(required=False, type='str'),
|
key=dict(required=False, type='str'),
|
||||||
path = dict(default="~/.ssh/known_hosts", type='path'),
|
path=dict(default="~/.ssh/known_hosts", type='path'),
|
||||||
hash_host = dict(required=False, type='bool' ,default=False),
|
hash_host=dict(required=False, type='bool', default=False),
|
||||||
state = dict(default='present', choices=['absent','present']),
|
state=dict(default='present', choices=['absent', 'present']),
|
||||||
),
|
),
|
||||||
supports_check_mode = True
|
supports_check_mode=True
|
||||||
)
|
)
|
||||||
|
|
||||||
results = enforce_state(module,module.params)
|
results = enforce_state(module, module.params)
|
||||||
module.exit_json(**results)
|
module.exit_json(**results)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
@ -729,7 +729,6 @@ lib/ansible/modules/system/hostname.py
|
||||||
lib/ansible/modules/system/iptables.py
|
lib/ansible/modules/system/iptables.py
|
||||||
lib/ansible/modules/system/java_cert.py
|
lib/ansible/modules/system/java_cert.py
|
||||||
lib/ansible/modules/system/kernel_blacklist.py
|
lib/ansible/modules/system/kernel_blacklist.py
|
||||||
lib/ansible/modules/system/known_hosts.py
|
|
||||||
lib/ansible/modules/system/locale_gen.py
|
lib/ansible/modules/system/locale_gen.py
|
||||||
lib/ansible/modules/system/lvg.py
|
lib/ansible/modules/system/lvg.py
|
||||||
lib/ansible/modules/system/lvol.py
|
lib/ansible/modules/system/lvol.py
|
||||||
|
|
Loading…
Reference in a new issue