0

I want to write a script that pings all the ip addresses in a file and displays the status the server name and content length. Now some websites don't display a content length and I want to write if it doesn't exist go on to the next up address.

This is what I have so far

import requests
import os

#input file name
file_name = input("Enter the name of the file: ")

print("hello")



with open(file_name, 'r') as f:
    for line in f:
        ip = line.strip()
        url = "http://" + ip + "/"
        print(ip)
        response = requests.get(url)
        print(response.status_code, len(response.text))
        #print(response.text)
        #print(response.headers)
        #print(response.headers['Content-Type'])
        print(response.headers['Server'])
        #print(response.headers['X-Powered-By'])
        if response.headers['Content-Length'] == None:

            print("Missing Content-Length")
        else:
            print("this is the content type:", response.headers['Content-Length'])

        if ip=="":
            print("No host supplied")

but I'm still getting an error saying

 File "/home/anton/tools/internal_web_tool/web_ip_enumerator.py", line 29, in <module>
    if response.headers['Content-Length'] == "":
  File "/home/anton/.local/lib/python3.9/site-packages/requests/structures.py", line 54, in __getitem__
    return self._store[key.lower()][1]
KeyError: 'content-length'

how can I check if the content length exists or not ?

correction I checked that the content length exists on the ip that I was trying, I but it crashes and gives me the error and I have no idea why

dentist
  • 9
  • 2
  • `dict`s have a nifty, built-in method `.get()` for this: `response.headers.get('Content-Length')`, that defaults to `None` if it doesn’t exist. https://docs.python.org/3/library/stdtypes.html#dict.get – Boldewyn Jun 23 '22 at 08:53
  • Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – SuperStormer Jun 23 '22 at 08:56

1 Answers1

1

To check if a key exists in a dictionary or not, you can simply do:

if "Content-Length" in response.headers:
    print("Do stuff with it")
else:
    print("Missing Content-Length")