Disable unused USB devices in Ubuntu

Sadly Ubuntu does not yet support the multitouch screen and fingerprint reader of my notebook. I also hardly use my webcam. That is why I decided to disable the devices to save energy.

I put together a small PHP which I called “unbindUsb” script that can be run in the command line to enable/disable the devices. As root run:

# unbindUsb unbind
# unbindUsb bind

If no parameter is given the default behavior is to unbind the devices.

Source code:

#!/bin/php
<?php

    $devices = [
        'Raydium Touch System',
        'EgisTec Touch Fingerprint Sensor',
        'HD WebCam',
    ];
    $defaultCmd = 'unbind';


    if(isset($argv) && is_array($argv)) {
        $usbCommand = $defaultCmd;
        if(isset($argv[1])) {
            $argvCmd = trim(htmlspecialchars(strtolower($argv[1])));
            if(in_array($argvCmd, ['bind', 'unbind'])) {
                $usbCommand = $argvCmd;
            }
        }

        if($filePaths = glob('/sys/bus/usb/devices/*/product')) {
            foreach($filePaths as $filePath) {
                $deviceName = trim(file_get_contents($filePath));
                foreach($devices as $device) {
                    if(strstr($deviceName, $device)) {
                        echo $usbCommand.' '.$deviceName."\n";
                        $deviceId = false;
                        $match = [];
                        if(preg_match('/^\/sys\/bus\/usb\/devices\/([^\/]+)/', $filePath, $match)) {
                            $deviceId = $match[1];

                        }
                        $cmd = "echo '".$deviceId."' | tee /sys/bus/usb/drivers/usb/".$usbCommand;
                        exec($cmd);
                        echo "\n";
                        break;
                    }
                }
            }
        }
    }

Inspiration: https://karlcode.owtelse.com/blog/2017/01/09/disabling-usb-ports-on-linux/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.