Software source reference
"""
Contains script that tries to ensure that all USB connections are writable. By our configuration,
the script is run every 15 minutes.
Authors:
Min Tai Yap
"""
import os
import subprocess
from pathlib import Path
[docs]
def get_usb_mounts():
"""
Detect mounted removable devices (like USBs).
:returns: List of all removable mounted devices
"""
mounts = []
try:
output = subprocess.check_output(['lsblk', '-o', 'NAME,MOUNTPOINT,RM', '-nr'], text=True)
for line in output.strip().split('\n'):
parts = line.strip().split()
if len(parts) == 3:
name, mountpoint, removable = parts
mountpoint = mountpoint.encode('utf-8').decode('unicode_escape') # replace hex by ascii
if removable == '1' and mountpoint and Path(mountpoint).is_dir():
mounts.append((name, mountpoint))
except subprocess.CalledProcessError as e:
print(f"Error detecting USB devices: {e}")
return mounts
[docs]
def is_writable(mountpoint):
"""
Tests if a mount point is writable.
:param mountpoint: Path to the mount point
:returns: Boolean value whether the mount point is writable
"""
test_file = os.path.join(mountpoint, '.writetest.tmp')
try:
with open(test_file, 'w') as f:
f.write('test')
os.remove(test_file)
return True
except Exception as e:
print(f"Mount point {mountpoint} is not writable: {e}")
return False
[docs]
def remount_writable(mountpoint):
"""
Try to remount as read-write.
:param mountpoint: Path to the moint point
:returns: Boolean value whether the device with given mount point can be remounted
"""
try:
subprocess.check_call(['sudo', 'mount', '-o', 'remount,rw', mountpoint])
print(f"Remounted {mountpoint} as read-write.")
return True
except subprocess.CalledProcessError as e:
print(f"Remount failed: {e}")
return False
[docs]
def get_fs_type(device):
"""
Get the filesystem type of the device.
:param device: Device
:returns: Filesystem type of the device
"""
try:
output = subprocess.check_output(['lsblk', '-no', 'FSTYPE', f'/dev/{device}'], text=True)
return output.strip()
except subprocess.CalledProcessError as e:
print(f"Error getting filesystem type: {e}")
return None
[docs]
def remount_ntfs_rw(device, mountpoint):
"""
Try remounting NTFS with NTFS-3G.
:param device: Device
:param mountpoint: Mountpount of the device
:returns: Boolean value whether remounting with NTFS-3G was succesful
"""
try:
print("Trying to remount with ntfs-3g...")
subprocess.check_call(['sudo', 'umount', mountpoint])
subprocess.check_call(['sudo', 'mount', '-t', 'ntfs-3g', f'/dev/{device}', mountpoint])
print("Mounted NTFS using ntfs-3g.")
return True
except subprocess.CalledProcessError as e:
print(f"NTFS-3g remount failed: {e}")
return False
[docs]
def run_fsck(device):
"""
Run filesystem check and repair.
:param device: Device
:returns: Boolean value whether fsck was successful
"""
try:
print(f"Running fsck on /dev/{device}...")
subprocess.check_call(['sudo', 'umount', f'/dev/{device}'])
subprocess.check_call(['sudo', 'fsck', '-y', f'/dev/{device}'])
print("fsck completed.")
return True
except subprocess.CalledProcessError as e:
print(f"fsck failed: {e}")
return False
[docs]
def main():
"""
Checks if all mounted removable devices are writable. If that is not the case, the script
first tries to remount it. If the device is still not writable, it tries to remount
all NTFS devices with NTFS-3G. If it is still not writable or if the filesystem of the
device is not NTFS, it tries to run fsck on the device and remount it.
"""
usb_mounts = get_usb_mounts()
if not usb_mounts:
print("No USB devices detected.")
return
for device, mountpoint in usb_mounts:
print(f"\nChecking device /dev/{device} mounted at {mountpoint}")
if is_writable(mountpoint):
print(f"{mountpoint} is already writable.")
continue
print("Attempting remount...")
if remount_writable(mountpoint) and is_writable(mountpoint):
print(f"{mountpoint} is now writable after remount.")
continue
fs_type = get_fs_type(device)
print(f"Filesystem type: {fs_type}")
if fs_type == 'ntfs':
if remount_ntfs_rw(device, mountpoint) and is_writable(mountpoint):
print(f"{mountpoint} is now writable via ntfs-3g.")
continue
else:
print("ntfs-3g remount failed or still read-only.")
print("Trying fsck to repair possible file system issues...")
if run_fsck(device):
try:
subprocess.check_call(['sudo', 'mount', f'/dev/{device}', mountpoint])
if is_writable(mountpoint):
print(f"{mountpoint} is now writable after fsck.")
else:
print(f"{mountpoint} is still not writable after fsck.")
except subprocess.CalledProcessError:
print(f"Could not remount /dev/{device} after fsck.")
else:
print("fsck did not complete successfully.")
if __name__ == "__main__":
main()
