Skip to content

Instantly share code, notes, and snippets.

@Lvl4Sword
Last active October 4, 2018 23:12
Show Gist options
  • Save Lvl4Sword/f032d7814dc9ddc131ced3179e8235fe to your computer and use it in GitHub Desktop.
Save Lvl4Sword/f032d7814dc9ddc131ced3179e8235fe to your computer and use it in GitHub Desktop.
Detect Ethernet, Wireless, Battery, and Main Power Supply, within Linux.
#!/usr/bin/env python3
import os
ethernet_interfaces = []
wireless_interfaces = []
def get_interfaces():
interfaces = os.listdir('/sys/class/net')
return interfaces
def get_power():
power_supplies = os.listdir('/sys/class/power_supply')
return power_supplies
def get_ac(power_supplies):
for each in power_supplies:
with open('/sys/class/power_supply/{0}/type'.format(each), 'r') as ac_file:
for line in ac_file:
if line.strip() == 'Mains':
return each
def get_battery(power_supplies):
for each in power_supplies:
with open('/sys/class/power_supply/{0}/type'.format(each), 'r') as ac_file:
for line in ac_file:
if line.strip() == 'Battery':
return each
def detect_virtual_interfaces(interfaces):
for each in interfaces:
real_path = os.path.realpath(os.path.join('/sys/class/net/', each))
if '/devices/virtual/net/' in real_path:
interfaces.remove(each)
return interfaces
def detect_ethernet(clean_interfaces):
for each in clean_interfaces:
try:
with open('/sys/class/net/{0}/speed'.format(each), 'r') as speed_file:
for line in speed_file:
ethernet_interfaces.append(each)
except OSError:
pass
def detect_wireless(clean_interfaces):
for each in clean_interfaces:
if os.path.isdir('/sys/class/net/{0}/wireless'.format(each)):
wireless_interfaces.append(each)
if __name__ == '__main__':
interfaces = get_interfaces()
clean_interfaces = detect_virtual_interfaces(interfaces)
detect_ethernet(clean_interfaces)
if not ethernet_interfaces:
print('No ethernet detected!')
else:
print('Ethernet:', ', '.join(ethernet_interfaces))
detect_wireless(clean_interfaces)
if not wireless_interfaces:
print('No wireless detected!')
else:
print('Wireless:', ', '.join(wireless_interfaces))
power_supplies = get_power()
main_power_supply = get_ac(power_supplies)
battery = get_battery(power_supplies)
if not main_power_supply and battery:
print('Battery: {0}'.format(battery))
elif main_power_supply and battery:
print('Power Supply: {0}'.format(main_power_supply))
print('Battery: {0}'.format(battery))
elif main_power_supply and not battery:
print('Power Supply: {0}'.format(main_power_supply))
elif not main_power_supply and not battery:
print('This shouldn\'t happen.')
print('No power supply detected, no battery detected.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment