Example #1
0
 def get_connection() -> Connection:
     """Set up a connection."""
     if entry.options.get(CONF_UNAUTHENTICATED_MODE):
         _LOGGER.debug("Connecting in unauthenticated mode, reduced feature set")
         connection = Connection(url, timeout=CONNECTION_TIMEOUT)
     else:
         _LOGGER.debug("Connecting in authenticated mode, full feature set")
         username = entry.data.get(CONF_USERNAME) or ""
         password = entry.data.get(CONF_PASSWORD) or ""
         connection = Connection(
             url, username=username, password=password, timeout=CONNECTION_TIMEOUT
         )
     return connection
Example #2
0
 def try_connect(username: Optional[str],
                 password: Optional[str]) -> Connection:
     """Try connecting with given credentials."""
     if username or password:
         conn = AuthorizedConnection(
             user_input[CONF_URL],
             username=username,
             password=password,
             timeout=CONNECTION_TIMEOUT,
         )
     else:
         try:
             conn = AuthorizedConnection(
                 user_input[CONF_URL],
                 username="",
                 password="",
                 timeout=CONNECTION_TIMEOUT,
             )
             user_input[CONF_USERNAME] = ""
             user_input[CONF_PASSWORD] = ""
         except ResponseErrorException:
             _LOGGER.debug(
                 "Could not login with empty credentials, proceeding unauthenticated",
                 exc_info=True,
             )
             conn = Connection(user_input[CONF_URL],
                               timeout=CONNECTION_TIMEOUT)
             del user_input[CONF_USERNAME]
             del user_input[CONF_PASSWORD]
     return conn
Example #3
0
 def try_connect(user_input: dict[str, Any]) -> Connection:
     """Try connecting with given credentials."""
     username = user_input.get(CONF_USERNAME) or ""
     password = user_input.get(CONF_PASSWORD) or ""
     conn = Connection(
         user_input[CONF_URL],
         username=username,
         password=password,
         timeout=CONNECTION_TIMEOUT,
     )
     return conn
Example #4
0
    def get_connection() -> Connection:
        """
        Set up a connection.

        Authorized one if username/pass specified (even if empty), unauthorized one otherwise.
        """
        username = config_entry.data.get(CONF_USERNAME)
        password = config_entry.data.get(CONF_PASSWORD)
        if username or password:
            connection: Connection = AuthorizedConnection(
                url, username=username, password=password, timeout=CONNECTION_TIMEOUT
            )
        else:
            connection = Connection(url, timeout=CONNECTION_TIMEOUT)
        return connection
Example #5
0
def scrape():
    trying = True
    while trying is True:
        try:
            connection = Connection('http://192.168.8.1/')  #Router IP
            client = Client(connection)
            dicto = client.device.signal()
            global rs
            rssi = dicto["rssi"]
            r = re.findall(r'\d+', rssi)[0]
            rs = int(r)
            trying = False
            return rs
        except:
            pass
Example #6
0
def main():
    banner()
    ### Command line -helper for args
    import argparse
    parser = argparse.ArgumentParser(description="Huawei B315s-22 4G router information gathering tool")
    parser.add_argument("-i", "--ip", type=str, help="IP address of the router", metavar=("IP Router"))
    parser.add_argument("-n", "--nologin", action='store_true', help="Use this if you don't have any credentials")
    parser.add_argument("-u", "--username", type=str, default="admin", help="Username used to login to the router, default=admin")
    parser.add_argument("-p", "--password", type=str, default="admin", help="Password used to login to the router, default=admin")
    parser.add_argument("-w", "--write", type=str, help="Filename", metavar=("FILENAME"))
    args = parser.parse_args()

    #Check if atleast the ip address is given
    if args.ip == None:
        parser.print_usage()
    elif valid_ip(args.ip) == False:
        sys.exit("Enter a valid IP address")

    if args.nologin == True:
        try:
            connection = Connection('http://192.168.8.1/')
            client = Client(connection)
            data = getAllInfoWithoutLogin(client)
            if args.write:
                print("Data has been written into : " + args.write + "\n")
                writeToFile(args.write, data)
            else:
                print(data)
        except Exception as e:
            print(e)
    
    if args.username == True and args.password == True:
        try:
            connection = AuthorizedConnection('http://'+args.username+':'+args.password+'@'+args.ip+'/')
            client = Client(connection)
            data = getAllInfoLogin(client)
            if args.write:
                print("Data has been written into : " + args.write + "\n")
                writeToFile(args.write, data)
            else:
                print(data)
        except Exception as e:
            print(e)
