示例#1
0
def exists_outgoing_network_socket(localip, localport, remoteip, remoteport):
    """
  <Purpose>
    Determines if there exists a network socket with the specified unique tuple.
    Assumes TCP.

  <Arguments>
    localip: The IP address of the local socket
    localport: The port of the local socket
    remoteip:  The IP of the remote host
    remoteport: The port of the remote host
    
  <Returns>
    A Tuple, indicating the existence and state of the socket. E.g. (Exists (True/False), State (String or None))
  """

    # This only works if all are not of the None type
    if not (localip and localport and remoteip and remoteport):
        return (False, None)

    # Construct search strings, add a space so port 8 wont match 80
    localsocket = localip + ":" + str(localport) + " "
    remotesocket = remoteip + ":" + str(remoteport) + " "

    # Launch up a shell, get the feedback
    netstat_process = portable_popen.Popen(["netstat", "-an"])

    netstat_output, _ = netstat_process.communicate()

    target_lines = textops.textops_grep(localsocket, \
        textops.textops_rawtexttolines(netstat_output, linedelimiter="\r\n"))
    target_lines = textops.textops_grep(remotesocket, target_lines)

    target_lines = textops.textops_grep("tcp ",
                                        target_lines,
                                        case_sensitive=False)

    # Check each line, to make sure the local socket comes before the remote socket
    # Since we are just using find, the "order" is not imposed, so if the remote socket
    # is first that implies it is an inbound connection
    if len(target_lines) > 0:
        # Check each entry
        for line in target_lines:
            # Check the indexes for the local and remote socket, make sure local
            # comes first
            local_index = line.find(localsocket)
            remote_index = line.find(remotesocket)
            if local_index <= remote_index and local_index != -1:
                # Replace tabs with spaces, explode on spaces
                parts = line.replace("\t", "").strip("\r\n").split()
                # Get the state
                socket_state = parts[-1]

                return (True, socket_state)

        return (False, None)

    # If there were no entries, then there is no socket!
    else:
        return (False, None)
示例#2
0
def exists_outgoing_network_socket(localip, localport, remoteip, remoteport):
  """
  <Purpose>
    Determines if there exists a network socket with the specified unique tuple.
    Assumes TCP.

  <Arguments>
    localip: The IP address of the local socket
    localport: The port of the local socket
    remoteip:  The IP of the remote host
    remoteport: The port of the remote host
    
  <Returns>
    A Tuple, indicating the existence and state of the socket. E.g. (Exists (True/False), State (String or None))
  """
  
  # This only works if all are not of the None type
  if not (localip and localport and remoteip and remoteport):
    return (False, None)

  # Construct search strings, add a space so port 8 wont match 80
  localsocket = localip+":"+str(localport)+" "
  remotesocket = remoteip+":"+str(remoteport)+" "

  # Launch up a shell, get the feedback
  netstat_process = portable_popen.Popen(["netstat", "-an"])

  netstat_output, _ = netstat_process.communicate()

  target_lines = textops.textops_grep(localsocket, \
      textops.textops_rawtexttolines(netstat_output, linedelimiter="\r\n"))
  target_lines = textops.textops_grep(remotesocket, target_lines)

  target_lines = textops.textops_grep("tcp ", target_lines, case_sensitive=False)
  
  # Check each line, to make sure the local socket comes before the remote socket
  # Since we are just using find, the "order" is not imposed, so if the remote socket
  # is first that implies it is an inbound connection
  if len(target_lines) > 0:
    # Check each entry
    for line in target_lines:
      # Check the indexes for the local and remote socket, make sure local
      # comes first  
      local_index = line.find(localsocket)
      remote_index = line.find(remotesocket)
      if local_index <= remote_index and local_index != -1:
        # Replace tabs with spaces, explode on spaces
        parts = line.replace("\t","").strip("\r\n").split()
        # Get the state
        socket_state = parts[-1]
      
        return (True, socket_state)
 
    return (False, None)

  # If there were no entries, then there is no socket!
  else:
    return (False, None)
