def is_ssh_enabled(): """API called to execute commands to check if SSH is enabled. This will populate the ssh enabled radio button in the UI. Returns: dict: Execution status if the API call was successful, flag to indicate if ssh is enabled and with error reason if call fails. """ webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info("Providing ssh enabled as response") try: # Check SSH status if utility.execute("/bin/systemctl --no-pager status ssh", shlex_split=True)[1].find("active (running)") > -1: # Check UFW status stdout = utility.execute("/usr/sbin/ufw status", shlex_split=True)[1] if re.search("22.*ALLOW", stdout): return jsonify(success=True, isSshEnabled=True, reason="Ssh is enabled.") else: return jsonify(success=True, isSshEnabled=False, reason="Ssh not enabled.") else: return jsonify(success=True, isSshEnabled=False, reason="Ssh not enabled.") except Exception as ex: webserver_node.get_logger().error( f"Failed check if ssh is enabled: {ex}") return jsonify(success=False, isSshEnabled=False, reason="Error")
def ssh_reset(): """API called to execute commands to reset the ssh password with the new one. Returns: dict: Execution status if the API call was successful and with error reason if failed. """ webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info( "User requesting for resetting the ssh credentials") try: old_ssh_password = request.json["oldPassword"] new_ssh_password = request.json["newPassword"] # Check if old password is correct if not pam.pam().authenticate(DEFAULT_USER, old_ssh_password): return jsonify(success=False, reason="The password is incorrect. " "Provide your current password.") # Check if the default password is updated passwd_status_cmd = f"/usr/bin/passwd --status {DEFAULT_USER}" passwd_status_output = utility.execute(passwd_status_cmd, shlex_split=True)[1] # Execute passwd command based on the status of the password obtained above if passwd_status_output.split()[1] == "P": webserver_node.get_logger().info("Usable Password present") if (utility.execute( f"/usr/bin/sudo -u {DEFAULT_USER} /usr/bin/passwd", input_str=(f"{old_ssh_password}" f"\n{new_ssh_password}" f"\n{new_ssh_password}"), shlex_split=True)[1].find("successfully")) == -1: return jsonify(success=False, reason="The password update was unsuccessful.") else: return jsonify(success=True) elif passwd_status_output.split()[1] == "NP": webserver_node.get_logger().info("No Password present") if (utility.execute( f"/usr/bin/passwd {DEFAULT_USER}", input_str=(f"{new_ssh_password}\n" f"{new_ssh_password}"), shlex_split=True)[1].find("successfully")) > -1: return jsonify(success=True) else: return jsonify(success=False, reason="Unable to change the SSH password") except Exception: return jsonify(success=False, reason="Error")
def api_wifi_information(): """API to get the list of available WiFi networks. This will populate the wifi drop down in the UI. Returns: list: List of dict objects with WiFi network details. """ webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info("Providing wifi information as response") ssid_set = set() cmd = "/usr/bin/nmcli -t -f ssid,signal,security -e no device wifi list" wifi_list = list() wifi_lines = utility.execute(cmd, shlex_split=True)[1].split("\n") for wifi in wifi_lines: words = wifi.split(":") if words[0] in ssid_set or words[0] == "--" or len(words[0]) == 0: continue ssid_set.add(words[0]) wifi_data = { "ssid": words[0], "strength": math.floor(1.0 + float(words[1]) / 30.0), "security_info": words[2] } wifi_list.append(wifi_data) return jsonify(wifi_list)
def disable_ssh(): """API called to execute commands to disable the ssh. Returns: dict: Execution status if the API call was successful, flag to indicate if ssh is still enabled and with error reason if call fails. """ webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info("Disabling SSH") try: # Stop SSH utility.execute("/usr/sbin/service ssh stop", shlex_split=True) return jsonify(success=True, isSshEnabled=False, reason="Ssh disabled.") except Exception as ex: webserver_node.get_logger().error(f"Failed to disable ssh: {ex}") return jsonify(success=False, isSshEnabled=True, reason="Error")
def get_connected_ssid(): """Get the current SSID if the vehicle is connected to the suppied SSID. Returns: str: SSID details. """ cur_ssid = utility.execute( r'/usr/bin/nmcli -t -f active,ssid -e no dev wifi | egrep "^yes" | cut -d\: -f2', shell=True)[1] return cur_ssid.strip() if cur_ssid.strip() and cur_ssid else ""
def get_file_and_folder_info(path): """Helper function to get the file and folder information for the model at the model path sent as parameter. Args: path (str): Model directory path. Returns: dict: Dictonary with the relevant details about the model. """ training_algorithm_display_name = \ constants.TRAINING_ALGORITHM_NAME_MAPPING[constants.INVALID_ENUM_VALUE] action_space_type_display_name = \ constants.ACTION_SPACE_TYPE_NAME_MAPPING[constants.INVALID_ENUM_VALUE] model_metadata_sensors_display_names = \ [constants.SENSOR_INPUT_NAME_MAPPING[constants.INVALID_ENUM_VALUE]] size = utility.execute(["du", "-sh", path])[1].split("\t")[0] err_code, err_msg, model_metadata_content = \ read_model_metadata_file(os.path.join(path, "model_metadata.json")) if err_code == 0: err_code, err_msg, model_metadata_sensors = get_sensors( model_metadata_content) if err_code == 0: model_metadata_sensors_display_names = [ constants.SENSOR_INPUT_NAME_MAPPING[constants.SensorInputKeys( sensor)] for sensor in model_metadata_sensors ] err_code, err_msg, training_algorithm = get_training_algorithm( model_metadata_content) if err_code == 0: training_algorithm_display_name = \ constants.TRAINING_ALGORITHM_NAME_MAPPING[ constants.TrainingAlgorithms(training_algorithm)] err_code, err_msg, action_space_type = get_action_space_type( model_metadata_content) if err_code == 0: action_space_type_display_name = \ constants.ACTION_SPACE_TYPE_NAME_MAPPING[ constants.ActionSpaceTypes(action_space_type)] data = { "name": os.path.basename(path), "size": size, "creation_time": os.path.getmtime(path), "status": "Ready", "training_algorithm": training_algorithm_display_name, "action_space_type": action_space_type_display_name, "sensors": ", ".join(model_metadata_sensors_display_names) } return data
def get_static_ip_address(): """Returns the static ip address of the vehicle. Returns: str: Comma seperated ip address values. """ webserver_node = webserver_publisher_node.get_webserver_node() try: _, ips = utility.execute("hostname -I", shell=True) req_ips = list() for ip_address in ips.split(): ip_norm = ip_address.strip() if ip_norm in REMOVE_IPS or not ip_norm: continue req_ips.append(ip_norm) return ", ".join(req_ips) except Exception as ex: webserver_node.get_logger().info( f"Failed to fetch the static IP address: {ex}") return ""
def api_wifi_reset(): """API used to reset the wifi ssid and password. This will send success or failure message. Connects the vehicle to the provide Wi-Fi credentials. Returns: dict: Execution status if the reset was successful and the static ip address. """ webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info( "User requesting for resetting the wifi credentials") form_data = request.json wifi_name = form_data["wifi_name"] wifi_password = form_data["wifi_password"] if utility.is_network_connected(wifi_name): ip_address = get_static_ip_address() return jsonify({"success": True, "ip_address": ip_address}) if utility.is_network_inactive(wifi_name): utility.execute(['sudo', '/usr/bin/nmcli', 'con', 'del', wifi_name]) utility.execute([ 'sudo', '/usr/bin/nmcli', 'device', 'wifi', 'con', wifi_name, 'password', wifi_password, 'ifname', 'mlan0' ]) if not utility.is_network_connected(wifi_name): webserver_node.get_logger().info( "Wifi not changed successfully, clean up.") utility.execute(['sudo', '/usr/bin/nmcli', 'con', 'del', wifi_name]) return jsonify({ "success": False, "reason": "Could not connect to the Wi-Fi network.\ Check your network ID and password and try again." }) ip_address = get_static_ip_address() return jsonify({"success": True, "ip_address": ip_address})