#!/usr/bin/env python3
"""
Example code on how to ignore SSL checks to accept expired or self signed SSL certs, you can try it by running:
python3 ignore_ssl_check.py http://admin:[email protected]/
"""
from argparse import ArgumentParser

import requests

from huawei_lte_api.Client import Client
from huawei_lte_api.Connection import Connection

parser = ArgumentParser()
parser.add_argument('url', type=str)
parser.add_argument('--username', type=str)
parser.add_argument('--password', type=str)
args = parser.parse_args()

# Create custom requests.Session
my_custom_session = requests.Session()
# Disable SSL verify
my_custom_session.verify = False

with Connection(args.url,
                username=args.username,
                password=args.password,
                requests_session=my_custom_session) as connection:
    client = Client(connection)
    print(client.device.information())
Example #8
0
#!/usr/bin/env python3
"""
Example code on how to send a SMS, you can try it by running:
python3 send_sms.py http://admin:[email protected]/ +420123456789 "Hello world"
"""
from argparse import ArgumentParser
from huawei_lte_api.Connection import Connection
from huawei_lte_api.Client import Client


parser = ArgumentParser()
parser.add_argument('url', type=str)
parser.add_argument('phone_number', type=str)
parser.add_argument('message', type=str)
parser.add_argument('--username', type=str)
parser.add_argument('--password', type=str)
args = parser.parse_args()

with Connection(args.url, username=args.username, password=args.password) as connection:
    client = Client(connection)
    if client.sms.send_sms([args.phone_number], args.message) == 'OK':
        print('SMS was send successfully')
    else:
        print('Error')
Example #9
0
def test_connection_wrong_url():
    with pytest.raises(Exception):
        Connection('http://localhost')
Example #10
0
import sys
from typing import Any, Callable
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))

from huawei_lte_api.AuthorizedConnection import AuthorizedConnection
from huawei_lte_api.Client import Client
from huawei_lte_api.Connection import Connection

parser = ArgumentParser()
parser.add_argument('url', type=str)
parser.add_argument('--username', type=str)
parser.add_argument('--password', type=str)
args = parser.parse_args()

if args.username is None:
    connection = Connection(args.url)
else:
    connection = AuthorizedConnection(args.url,
                                      username=args.username,
                                      password=args.password)

client = Client(connection)


def dump(method: Callable[[], Any]) -> None:
    print("==== %s" % method)
    try:
        pprint.pprint(method())
    except Exception as e:
        print(str(e))
    print("")
Example #11
0
#!/usr/bin/env python3

import http.client
from huawei_lte_api.AuthorizedConnection import AuthorizedConnection
from huawei_lte_api.Connection import Connection
from huawei_lte_api.Client import Client

URL = "http://192.168.8.1/"
USERNAME = "******"
PASSWORD = "******"
CONNECTION_TIMEOUT = 10

http.client.HTTPConnection.debuglevel = 1

if USERNAME or PASSWORD:
    connection = AuthorizedConnection(URL,
                                      username=USERNAME,
                                      password=PASSWORD,
                                      timeout=CONNECTION_TIMEOUT)
else:
    connection = Connection(URL, timeout=CONNECTION_TIMEOUT)

if isinstance(connection, AuthorizedConnection):
    print(Client(connection).device.information())
    Client(connection).user.logout()
Example #12
0
from huawei_lte_api.Client import Client
from huawei_lte_api.AuthorizedConnection import AuthorizedConnection
from huawei_lte_api.Connection import Connection
from pprint import pprint

connection = Connection('http://192.168.8.1/')
client = Client(connection)

