What is the best way to add a new line following every awk command in Python code?

Is there a way to insert a new line after each string is found in Python? Any assistance would be highly appreciated, and I am open to other search methods like GREP or SED. I need something that can scan through the output, identify key words, and display each result on a separate line. Thank you.

The current output appears as follows:

['+ Target IP: 127.0.0.1', '+ Target Hostname: 127.0.0.1', '+ Server: Apache/2.4.46 (Debian)']

I want the output to be formatted like this:

Target IP: 127.0.0.1

Target Hostname: 127.0.0.1

Server: Apache/2.4.46 (Debian)

Python Script:

#!/usr/bin/python
import subprocess
import os

def execute_command(command):
    return subprocess.check_output(['bash', '-c', command])

def nikto_scan():
    result = execute_command("nikto -h %s | awk '/Target IP|Hostname|Server/ ' " % target_value).splitlines()

    print(result)

nikto_scan()

Answer №1

If every item in the collection is consistently preceded by '+ ', simply remove the first two characters by slicing each string starting from the second position and then use the '\n'.join() method (the string that the join method acts on serves as the separator between elements) to combine them together and display the result.

print('\n'.join([item[2:] for item in data]))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Selenium test functions correctly in the production environment, however it encounters issues when run

I am facing an issue with my Vue.js application while writing Selenium tests. The test passes when run against the deployed production version of the app, but fails when run against a local version. When running the app locally, it is not from a build, bu ...

Error arises in Python when strings are compared

I'm having an issue with this code where it's not properly comparing strings and I've exhausted all possible avenues for finding the problem: If anyone could assist me, the files are being read correctly but the comparison is not happening ...

Combining Starlette and pydantic for optimal performance

Could you provide guidance on using Pydantic to extract user input in a Starlette application? I would appreciate any assistance. class Post(BaseModel): title:str content:str @app.route("/createposts",methods=["POST"]) async def crea ...

Insert a vertical divider to separate icons and text within a menu

I'm seeking guidance on how to implement separators between icons and text in a menu. Any suggestions would be greatly appreciated. The specific task I am looking to accomplish is: . Open a menu from a button and incorporate separators as shown in t ...

Different ways to change the name of an element within a loop in Python 3

I've been attempting to develop a basic calculator, and I'm facing an issue with dynamically changing my object's name within a loop. RoR = RoR + 1 "C{0}R{1}".format(CoC, RoR) = int(input("Please enter the number for Row {0}, Column {1}: ". ...

When trying to load the JSON data saved in a JSON file, I encounter an error: JSONDecodeError: Expecting value at line 1, column 1

In this scenario, I am experimenting with saving data in json format to a json file, but encountering issues when trying to load it back. import json # Python objects can be stored in json format value = [ ['sentence one', {'en ...

Python function to validate input while preserving original values

While developing a tax calculator application, I encountered an issue with the validation of input tax codes. It appears that the program rejects invalid tax codes initially, but then proceeds to hold onto the original inputs and iterates through them in r ...

Extracting information from a webpage

I am trying to extract the text from the XPath provided below using Selenium. However, I keep encountering the following traceback error: date = driver.find_element_by_xpath('//[@id="General"]/fieldset/dl/dd[5]/text()').text() print(date) Error ...

What is stopping Mr. Developer from installing the necessary package dependencies for me?

I've encountered an issue with my mr.developer and buildout setup for a project. The eggs listed in my development packages' install_requires are not being installed. What could be the reason behind this? Here is the setup.py file for the projec ...

Issues with accessing global IDs in PyOpenCL within 2D arrays are causing errors

I'm completely new to OpenCL and decided to experiment with it using the code provided on a website. I made some changes to the code and am attempting to send a 4x4 matrix filled with all 1s to the kernel and retrieve it back. It may seem like a simpl ...

Selenium in Python encounters difficulty locating web element

I've been attempting to extract posts from a forum I found at this specific URL: The main content I'm trying to pull is located within: <div class="post-content"> However, no matter if I use get element to search by XPATH or CLA ...

Generate a string containing a hexadecimal number in Python

Is there a more efficient way to format numbers as hex inside a string when printing? I need to print a hex number at any position within the string. a = [1, 2, 10, 30] # The current method works, but I'm looking for a more optimal solution, especial ...

Setting up your YAML configuration to utilize both PHP and Python with AJAX in a unified project on App Engine

Here is my project idea https://i.stack.imgur.com/oGOam.jpg $.ajax({ url: '../server/python/python_file.py', dataType: 'json', type: 'POST', success:function(data) { //Perform additional AJAX requests using PHP f ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

In Python, update a dictionary only if the value is defined

Consider this code snippet: import json foo_data = [ { "name": "Bob", "occupation": "", "standing": "good", "locations": ["California"], "meta": { "last_updated": "2018-01-15" } }, { "name": "", ...

Python error: "IndexError: the index of the string is beyond the specified range"

After importing my txt file as a string using the `open` method: with open('./doc', 'r') as f: data = f.readlines() I then attempted to clean the data by iterating through it with a for loop: documents = [] for line in data: ...

Selenium extracts valuable content, specifically the text within the <h2> tag of a webpage,

I am currently working on a project that involves entering a postcode (which will eventually be a list) into a website and saving the obtained results to a CSV file using a loop to move on to the next. However, I am encountering difficulties when it comes ...

Python offers a straightforward way to calculate the integration of multiplying a series of functions. Follow these steps

As I tackle the task of calculating the integration presented below: where p_{i} represent values and x serves as the variable, with N being equal to 5. I am aware that solving this equation using sympy might prove to be difficult. That's why I have ...

How can I obtain a rounded integer in Python?

My dilemma involves dividing the number 120 by 100 in Python. The result I am currently receiving is 1.2, however, I am seeking a solution to obtain only 2 (not 2.0) without importing any libraries. Is there anyone who can provide assistance with this? ...

Transferring a list of decimal numbers from a Python server to another using Flask and the requests library

I am working on a project that involves periodically sending an Array of doubles from a Python service to another. Despite being a newcomer to Python, I have delved into topics like Flask and requests. Below is a basic code example that I put together jus ...