示例#3
0
def exists_outgoing_network_socket(localip, localport, remoteip, remoteport):

  """
  <Purpose>
    Determines if there exists a network socket with the specified unique tuple.
    Assumes TCP.

  <Arguments>
    localip: The IP address of the local socket
    localport: The port of the local socket
    remoteip:  The IP of the remote host
    remoteport: The port of the remote host
    
  <Returns>
    A Tuple, indicating the existence and state of the socket. E.g. (Exists (True/False), State (String or None))

  """
  # This only works if all are not of the None type
  if not (localip and localport and remoteip and remoteport):
    return (False, None)

  #set to none to check if process will run
  network_status_process = None

  # netstat portion
  if(network_status_process == None):
    try:
      # Grab netstat output.
      network_status_process = portable_popen.Popen(["netstat", "-an"])
      netstat_stdout, _ = network_status_process.communicate()
      netstat_lines = textops.textops_rawtexttolines(netstat_stdout)

      # Search for things matching the local and remote ip+port we are trying to get
      # information about.
      target_lines = textops.textops_grep(localip + ':' + str(localport), netstat_lines) + \
        textops.textops_grep(localip + '.' + str(localport), netstat_lines)

      target_lines = textops.textops_grep(remoteip + ':' + str(remoteport), target_lines) + \
        textops.textops_grep(remoteip + '.' + str(remoteport), target_lines)

      if len(target_lines) > 0:
        line = target_lines[0]

        # Replace tabs with spaces, explode on spaces
        parts = line.replace("\t","").strip("\n").split()


        # Get the state
        socket_state = parts[-1]
        return (True, socket_state)

    except Exception, e:
      #skips the exception to try the next command
      pass
示例#4
0
def get_available_interfaces():
  """
  <Purpose>
    Returns a list of available network interfaces.
  
  <Returns>
    An array of string interfaces
  """
  # Common headers
  # This list contains common header elements so that they can be stripped
  common_headers_list = ["Name", "Kernel", "Iface"]
  
  # Netstat will return all interfaces, but also has some duplication.
  #If Netstat is not on machine then secondary command IP will be used as substitute
  # Cut will get the first field from each line, which is the interface name.
  # Sort prepares the input for uniq, which only works on sorted lists.
  # Uniq, is somewhat obvious, it will only return the unique interfaces to remove duplicates.
  # Launch up a shell, get the feedback


  network_status_process = None

  #netstat process
  if(network_status_process == None):
    try:
      network_status_process = portable_popen.Popen(["netstat", "-i"])
      netstat_stdout, _ = network_status_process.communicate()
      netstat_lines = textops.textops_rawtexttolines(netstat_stdout)

      target_lines = textops.textops_cut(netstat_lines, delimiter=" ", fields=[0])

      unique_lines = set(target_lines)

      # Create an array for the interfaces
      interfaces_list = []
  
      for line in unique_lines:
        # Strip the newline
        line = line.strip("\n")
        # Check if this is a header
        if line in common_headers_list:
          continue
        interfaces_list.append(line)
  
      # Done, return the interfaces
      return interfaces_list
    except Exception, e:
      pass
