Friday, August 16, 2024

Enable and Disable USB support on Linux servers without reboot

 Hello Guys,

In past couple of weeks i was working on a small project with very specific objective where i need to enable and disable the usb support on linux based edge device. I have use raspberry pi 4 as i don't have any  other supported industrial controller with me.

I have started with installing the default available os on the rasberry pi and i was able to login on the system which looks like 


after doing it i need to enable and disable the usb support on lets say hundreds of devices so its automation is the way cant do it manually at the same time i need to make sure that system should not required reboot other wise it will beat the purpose. so i can not go with conventional way of disabling the usb support at kernel level.

so after much google i have come across a utility in linux called usbguard which can be helpful. once the approach is finalised then i have moved into the  write a playbook the playbook looks as 


---

- name: enable disable USB

  hosts: "{{target}}"

  become: true

  vars:

    enable_usb: allow


  tasks:

    - name: Install usb guard on redhat family os

      ansible.builtin.yum:

        name: usbguard

        state: present

      when: ansible_facts['os_family'] == 'RedHat'


    - name: Install usb guard on others

      ansible.builtin.apt:

        name: usbguard

        state: present

      when: ansible_facts['os_family'] == 'Debian'


    - name: Install usb guard on the edge devices

      ansible.builtin.template:

        src: usbguard-daemon.conf.j2

        dest:  /etc/usbguard/usbguard-daemon.conf

        owner: root

        group: root

        mode: '0600'


    - name: restart usb guard service to {{ enable_usb }}

      ansible.builtin.service:

        name: usbguard

        state: restarted

        enabled: true

and template look like 

RuleFile=/etc/usbguard/rules.conf


RuleFolder=/etc/usbguard/rules.d/


ImplicitPolicyTarget={{ enable_usb }}


PresentDevicePolicy={{ enable_usb}}


PresentControllerPolicy={{enable_usb}}


InsertedDevicePolicy=apply-policy



RestoreControllerDeviceState=false


DeviceManagerBackend=uevent



IPCAllowedUsers=root


IPCAllowedGroups=wheel


IPCAccessControlFiles=/etc/usbguard/IPCAccessControl.d/


DeviceRulesWithPort=false


AuditBackend=FileAudit


AuditFilePath=/var/log/usbguard/usbguard-audit.log



using above automation i can enable and disable the usb support with the redhat aap with a one click


with This one job i can get my job done

No comments:

Post a Comment