Created
November 11, 2017 23:31
-
-
Save slobdell/7d052e01fed005f387b1c8e4994cd6d1 to your computer and use it in GitHub Desktop.
Automatically mount USB drive in python script
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 commands | |
# ASSUMED THAT THIS COMMAND HAS ALREADY BEEN RUN | |
# sudo mkdir /mnt/usb_stick | |
MOUNT_DIR = "/mnt/usb_stick" | |
def run_command(command): | |
# start = time.time() | |
ret_code, output = commands.getstatusoutput(command) | |
if ret_code == 1: | |
raise Exception("FAILED: %s" % command) | |
# end = time.time() | |
# print "Finished in %s seconds" % (end - start) | |
return output.splitlines() | |
def uuid_from_line(line): | |
start_str = "UUID=\"" | |
example_uuid = "6784-3407" | |
uuid_start = line.index(start_str) + len(start_str) | |
uuid_end = uuid_start + len(example_uuid) | |
return line[uuid_start: uuid_end] | |
output = run_command("blkid | grep LABEL | grep -v boot") | |
# ['/dev/sda1: LABEL="KINGSTON" UUID="6784-3407" TYPE="vfat" PARTUUID="459720e1-01"'] | |
for usb_device in output: | |
command = "mount --uuid %s %s" % (uuid_from_line(usb_device), MOUNT_DIR) | |
run_command(command) | |
break |
Thanks for this code man!!! Im working on a project to use USB as a syncronization medium between two RaspberryPi NAS servers. Im looking to not use the internet to sync them due to Data cap on the internet transfer for one of the locations.
Ill be sure to reference your code in my GitHub Project!
Hello, I also want to mount the USB automatically but in this code, I m getting stuck at line number 25, run_command need an attribute.. klindly explain me that line or help in this regard. thanks in advance
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fantastic code!!!!!! Congrats.