pprint(client.device.signal())
Example #13
0
    def run(self):
        # Initialize

        # ... arguments
        try:
            self.__oArguments = self.__oArgumentParser.parse_args()
        except Exception as e:
            logger.error(f"Failed to parse arguments; {str(e)}")
            return errno.EINVAL

        # ... verbosity
        if self.__oArguments.debug:
            logger.setLevel(logging.DEBUG)

        # ... configuration
        try:
            self.__dConfig = HuaweiHilink_Config.load(self.__oArguments.config)
        except Exception as e:
            logger.error(f"Failed to load configuration; {str(e)}")
            return errno.EINVAL

        # Category
        sCategory = self.__oArguments.category
        dCategory = HUAWEI_HILINK_API[sCategory]
        dCommands = dCategory["commands"]

        # ... help
        if self.__oArguments.command == "help":
            print(f"{sCategory}")
            for sCommand, dCommand in dCommands.items():
                sHelp = dCommand.get("help")
                print(f"  {sCommand}: {sHelp}"
                      if sHelp is not None else f"  {sCommand}")
                dArguments = dCommand.get("uargs", {})
                for sFunctionArg, sUserArg in dArguments.items():
                    print(f"    --{sUserArg} <{sFunctionArg}>")
            return 0

        # ... command
        sCommand = self.__oArguments.command
        if sCommand not in dCommands:
            logging.error(f"Invalid command ({sCategory}:{sCommand})")
            return errno.EINVAL

        # API

        # ... connection
        sScheme = "https" if self.__dConfig["ssl"] else "http"
        sEndpoint = self.__dConfig["endpoint"]
        try:
            if len(self.__dConfig["password"]):
                oConnection = AuthorizedConnection(
                    f"{sScheme}://{sEndpoint}/",
                    username=self.__dConfig["username"],
                    password=self.__dConfig["password"],
                )
            else:
                oConnection = Connection(f"{sScheme}://{sEndpoint}/")
        except Exception as e:
            logger.error(
                f"Failed to connect to endpoint ({sScheme}://{sEndpoint}/); {str(e)}"
            )
            return errno.EFAULT

        # ... class (category)
        try:
            sClass = dCategory["class"]
            cClass = getattr(
                __import__(f"huawei_lte_api.api.{sClass}",
                           fromlist=["huawei_lte_api.api"]),
                sClass,
            )
        except Exception as e:
            logger.error(f"Failed to load API class ({sCategory}); {str(e)}")
            return errno.EFAULT
        oCategory = cClass(oConnection)

        # ... method (command)
        dCommand = dCommands[sCommand]
        try:
            sMethod = dCommand["method"]
            fMethod = getattr(oCategory, sMethod)
            dArguments = {}
            for sFunctionArg, sSystemArg in dCommand.get("sargs", {}).items():
                dArguments[sFunctionArg] = sSystemArg
            for sFunctionArg, sUserArg in dCommand.get("uargs", {}).items():
                if hasattr(self.__oArguments, sUserArg):
                    dArguments[sFunctionArg] = getattr(self.__oArguments,
                                                       sUserArg)
                elif sUserArg in self.__dConfig:
                    dArguments[sFunctionArg] = self.__dConfig[sUserArg]
                else:
                    logger.error(
                        f"Invalid command argument ({sCategory}:{sCommand}:{sFunctionArg})"
                    )
                    return errno.EFAULT
                if dArguments[sFunctionArg] is None:
                    logger.error(
                        f"Missing command argument ({sCategory}:{sCommand}: --{sUserArg})"
                    )
                    return errno.EINVAL
            logger.debug(
                f"Calling API method: huawei_lte_api.api.{sClass}.{sMethod}({dArguments})"
            )
            dOutput = fMethod(**dArguments)
        except Exception as e:
            logger.error(
                f"Failed to execute API method ({sCategory}:{sCommand}); {str(e)}"
            )
            return errno.EFAULT

        # ... output
        if self.__oArguments.field is not None:
            sField = self.__oArguments.field
            if sField in dOutput:
                print(dOutput[self.__oArguments.field])
            else:
                logger.warning(
                    f"Command output has no such field ({sCategory}:{sCommand} -> {sField})"
                )
        else:
            print(json.dumps(dOutput, sort_keys=True, indent=2))

        # ... logout
        if isinstance(oConnection,
                      AuthorizedConnection) and oConnection.logged_in:
            oConnection.user.logout()
from huawei_lte_api.Client import Client
from huawei_lte_api.AuthorizedConnection import AuthorizedConnection
from huawei_lte_api.Connection import Connection

connection = Connection('http://192.168.8.1/') # For limited access, I have valid credentials no need for limited access
# connection = AuthorizedConnection('http://*****:*****@192.168.8.1/', login_on_demand=True)
# If you wish to login on demand (when call requires authorization), pass login_on_demand=True
# connection = AuthorizedConnection('http://*****:*****@192.168.8.1/')

client = Client(connection)
# This just simplifies access to separate API groups, you can use device = Device(connection) if you want

print(client.device.signal())  # Can be accessed without authorization
#print(client.device.information())
# Needs valid authorization, will throw exception if invalid credentials are passed in URL