From fee4c24ad456020db4397d090509da5b96a227a2 Mon Sep 17 00:00:00 2001 From: Trishna Guha Date: Mon, 30 Jul 2018 20:42:47 +0530 Subject: [PATCH] Add md5sum check in nxos_file_copy module (#43423) * Add md5sum check in nxos_file_copy module Signed-off-by: Trishna Guha * address review comment Signed-off-by: Trishna Guha --- .../modules/network/nxos/nxos_file_copy.py | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/ansible/modules/network/nxos/nxos_file_copy.py b/lib/ansible/modules/network/nxos/nxos_file_copy.py index 7a4acf1b64..000da54a0d 100644 --- a/lib/ansible/modules/network/nxos/nxos_file_copy.py +++ b/lib/ansible/modules/network/nxos/nxos_file_copy.py @@ -146,6 +146,7 @@ remote_file: sample: '/path/to/remote/file' ''' +import hashlib import os import re import time @@ -154,7 +155,7 @@ import traceback from ansible.module_utils.network.nxos.nxos import run_commands from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils._text import to_native, to_text +from ansible.module_utils._text import to_native, to_text, to_bytes try: import paramiko @@ -175,12 +176,34 @@ except ImportError: HAS_PEXPECT = False +def md5sum_check(module, dst, file_system): + command = 'show file {0}{1} md5sum'.format(file_system, dst) + remote_filehash = run_commands(module, {'command': command, 'output': 'text'})[0] + remote_filehash = to_bytes(remote_filehash, errors='surrogate_or_strict') + + local_file = module.params['local_file'] + try: + with open(local_file, 'r') as f: + filecontent = f.read() + except (OSError, IOError) as exc: + module.fail_json(msg="Error reading the file: %s" % to_text(exc)) + + filecontent = to_bytes(filecontent, errors='surrogate_or_strict') + local_filehash = hashlib.md5(filecontent).hexdigest() + + if local_filehash == remote_filehash: + return True + else: + return False + + def remote_file_exists(module, dst, file_system='bootflash:'): command = 'dir {0}/{1}'.format(file_system, dst) body = run_commands(module, {'command': command, 'output': 'text'})[0] if 'No such file' in body: return False - return True + else: + return md5sum_check(module, dst, file_system) def verify_remote_file_exists(module, dst, file_system='bootflash:'):