Пример #1
0
def add_hosts_info(ip, hostnames):
    hosts = python_hosts.Hosts(path='/etc/hosts')
    filtered_hostnames = [hostname for hostname in hostnames if hostname]
    if not ip or not filtered_hostnames:
        return
    new_entry = python_hosts.HostsEntry(entry_type='ipv4',
                                        address=ip,
                                        names=filtered_hostnames)
    hosts.add([new_entry])
    hosts.write()
Пример #2
0
    def __init__(self, ui_main, main_logger, ssh_pass):
        #set imports as part of self
        self.uimain = ui_main
        self.ssh_tunnel = magmaGS.magmaGS(main_logger, ssh_pass)

        #read config
        self.actions_config_file = open(
            ApplicationContext().get_resource("actions_config.json"))
        self.actions_config = json.load(self.actions_config_file)
        print(self.actions_config)
        self.hosts_file = python_hosts.Hosts()
Пример #3
0
 def test_named_proxyport_exists():
     if not is_admin():
         run_as_admin(["python", __file__])
     else:
         print("Exists:", named_proxyport_exists("foo.bar"))
         register_named_proxyport("foo.bar")
         print("Exists:", named_proxyport_exists("foo.bar"))
         hosts = python_hosts.Hosts()
         hosts.remove_all_matching(name="foo.bar")
         hosts.write()
         print("Exists:", named_proxyport_exists("foo.bar"))
         remove_named_proxyport("foo.bar")
         print("Exists:", named_proxyport_exists("foo.bar"))
Пример #4
0
def register_named_proxyport(*names,
                             targetip="127.0.0.1",
                             targetport=8000,
                             proxyaddress="127.65.43.21",
                             proxyport=80):
    """ Uses netsh and the Windows hosts file in order to create a name which directs to another ip and port.
    
        This function requires Administrative rights. If not available, a RuntimeError will be raised.

        names is one or more names that will be resolved to the given target. If those names are already
        registered, a ValueError is raised.
        targetip is the ip that should be redirected to. The default is "127.0.0.1" (localhost).
        targetport is the port on that ip to target. The default port is 8000.
        proxyaddress is an address that netsh should listen on. It should be an address that is not
        already being monitored. The "netstat -a -n -p TCP" console command can be used to check the
        address. Default value is "127.65.43.21". If this address is already registered, a ValueError
        will be raised.
        proxyport is "80" by default and should be kept that way for use with webbrowsers.
    """
    if not is_admin():
        raise RuntimeError(
            "register_named_proxyport requires Administrative Rights")
    try:
        1 <= int(targetport) <= 65535
    except:
        raise ValueError("Invalid targetport")
    try:
        1 <= int(proxyport) <= 65535
    except:
        raise ValueError("Invalid proxyport")

    cmds = "netsh","interface","portproxy","add","v4tov4",f"listenport={proxyport}",f"listenaddress={proxyaddress}",\
    f"connectport={targetport}",f"connectaddress={targetip}"
    entry = python_hosts.HostsEntry(entry_type="ipv4",
                                    address=proxyaddress,
                                    names=names)

    subprocess.run(cmds)

    hosts = python_hosts.Hosts()
    if hosts.exists(address == proxyaddress):
        raise ValueError("Provided proxy address is already in use")
    if hosts.exists(names=names):
        raise ValueError("Provided names are already registered")
    hosts.add([
        entry,
    ])
    hosts.write()
Пример #5
0
def remove_named_proxyport(*names, proxyaddress="127.65.43.21", proxyport=80):
    """ Removes the netsh and hosts file changes made by register_named_proxyport.

        This function requires Administrative rights. If not available, a RuntimeError will be raised.

        names, proxyaddress, and proxyport should all match the arguments of the same name
        passed to register_named_proxyport.
        The defaults for proxyaddress and proxyport are the same as that function.
    """
    if not is_admin():
        raise RuntimeError(
            "remove_named_proxyport requires Administrative Rights")

    cmds = "netsh", "interface", "portproxy", "delete", "v4tov4", f"listenport={proxyport}", f"listenaddress={proxyaddress}"
    subprocess.run(cmds)

    hosts = python_hosts.Hosts()
    for name in names:
        hosts.remove_all_matching(name=name)
    hosts.write()
Пример #6
0
def named_proxyport_exists(*names,
                           targetip="127.0.0.1",
                           targetport=8000,
                           proxyaddress="127.65.43.21",
                           proxyport=80):
    """ Checks whether register_named_proxyport has been used with the provided arguments.

        All arguments are the same as register_named_proxyport.
        If the named proxyport exists, return True. If no portion of the named proxyport is present, return False.
        If the named proxyport is incomplete, raise a RuntimeWarning. Incomplete named proxyports should be removed and re-registered.
    """
    netsh = False
    registered_netsh = get_netsh_portproxy()
    for entry in registered_netsh:
        ## ports should be converted to strings since get_netsh_portproxy returns strings
        if entry['listen']['address'] != proxyaddress: continue
        if entry['listen']['port'] != str(proxyport): continue
        if entry['connect']['address'] != targetip: continue
        if entry['connect']['port'] != str(targetport): continue
        netsh = True
        break

    hosts = python_hosts.Hosts()
    hostfile = False
    for entry in hosts.entries:
        if not entry.names: continue
        if not all(name in entry.names for name in names): continue
        if entry.address == proxyaddress:
            hostfile = True
            break

    if hostfile and netsh: return True
    if not hostfile and not netsh: return False
    warnings.warn(
        f"Incomplete Named Proxyport (netsh={netsh},hosts={hostfile})",
        RuntimeWarning)
# If you're rerunning this script after the initial provisioning, run the
# GetIPAddresses.ps1 powershell script first.  That will refresh the hosts.ini
# data with current ip addresses.

import python_hosts
import configparser

config = configparser.ConfigParser()
config.read("/vagrant/hosts.ini")

hosts = python_hosts.Hosts(path="/etc/hosts")

for entry in config.sections():
    print("entry:", entry)
    entry_type = config[entry]["entry_type"]
    print("entry_type:", entry_type)
    ip_address = config[entry]["address"]
    print("ip_address:", ip_address)

    name_list = []
    name = config[entry]["names"]
    print("name:", name)
    for n in name.split(","):
        name_list.append(n)

    # Remove any previous entry in the hosts file for the current name. If a
    # computer is recreated, this will clear out the previous entry in the
    # hosts file, and replace it with new information.
    hosts.remove_all_matching(name=name)

    new_entry = python_hosts.HostsEntry(entry_type=entry_type,