Skip to content

Instantly share code, notes, and snippets.

@khaotik
Created January 8, 2019 05:01
Show Gist options
  • Save khaotik/32af34c58f2c06d794d328706253eb0a to your computer and use it in GitHub Desktop.
Save khaotik/32af34c58f2c06d794d328706253eb0a to your computer and use it in GitHub Desktop.
ezumount - easily unmount and power off plugged USB disks from linux CLI
#!/usr/bin/env python3
import os
import sys
import subprocess as subp
if len(sys.argv) != 2:
appname = sys.argv[0]
print('%s - unmount USB directory and power it off' % appname, file=sys.stderr)
print('Usage: %s <directory>' % appname, file=sys.stderr)
sys.exit(-1)
lines = subp.getoutput('df').splitlines()[1:]
mountpt_to_dev_map = {}
for l in lines:
device, _1, _2, _3, _4, mountdst = l.split()
mountpt_to_dev_map[mountdst] = device
dstdir = os.path.abspath(sys.argv[1])
srcdev = mountpt_to_dev_map.get(dstdir)
if srcdev is None:
print('Directory %s is not a mount point' % dstdir, file=sys.stderr)
sys.exit(-1)
i = 0
while i<len(srcdev) and srcdev[-i-1].isdigit():
i += 1
maindev = srcdev[:(len(srcdev)-i)]
all_mountpts = [m for m,d in mountpt_to_dev_map.items() if d.startswith(maindev)]
for m in all_mountpts:
code, out = subp.getstatusoutput("sudo umount '%s'" % m)
if out:
print(out)
if code != 0:
print('Failed to unmount %s (%d)'%(m, code), file=sys.stderr)
sys.exit(code)
code, out = subp.getstatusoutput("sudo udisksctl power-off -b '%s'" % maindev)
if out:
print(out)
if code != 0:
print('Failed to poweroff %s (%d)'%(maindev, code), file=sys.stderr)
sys.exit(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment