Last active
April 27, 2022 23:53
-
-
Save in03/05bacdef6a24ca9000b14a6f10a31006 to your computer and use it in GitHub Desktop.
Resolve cross-platform network paths from local mapped mounts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import os | |
import pathlib | |
import socket | |
def resolve_network_path(local_path, strict=True): | |
""" | |
Resolve cross-platform network paths from local mapped mounts | |
Args: | |
- local_path (str): local path to resolve | |
- strict (bool): return None for unresolvable path or re-return local_path | |
""" | |
abspath = pathlib.Path(local_path).resolve() | |
try: | |
# First two segments will be leading slashes | |
path_segs = str(abspath).split(os.path.sep) | |
ip = path_segs[2] | |
hostname = socket.gethostbyaddr(ip)[0] | |
except IndexError or socket.gaierror as e: | |
error_msg = f"Path is not a network location or IP unresolvable\n{e}" | |
if strict: | |
logging.error(error_msg) | |
return None | |
else: | |
logging.debug(error_msg) | |
return local_path | |
else: | |
# Substitute hostname | |
path_segs[2] = hostname | |
return os.path.sep.join(path_segs) | |
if __name__ == "__main__": | |
answer = input("Enter a network drive path:\n") | |
resolve_network_path(answer, strict=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment