Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New int cmds #18

Merged
merged 12 commits into from Jan 15, 2022
2 changes: 1 addition & 1 deletion chatbot/__version__.py
Expand Up @@ -15,5 +15,5 @@
__url__ = "https://github.com/wlan-pi/wlanpi-chat-bot"
__author__ = "Nigel Bowden"
__author_email__ = "wifinigel@gmail.com"
__version__ = "1.0.11"
__version__ = "1.0.12"
__license__ = "MIT"
3 changes: 1 addition & 2 deletions chatbot/chatbot.py
Expand Up @@ -286,8 +286,7 @@ def main():
# slice out the last msg (in the case of multipe msgs being sent)
update = updates["result"][-1]

script_logger.debug("Dump of received update:")
script_logger.debug(pprint(update))
script_logger.debug(f"Dump of received update: {update}")

# extract the message text
if "message" in update.keys():
Expand Down
3 changes: 3 additions & 0 deletions chatbot/py_commands/command.py
Expand Up @@ -127,12 +127,15 @@ def help(self):
#from .reboot import Reboot
#from .set_display_mode import SetDisplayMode
#from .set_display_width import SetDisplayWidth
from .show_eth0_ip import ShowEth0Ip
from .show_interfaces import ShowInterfaces
from .show_mode import ShowMode
from .show_status import ShowStatus
from .show_summary import ShowSummary
from .show_time import ShowTime
from .show_uptime import ShowUptime
from .show_version import ShowVersion
from .show_wlaninterfaces import ShowWlanInterfaces
from .speedtest import Speedtest


Expand Down
47 changes: 47 additions & 0 deletions chatbot/py_commands/show_eth0_ip.py
@@ -0,0 +1,47 @@
import socket
import subprocess
import re

from .command import Command


class ShowEth0Ip(Command):
def __init__(self, telegram_object, conf_obj):
super().__init__(telegram_object, conf_obj)

self.command_name = "show_eth0-ip"


def run(self, args_list):

# Taken from FPMS...

'''
Return IP configuration of eth0 including IP, default gateway, DNS servers
'''
IPCONFIG_FILE = "/usr/bin/ipconfig"

eth0_ipconfig_info = []

try:
ipconfig_output = subprocess.check_output(IPCONFIG_FILE, shell=True).decode().strip()
ipconfig_info = ipconfig_output.split('\n')
except subprocess.CalledProcessError as exc:
output = exc.output.decode()
print("Err: ipconfig command error", output)
return

for n in ipconfig_info:
# do some cleanup
n = n.replace("DHCP server name", "DHCP")
n = n.replace("DHCP server address", "DHCP IP")
eth0_ipconfig_info.append(n)

if len(ipconfig_info) <= 1:
eth0_ipconfig_info = ["Eth0 is down or not connected."]

final_page = "Eth0 IP Config:\n\n"

final_page += "\n".join(eth0_ipconfig_info)

return self._render(final_page)
77 changes: 77 additions & 0 deletions chatbot/py_commands/show_interfaces.py
@@ -0,0 +1,77 @@
import socket
import subprocess
import re

from .command import Command


class ShowInterfaces(Command):
def __init__(self, telegram_object, conf_obj):
super().__init__(telegram_object, conf_obj)

self.command_name = "show_interfaces"


def run(self, args_list):

# Taken from FPMS...

'''
Return the list of network interfaces with IP address (if available)
'''
IFCONFIG_FILE = "/usr/sbin/ifconfig"
IW_FILE = "/usr/sbin/iw"

try:
ifconfig_info = subprocess.check_output(f"{IFCONFIG_FILE} -a", shell=True).decode()
except Exception as ex:
print("Err: ifconfig error", str(ex))
return

# Extract interface info with a bit of regex magic
interface_re = re.findall(
r'^(\w+?)\: flags(.*?)RX packets', ifconfig_info, re.DOTALL | re.MULTILINE)
if interface_re is None:
# Something broke is our regex - report an issue
print("Error: match error")
else:
interfaces = []
for result in interface_re:

# save the interface name
interface_name = result[0]

# look at the rest of the interface info & extract IP if available
interface_info = result[1]

# determine interface status
status = "▲" if re.search("UP", interface_info, re.MULTILINE) is not None else "▽"

# determine IP address
inet_search = re.search(
"inet (.+?) ", interface_info, re.MULTILINE)
if inet_search is None:
ip_address = "-"