示例#5
0
def exists_outgoing_network_socket(localip, localport, remoteip, remoteport):
    """
  <Purpose>
    Determines if there exists a network socket with the specified unique tuple.
    Assumes TCP.

  <Arguments>
    localip: The IP address of the local socket
    localport: The port of the local socket
    remoteip:  The IP of the remote host
    remoteport: The port of the remote host
    
  <Returns>
    A Tuple, indicating the existence and state of the socket. E.g. (Exists (True/False), State (String or None))

  """
    # This only works if all are not of the None type
    if not (localip and localport and remoteip and remoteport):
        return (False, None)

    # Grab netstat output.
    netstat_process = portable_popen.Popen(["netstat", "-an"])
    netstat_stdout, _ = netstat_process.communicate()
    netstat_lines = textops.textops_rawtexttolines(netstat_stdout)

    # Search for things matching the local and remote ip+port we are trying to get
    # information about.
    target_lines = textops.textops_grep(localip + ':' + str(localport), netstat_lines) + \
        textops.textops_grep(localip + '.' + str(localport), netstat_lines)

    target_lines = textops.textops_grep(remoteip + ':' + str(remoteport), target_lines) + \
        textops.textops_grep(remoteip + '.' + str(remoteport), target_lines)

    # Only tcp connections.
    target_lines = textops.textops_grep('tcp', target_lines)

    # Check if there is any entries
    if len(target_lines) > 0:
        line = target_lines[0]
        # Replace tabs with spaces, explode on spaces
        parts = line.replace("\t", "").strip("\n").split()
        # Get the state
        socket_state = parts[-1]

        return (True, socket_state)

    else:
        return (False, None)
示例#6
0
def exists_listening_network_socket(ip, port, tcp):
  """
  <Purpose>
    Determines if there exists a network socket with the specified ip and port which is the LISTEN state.
  
  <Arguments>
    ip: The IP address of the listening socket
    port: The port of the listening socket
    tcp: Is the socket of TCP type, else UDP
    
  <Returns>
    True or False.
  """
  # This only works if both are not of the None type
  if not (ip and port):
    return False
  
  # UDP connections are stateless, so for TCP check for the LISTEN state
  # and for UDP, just check that there exists a UDP port
  if tcp:
    grep_terms = ["tcp", "LISTEN"]
  else:
    grep_terms = ["udp"]

  #set to none to check if process will run
  network_status_process = None

  # netstat portion
  if(network_status_process == None):
    try:

      # Launch up a shell, get the feedback
      network_status_process = portable_popen.Popen(["netstat", "-an"])
      netstat_stdout, _ = network_status_process.communicate()
      netstat_lines = textops.textops_rawtexttolines(netstat_stdout)
      # Search for things matching the ip+port we are trying to get
      # information about.
      target_lines = textops.textops_grep(ip + ':' + str(port), netstat_lines) + \
          textops.textops_grep(ip + '.' + str(port), netstat_lines)

      for term in grep_terms:
        target_lines = textops.textops_grep(term, target_lines)

      number_of_sockets = len(target_lines)
      return (number_of_sockets > 0)
    except Exception, e:
      pass
示例#7
0
def get_system_thread_count():
  """
  <Purpose>
    Returns the number of active threads running on the system.

  <Returns>
    The thread count.
  """
  # Use PS since it is can get the info for us
  process = portable_popen.Popen(["ps", "axH"])

  ps_output, _ = process.communicate()

  # Subtract 1 from the number of lines because the first line is a a table
  # header: "  PID TTY      STAT   TIME COMMAND"
  threads = len(textops.textops_rawtexttolines(ps_output)) - 1

  return threads
示例#8
0
def get_system_thread_count():
    """
  <Purpose>
    Returns the number of active threads running on the system.

  <Returns>
    The thread count.
  """
    # Use PS since it is can get the info for us
    process = portable_popen.Popen(["ps", "axH"])

    ps_output, _ = process.communicate()

    # Subtract 1 from the number of lines because the first line is a a table
    # header: "  PID TTY      STAT   TIME COMMAND"
    threads = len(textops.textops_rawtexttolines(ps_output)) - 1

    return threads
示例#9
0
def exists_listening_network_socket(ip, port, tcp):
    """
  <Purpose>
    Determines if there exists a network socket with the specified ip and port which is the LISTEN state.
  <Arguments>
    ip: The IP address of the listening socket
    port: The port of the listening socket
    tcp: Is the socket of TCP type, else UDP

  <Returns>
    True or False.
  """

    # This only works if both are not of the None type
    if not (ip and port):
        return False

    # UDP connections are stateless, so for TCP check for the LISTEN state
    # and for UDP, just check that there exists a UDP port
    if tcp:
        find = ["tcp", "LISTEN"]
    else:
        find = ["udp"]

    # Launch up a shell, get the feed back
    netstat_process = portable_popen.Popen(["netstat", "-an"])

    netstat_output, _ = netstat_process.communicate()

    target_lines = textops.textops_grep(ip+':'+str(port)+' ', \
        textops.textops_rawtexttolines(netstat_output, linedelimiter="\r\n"))

    for term in find:  # Add additional grep's
        target_lines = textops.textops_grep(term,
                                            target_lines,
                                            case_sensitive=False)

    # Convert to an integer
    num = len(target_lines)

    return (num > 0)
