Created
November 30, 2025 21:44
-
-
Save xanarin/004c9ec8d8f7e4e1d3dabf8934d33787 to your computer and use it in GitHub Desktop.
Script to (un)mount SMB shares using GVFS and gnome keychain instead of kernel CIFS driver
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
| #!/usr/bin/python3 | |
| import argparse | |
| from typing import Set | |
| import subprocess | |
| import sys | |
| COMMON_SHARES = [ | |
| "Share1", | |
| "Share2", | |
| ] | |
| REMAINING_SHARES = [ | |
| "Share3", | |
| "Share4", | |
| "Share5", | |
| ] | |
| SHARE_CONNECT_STR = "smb://DOMAIN;USERNAME@nas.ext.com/" | |
| def get_current_gvfs_mounts() -> Set[str]: | |
| result = subprocess.run(["gio", "mount", "--list"], check=True, capture_output=True) | |
| mount_lines = [l for l in result.stdout.decode().splitlines() if l.startswith("Mount(")] | |
| return {s.split()[1] for s in mount_lines} | |
| def parse_args(): | |
| parser = argparse.ArgumentParser("Script to mount and unmount NAS CIFS shares using GVFS") | |
| parser.add_argument("-u", "--unmount", action="store_true", help="Unmount the shares (implies --all)") | |
| parser.add_argument("-a", "--all", action="store_true", help="Mount ALL shares, not just the commonly-used ones") | |
| return parser.parse_args() | |
| def main(): | |
| args = parse_args() | |
| current_mounts = get_current_gvfs_mounts() | |
| # GVFS works with all lowercase names | |
| operating_set = {s.lower() for s in COMMON_SHARES} | |
| if args.all or args.unmount: | |
| operating_set = operating_set.union({s.lower() for s in REMAINING_SHARES}) | |
| extra_args = [] | |
| if args.unmount: | |
| extra_args = "--unmount" | |
| operating_set = operating_set.intersection(current_mounts) | |
| if operating_set: | |
| print(f"The following shares will be unmounted:\n {'\n '.join(operating_set)}\n") | |
| else: | |
| print("No shares need to be unmounted") | |
| return 0 | |
| else: | |
| operating_set = operating_set.difference(current_mounts) | |
| print(f"The following shares will be mounted:\n {'\n '.join(operating_set)}\n") | |
| args = ["gio", "mount"] | |
| if extra_args: | |
| args.append(extra_args) | |
| for mount in operating_set: | |
| inner_args = args + [f"{SHARE_CONNECT_STR}{mount}"] | |
| subprocess.run(inner_args, check=True, capture_output=False) | |
| shares_now = get_current_gvfs_mounts() | |
| if not shares_now: | |
| print("All shares unmounted") | |
| else: | |
| print(f"Mounted shares:\n {'\n '.join(shares_now)}") | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment