Yotch
Yotch

Reputation: 33

Host file injector with Python

I'm having some trouble with a function that's supposed to identify your operating system and return the corresponding PATH to that hosts file so that the program can read the file and add more lines to it. The problem relies when invoking the function into the open() statement as it returns "TypeError: expected str, bytes or os.PathLike object, not NoneType". Here's my code:

import time
import os 
import platform
from datetime import datetime as dt
from sys import platform as _platform

def osFinder():
    if _platform == "Linux" or _platform == "Linux2":
        return "/etc/hosts"
    elif _platform == "darwin":
        return "/etc/hosts"
    elif _platform == "win32":
        return r"C:\Windows\System32\drivers\etc\hosts"
    elif _platform == "win64":
        return r"C:\Windows\System32\drivers\etc\hosts"

# Host Files PATH:
# windows_path = r"C:\Windows\System32\drivers\etc\hosts"
# unix_path = "/etc/hosts"
temp_path = osFinder()

redirect = "127.0.0.1"

sitesList = [
    "www.facebook.com",
    "www.netflix.com",
    "www.youtube.com"
]

from_hour = 7
to_hour = 16

while True:
    if dt(dt.now().year, dt.now().month, dt.now().day, from_hour) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day, to_hour):
        print("Working")
        with open(temp_path, 'r+') as file:
            content = file.read()
            for site in sitesList:
                if site in content:
                    pass
                else:
                    file.write(redirect + " " + site + "\n")
    else:
        print("Happy Streaming")
        with open(temp_path, 'r+') as file:
            content = file.readlines()
            file.seek(0)
            for line in content:
                if not any(site in line for site in sitesList):
                    file.write(line)
            file.truncate()
    time.sleep(1)

Upvotes: 2

Views: 855

Answers (1)

ndclt
ndclt

Reputation: 3108

In osFinder, the platform names are incorrect (all values in the doc). There is no capital at "linux" and "linux2" does not exist anymore since Python 3.3.

I just write the osFinder:

from sys import platform as _platform


def osFinder():
    if _platform == "linux":
        return "/etc/hosts"
    elif _platform == "darwin":
        return "/etc/hosts"
    elif _platform == "win32":
        return r"C:\Windows\System32\drivers\etc\hosts"

This can be rewritten in a more pythonic way:

from sys import platform as _platform


PATH_FOR_PLATFORM = {
    "linux": "/etc/hosts", 
    "darwin": "/etc/hosts",
    "win32": r"C:\Windows\System32\drivers\etc\hosts"
}
temp_path = PATH_FOR_PLATFORM[_platform]

Hope it helps.

Upvotes: 0

Related Questions