Pep8 fixes for known_hosts.py (#24029)

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
Abhijeet Kasurde 2017-04-27 19:51:49 +05:30 committed by Matt Martz
parent 7c1b8da1a1
commit 9456f93ea8
2 changed files with 72 additions and 70 deletions

View file

@ -102,69 +102,68 @@ def enforce_state(module, params):
"""
host = params["name"]
key = params.get("key",None)
port = params.get("port",None)
key = params.get("key", None)
port = params.get("port", None)
path = params.get("path")
hash_host = params.get("hash_host")
state = params.get("state")
#Find the ssh-keygen binary
sshkeygen = module.get_bin_path("ssh-keygen",True)
# Find the ssh-keygen binary
sshkeygen = module.get_bin_path("ssh-keygen", True)
# Trailing newline in files gets lost, so re-add if necessary
if key and key[-1] != '\n':
key+='\n'
key += '\n'
if key is None and state != "absent":
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)
#We will change state if found==True & state!="present"
#or found==False & state=="present"
#i.e found XOR (state=="present")
#Alternatively, if replace is true (i.e. key present, and we must change it)
# We will change state if found==True & state!="present"
# or found==False & state=="present"
# i.e found XOR (state=="present")
# Alternatively, if replace is true (i.e. key present, and we must change
# it)
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'])
#Now do the work.
# Now do the work.
#Only remove whole host if found and no key provided
if found and key is None and state=="absent":
module.run_command([sshkeygen,'-R',host,'-f',path], check_rc=True)
# Only remove whole host if found and no key provided
if found and key is None and state == "absent":
module.run_command([sshkeygen, '-R', host, '-f', path], check_rc=True)
params['changed'] = True
#Next, add a new (or replacing) entry
if replace_or_add or found != (state=="present"):
# Next, add a new (or replacing) entry
if replace_or_add or found != (state == "present"):
try:
inf=open(path,"r")
inf = open(path, "r")
except IOError:
e = get_exception()
if e.errno == errno.ENOENT:
inf=None
inf = None
else:
module.fail_json(msg="Failed to read %s: %s" % \
(path,str(e)))
module.fail_json(msg="Failed to read %s: %s" % (path, str(e)))
try:
outf = tempfile.NamedTemporaryFile(mode='w+', dir=os.path.dirname(path))
if inf is not None:
for line_number, line in enumerate(inf):
if found_line==(line_number + 1) and (replace_or_add or state=='absent'):
continue # skip this line to replace its key
if found_line == (line_number + 1) and (replace_or_add or state == 'absent'):
continue # skip this line to replace its key
outf.write(line)
inf.close()
if state == 'present':
outf.write(key)
outf.flush()
module.atomic_move(outf.name,path)
except (IOError,OSError):
module.atomic_move(outf.name, path)
except (IOError, OSError):
e = get_exception()
module.fail_json(msg="Failed to write to file %s: %s" % \
(path,str(e)))
module.fail_json(msg="Failed to write to file %s: %s" % (path, str(e)))
try:
outf.close()
@ -175,7 +174,8 @@ def enforce_state(module, params):
return params
def sanity_check(module,host,key,sshkeygen):
def sanity_check(module, host, key, sshkeygen):
'''Check supplied key is sensible
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.
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:
return
#Rather than parsing the key ourselves, get ssh-keygen to do it
#(this is essential for hashed keys, but otherwise useful, as the
#key question is whether ssh-keygen thinks the key matches the host).
# Rather than parsing the key ourselves, get ssh-keygen to do it
# (this is essential for hashed keys, but otherwise useful, as the
# key question is whether ssh-keygen thinks the key matches the host).
#The approach is to write the key to a temporary file,
#and then attempt to look up the specified host in that file.
# The approach is to write the key to a temporary file,
# and then attempt to look up the specified host in that file.
try:
outf = tempfile.NamedTemporaryFile(mode='w+')
outf.write(key)
outf.flush()
except IOError:
e = get_exception()
module.fail_json(msg="Failed to write to temporary file %s: %s" % \
(outf.name,str(e)))
rc,stdout,stderr=module.run_command([sshkeygen,'-F',host,
'-f',outf.name],
check_rc=True)
module.fail_json(msg="Failed to write to temporary file %s: %s" %
(outf.name, str(e)))
sshkeygen_command = [sshkeygen, '-F', host, '-f', outf.name]
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=True)
try:
outf.close()
except:
@ -211,6 +211,7 @@ def sanity_check(module,host,key,sshkeygen):
if stdout == '': # host not found
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):
'''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:
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
# 1 if no host is found, whereas previously it returned 0
rc,stdout,stderr=module.run_command(sshkeygen_command,
check_rc = False)
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
if stdout == '' and stderr == '' and (rc == 0 or rc == 1):
return False, False, None, key # host not found, no other errors
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 key is None:
@ -246,7 +246,7 @@ def search_for_host_key(module, host, key, hash_host, path, sshkeygen):
sshkeygen_command.insert(1, '-H')
rc, stdout, stderr = module.run_command(sshkeygen_command, check_rc=False)
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')
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)
if hash_host is True:
if found_key['host'][:3] == '|1|':
new_key['host']=found_key['host']
new_key['host'] = found_key['host']
else:
hashed_host=normalize_known_hosts_key(hashed_lines[lnum])
found_key['host']=hashed_host['host']
key=key.replace(host,found_key['host'])
if new_key==found_key: # found a match
hashed_host = normalize_known_hosts_key(hashed_lines[lnum])
found_key['host'] = hashed_host['host']
key = key.replace(host, found_key['host'])
if new_key == found_key: # found a match
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
return True, True, found_line, key
# No match found, return found and replace, but no line
return True, True, None, key
def normalize_known_hosts_key(key):
'''
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
absent in known_hosts files)
'''
k=key.strip() #trim trailing newline
k=key.split()
k = key.strip() # trim trailing newline
k = key.split()
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] == '@':
d['options'] = k[0]
d['host']=k[1]
d['type']=k[2]
d['key']=k[3]
d['host'] = k[1]
d['type'] = k[2]
d['key'] = k[3]
else:
d['host']=k[0]
d['type']=k[1]
d['key']=k[2]
d['host'] = k[0]
d['type'] = k[1]
d['key'] = k[2]
return d
def compute_diff(path, found_line, replace_or_add, state, key):
diff = {
'before_header': path,
@ -323,20 +325,21 @@ def compute_diff(path, found_line, replace_or_add, state, key):
diff['after'] = ''.join(lines)
return diff
def main():
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True, type='str', aliases=['host']),
key = dict(required=False, type='str'),
path = dict(default="~/.ssh/known_hosts", type='path'),
hash_host = dict(required=False, type='bool' ,default=False),
state = dict(default='present', choices=['absent','present']),
),
supports_check_mode = True
)
argument_spec=dict(
name=dict(required=True, type='str', aliases=['host']),
key=dict(required=False, type='str'),
path=dict(default="~/.ssh/known_hosts", type='path'),
hash_host=dict(required=False, type='bool', default=False),
state=dict(default='present', choices=['absent', 'present']),
),
supports_check_mode=True
)
results = enforce_state(module,module.params)
results = enforce_state(module, module.params)
module.exit_json(**results)
if __name__ == '__main__':

View file

@ -729,7 +729,6 @@ lib/ansible/modules/system/hostname.py
lib/ansible/modules/system/iptables.py
lib/ansible/modules/system/java_cert.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/lvg.py
lib/ansible/modules/system/lvol.py