# do check if this is an interface in monitor mode
if (re.search(r"(wlan\d+)|(mon\d+)", interface_name, re.MULTILINE)):

# fire up 'iw' for this interface (hmmm..is this a bit of an un-necessary ovehead?)
try:
iw_info = subprocess.check_output('{} {} info'.format(IW_FILE, interface_name), shell=True).decode()

if re.search("type monitor", iw_info, re.MULTILINE):
ip_address = "Monitor"
except:
ip_address = "-"
else:
ip_address = inet_search.group(1)

# format interface info
interfaces.append('{} {} : {}'.format(status, interface_name, ip_address))

final_page = "Interfaces:\n\n"

final_page += "\n".join(interfaces)

return self._render(final_page)
105 changes: 105 additions & 0 deletions chatbot/py_commands/show_wlaninterfaces.py
@@ -0,0 +1,105 @@
import socket
import subprocess
import re

from .command import Command


class ShowWlanInterfaces(Command):
def __init__(self, telegram_object, conf_obj):
super().__init__(telegram_object, conf_obj)

self.command_name = "show_wlan-interfaces"

def channel_lookup(self, freq_mhz):
'''
Converts frequency (MHz) to channel number
'''
if freq_mhz == 2484:
return 14
elif freq_mhz >= 2412 and freq_mhz <= 2484:
return int(((freq_mhz - 2412) / 5) + 1)
elif freq_mhz >= 5160 and freq_mhz <= 5885:
return int(((freq_mhz - 5180) / 5) + 36)
elif freq_mhz >= 5955 and freq_mhz <= 7115:
return int(((freq_mhz - 5955) / 5) + 1)

return None

def run(self, args_list):

# Taken from FPMS...

'''
Create pages to summarise WLAN interface info
'''
IWCONFIG_FILE = "/usr/sbin/iwconfig"
IW_FILE = "/usr/sbin/iw"
ETHTOOL_FILE = "/usr/sbin/ethtool"

interfaces = []
pages = []

try:
interfaces = subprocess.check_output(f"{IWCONFIG_FILE} 2>&1 | grep 802.11" + "| awk '{ print $1 }'", shell=True).decode().strip().split()
except Exception as e:
print(e)

for interface in interfaces:
page = []
page.append(f"Interface: {interface}")

# Driver
try:
ethtool_output = subprocess.check_output(f"{ETHTOOL_FILE} -i {interface}", shell=True).decode().strip()
driver = re.search(".*driver:\s+(.*)", ethtool_output).group(1)
page.append(f"Driver: {driver}")
except subprocess.CalledProcessError as exc:
output = exc.ethtool_output.decode()
print(output)

# Addr, SSID, Mode, Channel
try:
iw_output = subprocess.check_output(f"{IW_FILE} {interface} info", shell=True).decode().strip()
except subprocess.CalledProcessError as exc:
output = exc.iw_output.decode()
print(output)

# Addr
try:
addr = re.search(".*addr\s+(.*)", iw_output).group(1).replace(":", "").upper()
page.append(f"Addr: {addr}")
except Exception:
pass

# Mode
try:
mode = re.search(".*type\s+(.*)", iw_output).group(1)
page.append(f"Mode: {mode.capitalize() if not mode.isupper() else mode}")
except Exception:
pass

# SSID
try:
ssid = re.search(".*ssid\s+(.*)", iw_output).group(1)
page.append(f"SSID: {ssid}")
except Exception:
pass

# Frequency
try:
freq = int(re.search(".*\(([0-9]+)\s+MHz\).*", iw_output).group(1))
channel = self.channel_lookup(freq)
page.append(f"Freq (MHz): {freq}")
page.append(f"Channel: {channel}")
except Exception:
pass

pages.append(page)

final_page = "WLAN Interfaces:\n\n"

for page in pages:
final_page += "\n".join(page) + "\n\n"

return self._render(final_page)
6 changes: 6 additions & 0 deletions debian/changelog
@@ -1,3 +1,9 @@
wlanpi-chat-bot (1.0.12) unstable; urgency=medium

* Add 3 new interface cmds from FPMS (interfaces, wlan interfaces, eth0)

-- Nigel Bowden <wifinigel@gmail.com> Sat, 15 Jan 2022 20:27:10 +0600

wlanpi-chat-bot (1.0.11) unstable; urgency=medium

* Remove all cmds that takes args & ensure all show commands work under new priv escalation restrictions
Expand Down