示例#10
0
def exists_listening_network_socket(ip, port, tcp):
    """
  <Purpose>
    Determines if there exists a network socket with the specified ip and port which is the LISTEN state.
  
  <Arguments>
    ip: The IP address of the listening socket
    port: The port of the listening socket
    tcp: Is the socket of TCP type, else UDP
    
  <Returns>
    True or False.
  """
    # This only works if both are not of the None type
    if not (ip and port):
        return False

    # UDP connections are stateless, so for TCP check for the LISTEN state
    # and for UDP, just check that there exists a UDP port
    if tcp:
        grep_terms = ["tcp", "LISTEN"]
    else:
        grep_terms = ["udp"]

    # Launch up a shell, get the feedback
    netstat_process = portable_popen.Popen(["netstat", "-an"])
    netstat_stdout, _ = netstat_process.communicate()
    netstat_lines = textops.textops_rawtexttolines(netstat_stdout)

    # Search for things matching the ip+port we are trying to get
    # information about.
    target_lines = textops.textops_grep(ip + ':' + str(port), netstat_lines) + \
        textops.textops_grep(ip + '.' + str(port), netstat_lines)

    for term in grep_terms:
        target_lines = textops.textops_grep(term, target_lines)

    number_of_sockets = len(target_lines)

    return (number_of_sockets > 0)
示例#11
0
def get_available_interfaces():
    """
  <Purpose>
    Returns a list of available network interfaces.
  
  <Returns>
    An array of string interfaces
  """
    # Common headers
    # This list contains common header elements so that they can be stripped
    common_headers_list = ["Name", "Kernel", "Iface"]

    # Netstat will return all interfaces, but also has some duplication.
    # Cut will get the first field from each line, which is the interface name.
    # Sort prepares the input for uniq, which only works on sorted lists.
    # Uniq, is somewhat obvious, it will only return the unique interfaces to remove duplicates.
    # Launch up a shell, get the feedback
    netstat_process = portable_popen.Popen(["netstat", "-i"])
    netstat_stdout, _ = netstat_process.communicate()
    netstat_lines = textops.textops_rawtexttolines(netstat_stdout)

    target_lines = textops.textops_cut(netstat_lines,
                                       delimiter=" ",
                                       fields=[0])

    unique_lines = set(target_lines)

    # Create an array for the interfaces
    interfaces_list = []

    for line in unique_lines:
        # Strip the newline
        line = line.strip("\n")
        # Check if this is a header
        if line in common_headers_list:
            continue
        interfaces_list.append(line)

    # Done, return the interfaces
    return interfaces_list
示例#12
0
def exists_listening_network_socket(ip, port, tcp):
  """
  <Purpose>
    Determines if there exists a network socket with the specified ip and port which is the LISTEN state.
  <Arguments>
    ip: The IP address of the listening socket
    port: The port of the listening socket
    tcp: Is the socket of TCP type, else UDP

  <Returns>
    True or False.
  """

  # This only works if both are not of the None type
  if not (ip and port):
    return False

  # UDP connections are stateless, so for TCP check for the LISTEN state
  # and for UDP, just check that there exists a UDP port
  if tcp:
    find = ["tcp", "LISTEN"]
  else:
    find = ["udp"]

  # Launch up a shell, get the feed back
  netstat_process = portable_popen.Popen(["netstat", "-an"])

  netstat_output, _ = netstat_process.communicate()

  target_lines = textops.textops_grep(ip+':'+str(port)+' ', \
      textops.textops_rawtexttolines(netstat_output, linedelimiter="\r\n"))

  for term in find:   # Add additional grep's
    target_lines = textops.textops_grep(term, target_lines, case_sensitive=False)

  # Convert to an integer
  num = len(target_lines)

  return (num > 0)
示例#13
0
def get_interface_ip_addresses(interfaceName):
    """
  <Purpose>
    Returns the IP address associated with the interface.
  
  <Arguments>
    interfaceName: The string name of the interface, e.g. eth0
  
  <Returns>
    A list of IP addresses associated with the interface.
  """

    # Launch up a shell, get the feed back
    # We use ifconfig with the interface name.
    ifconfig_process = portable_popen.Popen(
        ["/sbin/ifconfig", interfaceName.strip()])

    ifconfig_output, _ = ifconfig_process.communicate()
    ifconfig_lines = textops.textops_rawtexttolines(ifconfig_output)

    # Look for ipv4 addresses
    target_lines = textops.textops_grep("inet", ifconfig_lines)
    # and not ipv6
    target_lines = textops.textops_grep("inet6", target_lines, exclude=True)

    # Only take the ip(s)
    target_lines = textops.textops_cut(target_lines, delimiter=":", fields=[1])
    target_lines = textops.textops_cut(target_lines, delimiter=" ", fields=[0])

    # Create an array for the ip's
    ipaddressList = []

    for line in target_lines:
        # Strip the newline and any spacing
        line = line.strip("\n\t ")
        ipaddressList.append(line)

    # Done, return the interfaces
    return ipaddressList
示例#14
0
def get_interface_ip_addresses(interfaceName):
  """
  <Purpose>
    Returns the IP address associated with the interface.
  
  <Arguments>
    interfaceName: The string name of the interface, e.g. eth0
  
  <Returns>
    A list of IP addresses associated with the interface.
  """

  # Launch up a shell, get the feed back
  # We use ifconfig with the interface name.
  ifconfig_process = portable_popen.Popen(["/sbin/ifconfig", interfaceName.strip()])

  ifconfig_output, _ = ifconfig_process.communicate()
  ifconfig_lines = textops.textops_rawtexttolines(ifconfig_output)
  
  # Look for ipv4 addresses
  target_lines = textops.textops_grep("inet", ifconfig_lines)
  # and not ipv6
  target_lines = textops.textops_grep("inet6", target_lines, exclude=True)

  # Only take the ip(s)
  target_lines = textops.textops_cut(target_lines, delimiter=":", fields=[1])
  target_lines = textops.textops_cut(target_lines, delimiter=" ", fields=[0])

  # Create an array for the ip's
  ipaddressList = []
  
  for line in target_lines:
     # Strip the newline and any spacing
     line = line.strip("\n\t ")
     ipaddressList.append(line)

  # Done, return the interfaces
  return ipaddressList
示例#15
0

        # Get the state
        socket_state = parts[-1]
        return (True, socket_state)

    except Exception, e:
      #skips the exception to try the next command
      pass

  if(network_status_process == None):
    try:
      # Grab SS output.
      network_status_process = portable_popen.Popen(["ss", "-a"])
      ss_stdout, _ = network_status_process.communicate()
      ss_lines = textops.textops_rawtexttolines(ss_stdout)

      #SS has a different way of outputtiung local host then netstat -an
      if(localip == "0.0.0.0"):
        ip = "*"
      
      # Search for things matching the local and remote ip+port we are trying to get
      # information about.  
      target_lines = textops.textops_grep(localip + ':' + str(localport), ss_lines) + \
        textops.textops_grep(localip + '.' + str(localport), ss_lines)

      target_lines = textops.textops_grep(remoteip + ':' + str(remoteport), target_lines) + \
        textops.textops_grep(remoteip + '.' + str(remoteport), target_lines)

      if len(target_lines) > 0:
        line = target_lines[0]