コード例 #1
0
ファイル: wdtv_sim.py プロジェクト: clach04/skipstone_server
def determine_local_ipaddr():
    local_address = None

    # Most portable (for modern versions of Python)
    if hasattr(socket, 'gethostbyname_ex'):
        for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
            if not ip.startswith('127.'):
                local_address = ip
                break
    # may be none still (nokia) http://www.skweezer.com/s.aspx/-/pypi~python~org/pypi/netifaces/0~4 http://www.skweezer.com/s.aspx?q=http://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib has alonger one

    if sys.platform.startswith('linux'):
        import fcntl

        def get_ip_address(ifname):
            ifname = ifname.encode('latin1')
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            return socket.inet_ntoa(fcntl.ioctl(
                s.fileno(),
                0x8915,  # SIOCGIFADDR
                struct.pack('256s', ifname[:15])
            )[20:24])

        if not local_address:
            for devname in os.listdir('/sys/class/net/'):
                try:
                    ip = get_ip_address(devname)
                    if not ip.startswith('127.'):
                        local_address = ip
                        break
                except IOError:
                    pass

    # Jython / Java approach
    if not local_address and InetAddress:
        addr = InetAddress.getLocalHost()
        hostname = addr.getHostName()
        for ip_addr in InetAddress.getAllByName(hostname):
            if not ip_addr.isLoopbackAddress():
                local_address = ip_addr.getHostAddress()
                break

    if not local_address:
        # really? Oh well lets connect to a remote socket (Google DNS server)
        # and see what IP we use them
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 53))
        ip = s.getsockname()[0]
        s.close()
        if not ip.startswith('127.'):
            local_address = ip

    return local_address
コード例 #2
0
ファイル: netutils.py プロジェクト: deezeesms/dd-git
def getHostName(ipAddress, defaultValue=None):
    """
    @deprecated: Use SocketDnsResolver().resolve_hostnames(ip_address)

    Resolves the IP address to the host name in the DNS table.
    On failure to resolve the address the , default value parameter is returned.
    @param  ipAddress: IP address to resolve
    @type     ipAddress: string
    @param  defaultValue: the value to return if the address cannot be resolved
    @return: host name of the resolved IP address
    @rtype: string
    """
    if isValidIp(ipAddress):
        try:
            dnsName = str(InetAddress.getByName(ipAddress).getHostName())
            if dnsName == ipAddress:
                return defaultValue
            else:
                return dnsName
        except:
            defultHostName = defaultValue
            if defultHostName == None:
                defultHostName = 'null'
            logger.debug('Could not resolve DNS name for : ', ipAddress,
                         ',returning default value:', defultHostName,
                         ';reason:', str(sys.exc_info()[1]))
    return defaultValue
コード例 #3
0
ファイル: netutils.py プロジェクト: ddonnelly19/dd-git
def getHostName(ipAddress, defaultValue=None):
    """
    @deprecated: Use SocketDnsResolver().resolve_hostnames(ip_address)

    Resolves the IP address to the host name in the DNS table.
    On failure to resolve the address the , default value parameter is returned.
    @param  ipAddress: IP address to resolve
    @type     ipAddress: string
    @param  defaultValue: the value to return if the address cannot be resolved
    @return: host name of the resolved IP address
    @rtype: string
    """
    if isValidIp(ipAddress):
        try:
            dnsName = str(InetAddress.getByName(ipAddress).getHostName())
            if dnsName == ipAddress:
                return defaultValue
            else:
                return dnsName
        except:
            defultHostName = defaultValue
            if defultHostName == None:
                defultHostName = 'null'
            logger.debug('Could not resolve DNS name for : ', ipAddress,
                         ',returning default value:', defultHostName,
                         ';reason:', str(sys.exc_info()[1]))
    return defaultValue
コード例 #4
0
def doInstall(info):
    " do install of activation info"

    logger.info("OracleDatabaseContainer: doInstall:Enter")
    hostname = "localhost";
    try:
        hostname = InetAddress.getLocalHost().getCanonicalHostName()
    except:
        type, value, traceback = sys.exc_info()
        logger.severe("Hostname error:" + `value`)
    
    dbInstallOption = getVariableValue("DB_INSTALL_OPTION")
    if dbInstallOption == "INSTALL_DB_AND_CONFIG":        
        globalLockString = "OracleEnabler-" + hostname
        ContainerUtils.releaseGlobalLock(globalLockString)
        logger.info("Released global lock with name: " + globalLockString)
        
    try:
        oracleDatabase = getVariableValue("ORACLE_DATABASE_OBJECT")
        if oracleDatabase:
            oracleDatabase.installActivationInfo(info)
    except:
        type, value, traceback = sys.exc_info()
        logger.severe("Unexpected error in OracleDatabaseContainer:doInstall:" + `value`)
        
    logger.info("OracleDatabaseContainer: doInstall:Exit")
コード例 #5
0
def doInstall(info):
    " do install of activation info"

    logger.info("OracleDatabaseContainer: doInstall:Enter")
    hostname = "localhost"
    try:
        hostname = InetAddress.getLocalHost().getCanonicalHostName()
    except:
        type, value, traceback = sys.exc_info()
        logger.severe("Hostname error:" + ` value `)

    dbInstallOption = getVariableValue("DB_INSTALL_OPTION")
    if dbInstallOption == "INSTALL_DB_AND_CONFIG":
        globalLockString = "OracleEnabler-" + hostname
        ContainerUtils.releaseGlobalLock(globalLockString)
        logger.info("Released global lock with name: " + globalLockString)

    try:
        oracleDatabase = getVariableValue("ORACLE_DATABASE_OBJECT")
        if oracleDatabase:
            oracleDatabase.installActivationInfo(info)
    except:
        type, value, traceback = sys.exc_info()
        logger.severe(
            "Unexpected error in OracleDatabaseContainer:doInstall:" +
            ` value `)

    logger.info("OracleDatabaseContainer: doInstall:Exit")
コード例 #6
0
ファイル: metastudio.py プロジェクト: tommytracx/metastudio
def federationode(nodeName, noOfProcessors=1):
    from java.net import InetAddress
    from org.meta.net import FederationNode

    fNode = FederationNode(InetAddress.getByName(nodeName))
    fNode.setNoOfProcessors(noOfProcessors)

    return fNode
コード例 #7
0
def getMachineName():
    if isPython:
        from platform import uname
        return uname()[1]
    elif isJython:
        from java.net import InetAddress
        addr = InetAddress.getLocalHost()
        return str(addr.getHostName())
    return False
コード例 #8
0
ファイル: HttpRequest.py プロジェクト: hobson/ggpy
 def issueRequest(cls, targetHost, targetPort, forPlayerName, requestContent, timeoutClock):
     """ generated source for method issueRequest """
     socket = Socket()
     theHost = InetAddress.getByName(targetHost)
     socket.connect(InetSocketAddress(theHost.getHostAddress(), targetPort), 5000)
     HttpWriter.writeAsClient(socket, theHost.getHostName(), requestContent, forPlayerName)
     response = HttpReader.readAsClient(socket) if (timeoutClock < 0) else HttpReader.readAsClient(socket, timeoutClock)
     socket.close()
     return response
コード例 #9
0
 def __getHostName(self):
     "get hostname"
     self.__hostname = getVariableValue("ENGINE_USERNAME");
     try:
         hostname = InetAddress.getLocalHost().getCanonicalHostName()
         if hostname != "localhost" and not re.search("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", hostname):
             self.__hostname = hostname
     except:
         type, value, traceback = sys.exc_info()
         logger.severe("get hostname error:" + `value`)
コード例 #10
0
def _parseMixedIPFromIndex(rawIndexValue):
    rawIndexValue = rawIndexValue.split('.') #split it to array
    rawIndexValue = ".".join(rawIndexValue[2:]) #the first two elements are irrelevant, ignore them
    rawIndexValue = OctetString.fromString(rawIndexValue, '.', 10).getValue()
    ipAddr = None
    try:
        ipAddr = InetAddress.getByAddress(rawIndexValue).getHostAddress()
    except:
        pass
    return ipAddr
コード例 #11
0
 def check_address(self, addrblobs):
     for addrblob in addrblobs:
         addr_arr = addrblob.split("|")
         rrow = int(addr_arr[0])
         addr = addr_arr[1]
         try:
             result = InetAddress.getByName(addr)
             yield [rrow, "Success", result]
         except UnknownHostException:
             yield [rrow, "Fail", None]
コード例 #12
0
 def __init__(self,
              host=config.monomeHost,
              port=config.monomePort,
              prefix=config.monomePrefix,
              width=config.monomeWidth,
              height=config.monomeHeight):
     self.transmitter = UDPTransmitter(InetAddress.getByName(host), port)
     self.prefix = prefix
     self.width = width
     self.height = height
コード例 #13
0
 def __getHostName(self):
     "get hostname"
     self.__hostname = getVariableValue("ENGINE_USERNAME")
     try:
         hostname = InetAddress.getLocalHost().getCanonicalHostName()
         if hostname != "localhost" and not re.search(
                 "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+", hostname):
             self.__hostname = hostname
     except:
         type, value, traceback = sys.exc_info()
         logger.severe("get hostname error:" + ` value `)
コード例 #14
0
ファイル: netutils.py プロジェクト: ddonnelly19/dd-git
 def resolveHostIpWithLocalDns(self, hostName):
     """
     Resolves (or not) IP address by given machine name
     @param hostName: the machine name to resolve IPs
     @type hostName: string
     @rtype: string
     """
     try:
         return InetAddress.getByName(hostName).getHostAddress()
     except UnknownHostException:
         pass
コード例 #15
0
def parseIPv6FromIPv6NetToMediaTableIndex(rawIndexValue):
    realValue = None
    try:
        rawIndexValue = rawIndexValue.split('.') #split it to array
        rawIndexValue = ".".join(rawIndexValue[2:]) #the first two elements are irrelevant, ignore them
        rawIndexValue = OctetString.fromString(rawIndexValue, '.', 10).getValue()
        ipv6Address = InetAddress.getByAddress(rawIndexValue)
        realValue = ipv6Address.getHostAddress()
    except:
        pass
    return realValue
コード例 #16
0
ファイル: netutils.py プロジェクト: deezeesms/dd-git
 def resolveHostIpWithLocalDns(self, hostName):
     """
     Resolves (or not) IP address by given machine name
     @param hostName: the machine name to resolve IPs
     @type hostName: string
     @rtype: string
     """
     try:
         return InetAddress.getByName(hostName).getHostAddress()
     except UnknownHostException:
         pass
コード例 #17
0
def parseIPFromIpNetToPhysicalTableIndex(rawIndexValue):
    realValue = None
    try:
        rawIndexValue = rawIndexValue.split('.') #split it to array
        rawIndexValue = ".".join(rawIndexValue[3:]) #the first three elements are irrelevant, ignore them
        rawIndexValue = OctetString.fromString(rawIndexValue, '.', 10).getValue()
        inetAddress = InetAddress.getByAddress(rawIndexValue)
        realValue = inetAddress.getHostAddress()
    except:
        pass
    return realValue
コード例 #18
0
ファイル: autoRouteConfig.py プロジェクト: bayernmunich/IBM1
 def __init__(self, node, server, host):
     self.node = node
     self.server = server
     self.host = host
     ia = InetAddress.getByName(host)
     if (ia != None):
         self.host = ia.getCanonicalHostName()
         self.ipAddr = ia.getHostAddress()
         self.trustedProxy = self.ipAddr
     else:
         self.ipAddr = None
         self.trustedProxy = host
コード例 #19
0
ファイル: netutils.py プロジェクト: ddonnelly19/dd-git
 def resolveHostnamesByIp(self, ip):
     '''@types: str -> list[str]
     @raise ResolveException: Failed to resolve hostnames
     '''
     if not ip:
         raise ValueError("Ip is not specified")
     dnsName = None
     try:
         dnsName = str(InetAddress.getByName(ip).getHostName())
     except JException, je:
         logger.debug(str(je))
         raise self._HOSTNAME_RESOLVE_EXCEPTION
コード例 #20
0
ファイル: netutils.py プロジェクト: deezeesms/dd-git
 def resolveHostnamesByIp(self, ip):
     '''@types: str -> list[str]
     @raise ResolveException: Failed to resolve hostnames
     '''
     if not ip:
         raise ValueError("Ip is not specified")
     dnsName = None
     try:
         dnsName = str(InetAddress.getByName(ip).getHostName())
     except JException, je:
         logger.debug(str(je))
         raise self._HOSTNAME_RESOLVE_EXCEPTION
コード例 #21
0
ファイル: Server-2.py プロジェクト: jamesjames/ScotchOARKit
 def __init__(self, TCP_IP = None, TCP_PORT = 5006):
     #Automatically assign the IP if the field is left empty
     if x.getProperty("insideDev") == "false":
         # MAKE SURE THAT THE INET INTERFACE IS THE MAIN ONE
         TCP_IP = InetAddress.getLocalHost().getHostAddress()
         print("Running outside of Dev - IP = "+TCP_IP)
     else:
         TCP_IP = 'localhost'
         print("Running in Dev")
         
     self.TCP_IP = TCP_IP
     self.TCP_PORT = TCP_PORT
     self.BUFFER_SIZE = 1024  # Normally 1024, but we want fast response
コード例 #22
0
    def _discover(self, domainDto=None):
        '''
        if domainDto is None, domain controllers of self domain will be discovered,
        else controllers for specified domain will be discovered
        '''
        result = AdDiscoveryResult()
        dtoToOshMap = result.getMap()
        siteDtoToOshMap = result.getSiteDtoToOshMap()
        containerOshMap = result.getContainerOshMap()

        client = self._daoService.getClient()
        serverDao = self._daoService.getServerDao()
        domainDao = self._daoService.getDomainDao()
        siteDao = self._daoService.getSiteDao()
        if domainDto is None:
            domainDto = domainDao.createDto(domainDao.obtainSelfDomainId())

        serverDtos = serverDao.obtainServers(domainDto)
        selfControllerId = serverDao.obtainSelfServerId()
        for dto in serverDtos:
            hostOsh = None
            functionality = None
            #if this is controller that we are triggered on
            if selfControllerId == dto.id:
                dto.fullVersion = serverDao.obtainSelfFullVersion()
                dto.ipAddress = client.getIpAddress()
                if self.__isConnectionPortReported:
                    dto.port = client.getPort()
                dto.username = client.getUserName()
                dto.credentialId = client.getCredentialId()
                functionality = serverDao.obtainSelfFunctionality()
                if self._containerOsh:
                    hostOsh = self._containerOsh
            else:
                #determine container host
                try:
                    dto.ipAddress = InetAddress.getByName(
                        dto.dnsName).getHostAddress()
                    hostOsh = HostBuilder.incompleteByIp(dto.ipAddress).build()
                except JException:
                    logger.debug('Cannot resolve IP address for fqdn %s' %
                                 dto.dnsName)
            if hostOsh:
                siteDto = siteDao.createDto(dto.siteName)
                osh = self.createOsh(dto, hostOsh, functionality)
                dtoToOshMap[dto] = osh
                siteDtoToOshMap[siteDto] = osh
                containerOshMap[dto] = hostOsh
        return result
コード例 #23
0
ファイル: netutils.py プロジェクト: ddonnelly19/dd-git
 def resolveIpsByHostname(self, hostname):
     '''@types: str -> list[str]
     @raise ResolveException: Failed to resolve IPs
     @note: When resolved IP is local (loopback) it will be replaced
     with destination IP address if such was specified
     while initializing this DNS resolver
     '''
     if not hostname:
         raise ValueError("hostname is not specified")
     ip = None
     try:
         ip = str(InetAddress.getByName(hostname).getHostAddress())
     except JException, ex:
         logger.debug(str(ex))
         raise self._IP_RESOLVE_EXCEPTION
コード例 #24
0
ファイル: netutils.py プロジェクト: deezeesms/dd-git
 def resolveIpsByHostname(self, hostname):
     '''@types: str -> list[str]
     @raise ResolveException: Failed to resolve IPs
     @note: When resolved IP is local (loopback) it will be replaced
     with destination IP address if such was specified
     while initializing this DNS resolver
     '''
     if not hostname:
         raise ValueError("hostname is not specified")
     ip = None
     try:
         ip = str(InetAddress.getByName(hostname).getHostAddress())
     except JException, ex:
         logger.debug(str(ex))
         raise self._IP_RESOLVE_EXCEPTION
コード例 #25
0
ファイル: python_console.py プロジェクト: giflw/afn-tools
def init(context):
    if not File("storage/python_console.props").exists():
        context.log("storage/python_console.props does not exist")
        return
    context.log("storage/python_console.props exists; proceeding with load")
    props = Properties()
    props.load(FileInputStream(File("storage/python_console.props"))) 
    server = ServerSocket(int(props["port"]), 20,
                          InetAddress.getByName(props["host"])
                          if "host" in props else None)
    class ServerThread(Thread):
        def run(self):
            while not server.isClosed():
                socket = server.accept()
                HandlerThread(socket).start()
    ServerThread().start()
コード例 #26
0
    def _discover(self, domainDto=None):
        '''
        if domainDto is None, domain controllers of self domain will be discovered,
        else controllers for specified domain will be discovered
        '''
        result = AdDiscoveryResult()
        dtoToOshMap = result.getMap()
        siteDtoToOshMap = result.getSiteDtoToOshMap()
        containerOshMap = result.getContainerOshMap()

        client = self._daoService.getClient()
        serverDao = self._daoService.getServerDao()
        domainDao = self._daoService.getDomainDao()
        siteDao = self._daoService.getSiteDao()
        if domainDto is None:
            domainDto = domainDao.createDto(domainDao.obtainSelfDomainId())

        serverDtos = serverDao.obtainServers(domainDto)
        selfControllerId = serverDao.obtainSelfServerId()
        for dto in serverDtos:
            hostOsh = None
            functionality = None
            #if this is controller that we are triggered on
            if selfControllerId == dto.id:
                dto.fullVersion = serverDao.obtainSelfFullVersion()
                dto.ipAddress = client.getIpAddress()
                if self.__isConnectionPortReported:
                    dto.port = client.getPort()
                dto.username = client.getUserName()
                dto.credentialId = client.getCredentialId()
                functionality = serverDao.obtainSelfFunctionality()
                if self._containerOsh:
                    hostOsh = self._containerOsh
            else:
                #determine container host
                try:
                    dto.ipAddress = InetAddress.getByName(dto.dnsName).getHostAddress()
                    hostOsh = HostBuilder.incompleteByIp(dto.ipAddress).build()
                except JException:
                    logger.debug('Cannot resolve IP address for fqdn %s' % dto.dnsName)
            if hostOsh:
                siteDto = siteDao.createDto(dto.siteName)
                osh = self.createOsh(dto, hostOsh, functionality)
                dtoToOshMap[dto] = osh
                siteDtoToOshMap[siteDto] = osh
                containerOshMap[dto] = hostOsh
        return result
コード例 #27
0
def isOnDifferentHost():

    node = AdminControl.getNode()
    nodeId = AdminConfig.getid("/Node:" + node + "/")
    targetHostname = AdminConfig.showAttribute(nodeId, 'hostName')
    try:
        localHostname = InetAddress.getLocalHost().getCanonicalHostName()
    except:
        localHostname = "cannot_be_determined"

    if (localHostname.lower()) != (targetHostname.lower()):
        print "localHostname is: " + localHostname
        print "targetHostname is: " + targetHostname
        if localHostname == "cannot_be_determined":
            print "isOnDifferentHost returns false because hostname cannot be determined"
            return False
        else:
            return True
コード例 #28
0
ファイル: netutils.py プロジェクト: deezeesms/dd-git
def getHostAddress(dnsName, defaultValue=None):
    """
    @deprecated: Use SocketDnsResolver().resolve_ips(dnsName)

    Resolves the host name to the IP Address in DNS table.
    On failure to resolve the name, the default value parameter is returned.
    @param  dnsName: host name to resolve
    @type     dnsName: string
    @param  defaultValue: the value to return if the host name cannot be resolved
    @return: IP address of the resolved host name
    @rtype: string
    """
    if dnsName and dnsName.strip():
        try:
            return str(InetAddress.getByName(dnsName).getHostAddress())
        except:
            logger.debugException('Could not resolve DNS name: ', dnsName)
    return defaultValue
コード例 #29
0
ファイル: WebAdmin.py プロジェクト: gamer-lineage2/s4L2J
 def handle(self, exchange):
     if not exchange.getRemoteAddress().getAddress() == InetAddress.getByAddress([127, 0, 0, 1]):
         exchange.sendResponseHeaders(403, 0)
         exchange.close()
         return
     try:
         i = exchange.getRequestBody()
         ibuff = ""
         while True:
             temp = i.read()
             if temp == -1:
                 break
             ibuff += chr(temp)
         ibuff = _codecs.utf_8_decode(ibuff)[0]
         self.handleImpl(exchange, ibuff)
     except:
         exchange.sendResponseHeaders(500, 0)
     exchange.close()
コード例 #30
0
ファイル: netutils.py プロジェクト: ddonnelly19/dd-git
def getHostAddress(dnsName, defaultValue=None):
    """
    @deprecated: Use SocketDnsResolver().resolve_ips(dnsName)

    Resolves the host name to the IP Address in DNS table.
    On failure to resolve the name, the default value parameter is returned.
    @param  dnsName: host name to resolve
    @type     dnsName: string
    @param  defaultValue: the value to return if the host name cannot be resolved
    @return: IP address of the resolved host name
    @rtype: string
    """
    if dnsName and dnsName.strip():
        try:
            return str(InetAddress.getByName(dnsName).getHostAddress())
        except:
            logger.debugException('Could not resolve DNS name: ', dnsName)
    return defaultValue
コード例 #31
0
 def handle(self, exchange):
     if not exchange.getRemoteAddress().getAddress(
     ) == InetAddress.getByAddress([127, 0, 0, 1]):
         exchange.sendResponseHeaders(403, 0)
         exchange.close()
         return
     try:
         i = exchange.getRequestBody()
         ibuff = ""
         while True:
             temp = i.read()
             if temp == -1:
                 break
             ibuff += chr(temp)
         ibuff = _codecs.utf_8_decode(ibuff)[0]
         self.handleImpl(exchange, ibuff)
     except:
         exchange.sendResponseHeaders(500, 0)
     exchange.close()
コード例 #32
0
ファイル: PiNetJython.py プロジェクト: rdnelson/Hazzard
	def __init__(self, port=9001):
		self.__setPort(port)
		
		if self.debug: print 'Creating socket for receiving'
		
		# Create the socket for receiving
		self.sock_receive = MulticastSocket(InetSocketAddress("0", port))
		self.sock_receive.joinGroup(InetAddress.getByName(MCAST_IP))
		self.sock_receive.setTimeToLive(2)
		self.sock_receive.setSoTimeout(0)
		
		#self.sock_receive.sock_impl.jsocket = jmultisock
		
		if self.debug: print 'Socket created, bound to ', port

		if self.debug: print 'Joining multicast group'
		
		
		if self.debug: 
			print 'Init finished'
			print ''
			
		thread.start_new_thread(self.receiver, ())
コード例 #33
0
ファイル: model.py プロジェクト: jufei/BtsShell
    def __init__(self, address, port, update_interval, auto_reconnect, definitions_file_path, ftp_port, ftp_username, ftp_password):
        builder = NetworkDataProvider2.forAddress(InetAddress.getByName(address))\
            .withInfoModelPort(port)\
            .connectToRealBts()\
            .reconnectAutomatically(auto_reconnect)\
            .updateIntervalMs(update_interval)

        if definitions_file_path:
            object_definitions = ObjectDefinitionsFactory.getObjectDefinitions(File(definitions_file_path))
        else:
            ftp_properties = FtpProperties(address, ftp_port, ftp_username, ftp_password)
            object_definitions = ObjectDefinitionsFactory.getDefinitionsFromFtp(ftp_properties)

        builder.objectDefinitions(object_definitions)
        self.provider = builder.build()

        self.connection_manager = ConnectionManager()
        self.change_manager = ModelChangeManager()
        self.connection_status_monitor = ConnectionStatusChangeMonitor()
        self.model_change_monitor = ModelChangeMonitor()
        self.connection_status_monitor.register(self.connection_manager)
        self.model_change_monitor.register(self.change_manager)
        self.provider.registerForConnectionStatus(self.connection_status_monitor)
        self.provider.registerListener(self.model_change_monitor)
コード例 #34
0
#
# java -cp bin:../../java-router/build/deploy/lib/RawSocket.jar:../../java-router/build/deploy/lib/JythonRouter.jar:../../java-router/ThirdParty/jython2.5.1/jython.jar Main ../../java-router/code/scripts/preconfig.py ../../java-router/code/scripts/simple-ping.py

from code.messy.net.ethernet import Ethertype, ArpHandler
from code.messy.net.ip import IpProtocolHandler, PacketToIp, IpPacket
from code.messy.net.ip.icmp import IcmpHandler
from code.messy.net.ip.route import LocalSubnet
from java.net import InetAddress

icmp = IcmpHandler()
protocol = IpProtocolHandler()
protocol.register(IpPacket.Protocol.ICMP, icmp)
pak2Ip = PacketToIp(protocol)

arp = ArpHandler()

address = InetAddress.getByName('10.0.0.2')
LocalSubnet.create(address, 24, interface['eth1'])

address = InetAddress.getByName('10.1.0.2')
LocalSubnet.create(address, 24, interface['eth2'])

interface['eth1'].register(Ethertype.ARP, arp)
interface['eth2'].register(Ethertype.ARP, arp)

interface['eth1'].register(Ethertype.IP, pak2Ip)
interface['eth2'].register(Ethertype.IP, pak2Ip)

interface['eth1'].start()
interface['eth2'].start()
コード例 #35
0
ファイル: jelh5.py プロジェクト: filipealmeida/probespawner
    def __init__(self, config):
    	if isinstance(config, basestring):
            self.config = json.loads(config.decode('utf-8'))
    	else:
            self.config = config
        self.runtime = {}
        #TODO: ugly ugly initialization all around, review, make it sane
        clusterName = "elasticsearch"
        host = "localhost"
        port = 9300

        if "host" in self.config:
            host = self.config["host"]
        else:
            host = "localhost"
        if "port" in self.config:
            port = self.config["port"]
        else:
            port = "9300"
        if "bulkActions" not in self.config:
            self.config["bulkActions"] = 1000
        if "bulkSize" not in self.config:
            self.config["bulkSize"] = 107374182400
        if "flushInterval" not in self.config:
            self.config["flushInterval"] = 60000
        if "concurrentRequests" not in self.config:
            self.config["concurrentRequests"] = 1
        if "actionRetryTimeout" not in self.config:
            self.config["actionRetryTimeout"] = 5
        if "type" not in self.config:
            self.config["type"] = "logs"
        if "indexPrefix" not in self.config:
            self.config["indexPrefix"] = "sampleindex"
        if "indexSuffix" not in self.config:
            self.config["indexSuffix"] = "-%Y.%m.%d"
        logger.debug("Initializing elasticsearch output %s: %s", self.config["indexPrefix"], json.dumps("self.config"))
        self.config["settings"] = Settings.builder();
        if "options" not in self.config:
            self.config["options"] = {}
            if "cluster" in self.config:
                self.config["options"]["cluster.name"] = self.config["cluster"]
            else:
                self.config["options"]["cluster.name"] = "elasticsearch"
        else:
            if "cluster.name" not in self.config["options"]:
                if "cluster" in self.config:
                    self.config["options"]["cluster.name"] = self.config["cluster"]
                else:
                    self.config["options"]["cluster.name"] = "elasticsearch"

        for setting in self.config["options"]:
            value = self.config["options"][setting]
            logger.info("Setting Elasticsearch options: %s = %s", setting, value)
            self.config["settings"].put(setting, value)

        self.config["settings"].build()
        self.runtime["client"] = PreBuiltTransportClient(self.config["settings"].build(), [])
        if "host" in self.config:
            address = InetSocketTransportAddress(InetAddress.getByName(host), int(port))
            self.runtime["client"].addTransportAddress(address)
        if "hosts" in self.config:
            for hostport in self.config["hosts"]:
                host, port = hostport.split(":")
                address = InetSocketTransportAddress(InetAddress.getByName(host), int(port))
                logger.info("Setting Elasticsearch host: %s = %s", host, port)
                self.runtime["client"].addTransportAddress(address)

        self.readyBulk()
        self.runtime["indices"] = {}
コード例 #36
0
ファイル: GamerConfiguration.py プロジェクト: hobson/ggpy
 def getComputerName(cls):
     """ generated source for method getComputerName """
     try:
         return InetAddress.getLocalHost().getHostName().lower()
     except Exception as e:
         return None
コード例 #37
0
def DiscoveryMain(Framework):

    OSHVResult = ObjectStateHolderVector()
    ms_domain_name = Framework.getDestinationAttribute('ms_domain_name')
    if not ms_domain_name:
        ms_domain_name = 'NULL'

    try:
        netUtil = MsNetworkUtil()
        hostsOutput = netUtil.doNetServerEnum('NULL', SV_TYPE_SERVER,
                                              ms_domain_name)
        if hostsOutput != None:
            discoverUnknownIPs = 1
            try:
                strDiscoverUnknownIPs = Framework.getParameter(
                    'discoverUnknownIPs')
                discoverUnknownIPs = Boolean.parseBoolean(
                    strDiscoverUnknownIPs)
            except:
                pass

            oshMsDomain = ObjectStateHolder('msdomain')
            oshMsDomain.setStringAttribute('data_name', ms_domain_name)
            alreadyDiscoveredIps = HashMap()
            for hostInfo in hostsOutput:
                hostType = Long(hostInfo[1]).longValue()
                hostName = (str(hostInfo[0])).lower()
                try:
                    ip = InetAddress.getByName(hostInfo[0]).getHostAddress()
                    if netutils.isLocalIp(ip):
                        continue
                    cachedHostName = alreadyDiscoveredIps.get(ip)
                    if cachedHostName != None:
                        logger.debug(
                            'IP ', ip,
                            ' already reported for host ' + cachedHostName,
                            ' current host ', hostName, ' - skipping')
                        continue
                    else:
                        logger.debug('Discovered IP ' + ip + ' for host ' +
                                     hostName)
                        alreadyDiscoveredIps.put(ip, hostName)
                    ipDomain = DomainScopeManager.getDomainByIp(ip)
                    if not discoverUnknownIPs and ipDomain == 'unknown':
                        logger.debug(
                            'ip: ' + ip +
                            ' is out of probe range and will be excluded')
                        continue
                    if SV_TYPE_CLUSTER_NT & hostType:
                        logger.debug(
                            'Not reporting the entry %s because it is a Cluster'
                            % hostName)
                        continue
                    hostOsType = 'nt'
                    if SV_TYPE_SERVER_UNIX & hostType:
                        hostOsType = 'unix'
                    oshHost = modeling.createHostOSH(ip, hostOsType)
                    oshHost.setStringAttribute("host_hostname", hostName)
                    OSHVResult.add(oshHost)

                    link = modeling.createLinkOSH('member', oshMsDomain,
                                                  oshHost)
                    OSHVResult.add(link)
                    ipOSH = modeling.createIpOSH(ip)
                    OSHVResult.add(ipOSH)
                    contained = modeling.createLinkOSH('contained', oshHost,
                                                       ipOSH)
                    OSHVResult.add(contained)
                except:
                    errorMsg = str(sys.exc_info()[1]).strip()
                    logger.warn('Failed to resolve host ', hostInfo[0], ' : ',
                                errorMsg)
        else:
            message = 'Failed to discover hosts on MS Domain'
            logger.warn(message)
            logger.reportWarning(message)
    except:
        errorMsg = str(sys.exc_info()[1]).strip()
        logger.errorException('Failed to discovery MS Domains')
        errorMessage = errormessages.makeErrorMessage(
            "msdomain", errorMsg,
            errormessages.ERROR_FAILED_DISCOVERING_MSDOMAIN_HOSTS)
        errobj = errorobject.createError(
            errorcodes.FAILED_DISCOVERIING_MSDOMAIN_HOST,
            ["msdomain", errorMsg], errorMessage)
        logger.reportErrorObject(errobj)
    return OSHVResult
コード例 #38
0
def DiscoveryMain(Framework):

    OSHVResult = ObjectStateHolderVector()
    ms_domain_name = Framework.getDestinationAttribute('ms_domain_name')
    if not ms_domain_name:
        ms_domain_name = 'NULL'

    try:
        netUtil = MsNetworkUtil()
        hostsOutput = netUtil.doNetServerEnum('NULL',SV_TYPE_SERVER, ms_domain_name)
        if hostsOutput != None:
            discoverUnknownIPs = 1
            try:
                strDiscoverUnknownIPs = Framework.getParameter('discoverUnknownIPs');
                discoverUnknownIPs = Boolean.parseBoolean(strDiscoverUnknownIPs);
            except:
                pass

            oshMsDomain = ObjectStateHolder('msdomain')
            oshMsDomain.setStringAttribute('data_name', ms_domain_name)
            alreadyDiscoveredIps = HashMap()
            for hostInfo in hostsOutput:
                hostType = Long(hostInfo[1]).longValue()
                hostName = (str(hostInfo[0])).lower()
                try:
                    ip = InetAddress.getByName(hostInfo[0]).getHostAddress()
                    if netutils.isLocalIp(ip):
                        continue
                    cachedHostName = alreadyDiscoveredIps.get(ip)
                    if cachedHostName != None:
                        logger.debug('IP ', ip, ' already reported for host ' + cachedHostName, ' current host ', hostName, ' - skipping')
                        continue
                    else:
                        logger.debug('Discovered IP ' + ip + ' for host ' + hostName)
                        alreadyDiscoveredIps.put(ip, hostName)
                    ipDomain  = DomainScopeManager.getDomainByIp(ip)
                    if not discoverUnknownIPs and ipDomain == 'unknown':
                        logger.debug('ip: ' + ip + ' is out of probe range and will be excluded')
                        continue
                    if SV_TYPE_CLUSTER_NT & hostType:
                        logger.debug('Not reporting the entry %s because it is a Cluster' % hostName)
                        continue
                    hostOsType = 'nt'
                    if SV_TYPE_SERVER_UNIX & hostType:
                        hostOsType = 'unix'
                    oshHost = modeling.createHostOSH(ip, hostOsType)
                    oshHost.setStringAttribute("host_hostname", hostName)
                    OSHVResult.add(oshHost)

                    link = modeling.createLinkOSH('member', oshMsDomain, oshHost)
                    OSHVResult.add(link)
                    ipOSH = modeling.createIpOSH(ip)
                    OSHVResult.add(ipOSH)
                    contained = modeling.createLinkOSH('contained', oshHost, ipOSH)
                    OSHVResult.add(contained)
                except:
                    errorMsg = str(sys.exc_info()[1]).strip()
                    logger.warn('Failed to resolve host ', hostInfo[0], ' : ', errorMsg)
        else:
            message = 'Failed to discover hosts on MS Domain'
            logger.warn(message)
            logger.reportWarning(message)
    except:
        errorMsg = str(sys.exc_info()[1]).strip()
        logger.errorException('Failed to discovery MS Domains')
        errorMessage = errormessages.makeErrorMessage("msdomain", errorMsg, errormessages.ERROR_FAILED_DISCOVERING_MSDOMAIN_HOSTS)
        errobj = errorobject.createError(errorcodes.FAILED_DISCOVERIING_MSDOMAIN_HOST, ["msdomain", errorMsg], errorMessage)
        logger.reportErrorObject(errobj)
    return OSHVResult
コード例 #39
0
ファイル: jelh5.py プロジェクト: eggoynes/probespawner
    def __init__(self, config):
        if isinstance(config, basestring):
            self.config = json.loads(config.decode('utf-8'))
        else:
            self.config = config
        self.runtime = {}
        #TODO: ugly ugly initialization all around, review, make it sane
        clusterName = "elasticsearch"
        host = "localhost"
        port = 9300

        if "host" in self.config:
            host = self.config["host"]
        else:
            host = "localhost"
        if "port" in self.config:
            port = self.config["port"]
        else:
            port = "9300"
        if "bulkActions" not in self.config:
            self.config["bulkActions"] = 1000
        if "bulkSize" not in self.config:
            self.config["bulkSize"] = 107374182400
        if "flushInterval" not in self.config:
            self.config["flushInterval"] = 60000
        if "concurrentRequests" not in self.config:
            self.config["concurrentRequests"] = 1
        if "actionRetryTimeout" not in self.config:
            self.config["actionRetryTimeout"] = 5
        if "type" not in self.config:
            self.config["type"] = "logs"
        if "indexPrefix" not in self.config:
            self.config["indexPrefix"] = "sampleindex"
        if "indexSuffix" not in self.config:
            self.config["indexSuffix"] = "-%Y.%m.%d"
        logger.debug("Initializing elasticsearch output %s: %s",
                     self.config["indexPrefix"], json.dumps("self.config"))
        self.config["settings"] = Settings.builder()
        if "options" not in self.config:
            self.config["options"] = {}
            if "cluster" in self.config:
                self.config["options"]["cluster.name"] = self.config["cluster"]
            else:
                self.config["options"]["cluster.name"] = "elasticsearch"
        else:
            if "cluster.name" not in self.config["options"]:
                if "cluster" in self.config:
                    self.config["options"]["cluster.name"] = self.config[
                        "cluster"]
                else:
                    self.config["options"]["cluster.name"] = "elasticsearch"

        for setting in self.config["options"]:
            value = self.config["options"][setting]
            logger.info("Setting Elasticsearch options: %s = %s", setting,
                        value)
            self.config["settings"].put(setting, value)

        self.config["settings"].build()
        self.runtime["client"] = PreBuiltTransportClient(
            self.config["settings"].build(), [])
        if "host" in self.config:
            address = InetSocketTransportAddress(InetAddress.getByName(host),
                                                 int(port))
            self.runtime["client"].addTransportAddress(address)
        if "hosts" in self.config:
            for hostport in self.config["hosts"]:
                host, port = hostport.split(":")
                address = InetSocketTransportAddress(
                    InetAddress.getByName(host), int(port))
                logger.info("Setting Elasticsearch host: %s = %s", host, port)
                self.runtime["client"].addTransportAddress(address)

        self.readyBulk()
        self.runtime["indices"] = {}
コード例 #40
0
    def __init__(self, additionalVariables):
        " initialize oracle database"
        
        self.__hostname = "localhost";
        try:
            self.__hostname = InetAddress.getLocalHost().getCanonicalHostName()
        except:
            type, value, traceback = sys.exc_info()
            logger.severe("Hostname error:" + `value`)
        
        additionalVariables.add(RuntimeContextVariable("ORACLE_HOSTNAME", self.__hostname, RuntimeContextVariable.ENVIRONMENT_TYPE))

        dbPassword = getVariableValue("DB_PASSWORD_ALL")
        
        if dbPassword and dbPassword.strip():
            self.__sysPassword = dbPassword
            additionalVariables.add(RuntimeContextVariable("SYS_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE))
            additionalVariables.add(RuntimeContextVariable("DBSNMP_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE));
            additionalVariables.add(RuntimeContextVariable("SYSMAN_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE))
            additionalVariables.add(RuntimeContextVariable("SYSTEM_PWD", dbPassword, RuntimeContextVariable.ENVIRONMENT_TYPE));
        else:
            self.__sysPassword = getVariableValue("SYS_PWD")
            
        dbDataLocation = getVariableValue("DB_DATA_LOC")
        if dbDataLocation and os.path.isdir(dbDataLocation):
            dbName = getVariableValue("DB_NAME")
            
            dbDataDir = os.path.join(dbDataLocation, dbName)
            if os.path.isdir(dbDataDir):
                logger.info("DB Data directory already exists:" + dbDataDir + "; Setting DB_INSTALL_OPTION to INSTALL_DB_SWONLY")
                additionalVariables.add(RuntimeContextVariable( "DB_INSTALL_OPTION", "INSTALL_DB_SWONLY", RuntimeContextVariable.ENVIRONMENT_TYPE))
        

        tcpPort = getVariableValue("TCP_PORT");
        self.__serviceName = getVariableValue("DB_GLOBAL_NAME")

        sb = StringBuilder("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)")
        sb.append("(HOST=").append(self.__hostname).append(")")
        sb.append("(PORT=").append(tcpPort).append("))")
        sb.append("(CONNECT_DATA=(SERVICE_NAME=").append(self.__serviceName).append(")))")
        
        self.__oracleServiceUrl = sb.toString()
        
        logger.info("Oracle listener service URL:" + self.__oracleServiceUrl)
        
        self.__jdbcUrl = "jdbc:oracle:thin:@" + self.__hostname +":"+ tcpPort + ":" + self.__serviceName
        runtimeContext.addVariable(RuntimeContextVariable("JDBC_URL", self.__jdbcUrl, RuntimeContextVariable.STRING_TYPE, "Oracle Thin Driver JDBC Url", True, RuntimeContextVariable.NO_INCREMENT))
        
        
        oracleDriver = "oracle.jdbc.OracleDriver"
        runtimeContext.addVariable(RuntimeContextVariable("JDBC_DRIVER", oracleDriver, RuntimeContextVariable.STRING_TYPE, "Oracle Thin Driver class", True, RuntimeContextVariable.NO_INCREMENT))
        
        self.__dbControl = Boolean.parseBoolean(getVariableValue("CONFIG_DBCONTROL", "false"))
        
        if self.__dbControl:
            self.__dbCtrlPort = getVariableValue("DBCONTROL_HTTP_PORT")
            additionalVariables.add(RuntimeContextVariable( "HTTPS_PORT", self.__dbCtrlPort, RuntimeContextVariable.STRING_TYPE))
        
        oracleDir = getVariableValue("ORACLE_DIR")
        self.__markerFilePath = os.path.join(oracleDir, ".#dsoracle")
        
        self.__maintFilePath = getVariableValue("ORACLE_MAINT_FILE")
        
        dbInstallOption = getVariableValue("DB_INSTALL_OPTION")
        if dbInstallOption == "INSTALL_DB_AND_CONFIG":
            globalLockString = "OracleEnabler-" + self.__hostname
            logger.info("Requesting Global Lock with name: " + globalLockString)
            domain = proxy.getContainer().getCurrentDomain()
            options = domain.getOptions()
            maxActivationTimeOut = options.getProperty(Options.MAX_ACTIVATION_TIME_IN_SECONDS)
            lockTimeOut = Long.parseLong(maxActivationTimeOut) * 1000
            acquired = ContainerUtils.acquireGlobalLock(globalLockString, lockTimeOut , lockTimeOut)
            if acquired:
                logger.info("Acquired Global lock with name: " + globalLockString)
            else:
                logger.severe("Could not acquire Global lock with name: " + globalLockString)
                raise Exception("Could not acquire Global lock with name: " + globalLockString)
コード例 #41
0
def resolveHostIp(hostName):
    try:
        return InetAddress.getByName(hostName).getHostAddress()
    except UnknownHostException:
        logger.debug("Failed to resolve IP for host '%s'" % hostName)
コード例 #42
0
ファイル: src9.py プロジェクト: bgarciaentornos/turnitin
{rmessage=Successful!, userid=17463581, classid=2836734, assignmentid=7902887, rcode=41}
Adding an assignment with another inst
{'fid': '4', 'diagnostic': '0', 'ufn': 'StevenIU', 'uln': 'GithensIU', 'username': '******', 'assignid': 'AssignmentTitle2650fcca-b96e-42bd-926e-63660076d2ad', 'aid': '56021', 'src': '9', 'cid': '2836733', 'said': '56021', 'dtstart': '20091225', 'encrypt': '0', 'assign': 'AssignmentTitle2650fcca-b96e-42bd-926e-63660076d2ad', 'uem': '*****@*****.**', 'utp': '2', 'fcmd': '2', 'ctl': 'CourseTitle46abd163-7464-4d21-a2c0-90c5af3312ab', 'dtdue': '20100101'}
{rmessage=Successful!, userid=17463581, classid=2836734, assignmentid=7902888, rcode=41}



"""
import unittest
import random
import sys
from org.sakaiproject.component.cover import ComponentManager
from java.net import InetSocketAddress, Proxy, InetAddress
from java.util import HashMap

debug_proxy = Proxy(Proxy.Type.HTTP, InetSocketAddress(InetAddress.getByName("127.0.0.1"),8008))

tiireview_serv = ComponentManager.get("org.sakaiproject.contentreview.service.ContentReviewService")

class SakaiUuid(object):
    """My Current Jython impl doens't seem to have UUID, so re-implementing it 
    for now"""

    def __init__(self):
        self.idmanager = ComponentManager.get("org.sakaiproject.id.api.IdManager")

    def uuid1(self):
        return self.idmanager.createUuid()

uuid = SakaiUuid()
コード例 #43
0
from java.net import InetAddress as ip

website = raw_input("Enter website name: ")


#request serviced:
print (ip.getByName(website))

print ()
print ("all address: ")
for k in ip.getAllByName(website):
	print (k)
コード例 #44
0
ファイル: simple-ping.py プロジェクト: abdi256/java-router
#
# java -cp bin:../../java-router/build/deploy/lib/RawSocket.jar:../../java-router/build/deploy/lib/JythonRouter.jar:../../java-router/ThirdParty/jython2.5.1/jython.jar Main ../../java-router/code/scripts/preconfig.py ../../java-router/code/scripts/simple-ping.py

from code.messy.net.ethernet import Ethertype, ArpHandler
from code.messy.net.ip import IpProtocolHandler, PacketToIp, IpPacket
from code.messy.net.ip.icmp import IcmpHandler
from code.messy.net.ip.route import LocalSubnet
from java.net import InetAddress

icmp = IcmpHandler()
protocol = IpProtocolHandler()
protocol.register(IpPacket.Protocol.ICMP, icmp)
pak2Ip = PacketToIp(protocol)

arp = ArpHandler()

address = InetAddress.getByName('10.0.0.2')
LocalSubnet.create(address, 24, interface['eth1'])

address = InetAddress.getByName('10.1.0.2');
LocalSubnet.create(address, 24, interface['eth2'])

interface['eth1'].register(Ethertype.ARP, arp)
interface['eth2'].register(Ethertype.ARP, arp)

interface['eth1'].register(Ethertype.IP, pak2Ip)
interface['eth2'].register(Ethertype.IP, pak2Ip)

interface['eth1'].start()
interface['eth2'].start()
コード例 #45
0
 def __init__(self, IPaddress = "localhost", port = 57110):
    self.IPaddress = InetAddress.getByName(IPaddress)    # holds IP address of OSC device to connect with
    self.port = port                                     # and its listening port
    self.portOut = OSCPortOut(self.IPaddress, self.port) # create the connection
コード例 #46
0
ファイル: osc.py プロジェクト: HenryStevens/jes
 def __init__(self, IPaddress = "localhost", port = 57110):
    self.IPaddress = InetAddress.getByName(IPaddress)    # holds IP address of OSC device to connect with
    self.port = port                                     # and its listening port
    self.portOut = OSCPortOut(self.IPaddress, self.port) # create the connection
コード例 #47
0
 def __init__(self, host=config.monomeHost, port=config.monomePort, prefix=config.monomePrefix, width=config.monomeWidth, height=config.monomeHeight):
     self.transmitter = UDPTransmitter(InetAddress.getByName(host), port)
     self.prefix = prefix
     self.width = width
     self.height = height
コード例 #48
0
ファイル: static-route.py プロジェクト: abdi256/java-router
from code.messy.net.ethernet import Ethertype, ArpHandler, EthernetIpSupport

from code.messy.net.ip import IpProtocolHandler, IpPacket
from code.messy.net.ip.udp import UdpHandler
from code.messy.net.ip.dhcp import DhcpHandler
from code.messy.net.ip.route import LocalSubnet, RouteHandler, RoutingTable
from java.net import InetAddress

route = RouteHandler()
eth1ip = EthernetIpSupport(interface['eth1'])
eth2ip = EthernetIpSupport(interface['eth2'])

address = InetAddress.getByName('10.1.0.1');
eth1network = LocalSubnet.create(address, 24, eth1ip)
address = InetAddress.getByName('10.2.0.1');
eth2network = LocalSubnet.create(address, 24, eth2ip)

udp1 = UdpHandler()
protocol1 = IpProtocolHandler()
protocol1.register(IpPacket.Protocol.UDP, udp1)
protocol1.register(route)
dhcp1 = DhcpHandler(eth1network)
udp1.add(None, 67, dhcp1)

udp2 = UdpHandler()
protocol2 = IpProtocolHandler()
protocol2.register(IpPacket.Protocol.UDP, udp2)
protocol2.register(route)
dhcp2 = DhcpHandler(eth2network)
udp2.add(None, 67, dhcp2)
コード例 #49
0
if __name__ == '__main__':
    from wlstModule import *  # @UnusedWildImport

from java.net import InetAddress
from java.util.logging import *
from java.util.logging import Logger
import sys

logger = Logger.getLogger("scratch")

print "" + InetAddress.getLocalHost().getHostName()
コード例 #50
0
    def __init__(self, additionalVariables):
        " initialize oracle database"

        self.__hostname = "localhost"
        try:
            self.__hostname = InetAddress.getLocalHost().getCanonicalHostName()
        except:
            type, value, traceback = sys.exc_info()
            logger.severe("Hostname error:" + ` value `)

        additionalVariables.add(
            RuntimeContextVariable("ORACLE_HOSTNAME", self.__hostname,
                                   RuntimeContextVariable.ENVIRONMENT_TYPE,
                                   "Oracle Hostname", True,
                                   RuntimeContextVariable.NO_INCREMENT))

        listenAddress = getVariableValue("LISTEN_ADDRESS")
        additionalVariables.add(
            RuntimeContextVariable("ORACLE_LISTEN_ADDRESS", listenAddress,
                                   RuntimeContextVariable.ENVIRONMENT_TYPE,
                                   "Oracle Listen Address", True,
                                   RuntimeContextVariable.NO_INCREMENT))

        dbPassword = getVariableValue("DB_PASSWORD_ALL")

        if dbPassword and dbPassword.strip():
            self.__sysPassword = dbPassword
            additionalVariables.add(
                RuntimeContextVariable(
                    "SYS_PWD", dbPassword,
                    RuntimeContextVariable.ENVIRONMENT_TYPE))
            additionalVariables.add(
                RuntimeContextVariable(
                    "DBSNMP_PWD", dbPassword,
                    RuntimeContextVariable.ENVIRONMENT_TYPE))
            additionalVariables.add(
                RuntimeContextVariable(
                    "SYSMAN_PWD", dbPassword,
                    RuntimeContextVariable.ENVIRONMENT_TYPE))
            additionalVariables.add(
                RuntimeContextVariable(
                    "SYSTEM_PWD", dbPassword,
                    RuntimeContextVariable.ENVIRONMENT_TYPE))
        else:
            self.__sysPassword = getVariableValue("SYS_PWD")

        dbDataLocation = getVariableValue("DB_DATA_LOC")
        if dbDataLocation and os.path.isdir(dbDataLocation):
            dbName = getVariableValue("DB_NAME")

            dbDataDir = os.path.join(dbDataLocation, dbName)
            if os.path.isdir(dbDataDir):
                logger.info("DB Data directory already exists:" + dbDataDir +
                            "; Setting DB_INSTALL_OPTION to INSTALL_DB_SWONLY")
                additionalVariables.add(
                    RuntimeContextVariable(
                        "DB_INSTALL_OPTION", "INSTALL_DB_SWONLY",
                        RuntimeContextVariable.ENVIRONMENT_TYPE))

        tcpPort = getVariableValue("TCP_PORT")
        self.__serviceName = getVariableValue("DB_GLOBAL_NAME")

        sb = StringBuilder(
            "jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)")
        sb.append("(HOST=").append(self.__hostname).append(")")
        sb.append("(PORT=").append(tcpPort).append("))")
        sb.append("(CONNECT_DATA=(SERVICE_NAME=").append(
            self.__serviceName).append(")))")

        self.__oracleServiceUrl = sb.toString()

        logger.info("Oracle listener service URL:" + self.__oracleServiceUrl)

        self.__jdbcUrl = "jdbc:oracle:thin:@" + self.__hostname + ":" + tcpPort + ":" + self.__serviceName
        additionalVariables.add(
            RuntimeContextVariable("JDBC_URL", self.__jdbcUrl,
                                   RuntimeContextVariable.STRING_TYPE,
                                   "Oracle Thin Driver JDBC Url", True,
                                   RuntimeContextVariable.NO_INCREMENT))

        oracleDriver = "oracle.jdbc.OracleDriver"
        additionalVariables.add(
            RuntimeContextVariable("JDBC_DRIVER", oracleDriver,
                                   RuntimeContextVariable.STRING_TYPE,
                                   "Oracle Thin Driver class", True,
                                   RuntimeContextVariable.NO_INCREMENT))

        self.__dbControl = Boolean.parseBoolean(
            getVariableValue("CONFIG_DBCONTROL", "false"))

        if self.__dbControl:
            self.__dbCtrlPort = getVariableValue("DBCONTROL_HTTP_PORT")
            additionalVariables.add(
                RuntimeContextVariable("HTTPS_PORT", self.__dbCtrlPort,
                                       RuntimeContextVariable.STRING_TYPE))

        oracleDir = getVariableValue("ORACLE_DIR")
        self.__markerFilePath = os.path.join(oracleDir, ".#dsoracle")

        self.__maintFilePath = getVariableValue("ORACLE_MAINT_FILE")

        dbInstallOption = getVariableValue("DB_INSTALL_OPTION")
        if dbInstallOption == "INSTALL_DB_AND_CONFIG":
            globalLockString = "OracleEnabler-" + self.__hostname
            logger.info("Requesting Global Lock with name: " +
                        globalLockString)
            domain = proxy.getContainer().getCurrentDomain()
            options = domain.getOptions()
            maxActivationTimeOut = options.getProperty(
                Options.MAX_ACTIVATION_TIME_IN_SECONDS)
            lockTimeOut = Long.parseLong(maxActivationTimeOut) * 1000
            acquired = ContainerUtils.acquireGlobalLock(
                globalLockString, lockTimeOut, lockTimeOut)
            if acquired:
                logger.info("Acquired Global lock with name: " +
                            globalLockString)
            else:
                logger.severe("Could not acquire Global lock with name: " +
                              globalLockString)
                raise Exception("Could not acquire Global lock with name: " +
                                globalLockString)
コード例 #51
0
ファイル: plugins_mom.py プロジェクト: ddonnelly19/dd-git
def resolveHostIp(hostName):
    try: 
        return InetAddress.getByName(hostName).getHostAddress()
    except UnknownHostException:
        logger.debug("Failed to resolve IP for host '%s'" % hostName)
コード例 #52
0
ファイル: src9.py プロジェクト: sakai-mirror/turnitin
Adding an assignment with another inst
{'fid': '4', 'diagnostic': '0', 'ufn': 'StevenIU', 'uln': 'GithensIU', 'username': '******', 'assignid': 'AssignmentTitle2650fcca-b96e-42bd-926e-63660076d2ad', 'aid': '56021', 'src': '9', 'cid': '2836733', 'said': '56021', 'dtstart': '20091225', 'encrypt': '0', 'assign': 'AssignmentTitle2650fcca-b96e-42bd-926e-63660076d2ad', 'uem': '*****@*****.**', 'utp': '2', 'fcmd': '2', 'ctl': 'CourseTitle46abd163-7464-4d21-a2c0-90c5af3312ab', 'dtdue': '20100101'}
{rmessage=Successful!, userid=17463581, classid=2836734, assignmentid=7902888, rcode=41}



"""
import unittest
import random
import sys
from org.sakaiproject.component.cover import ComponentManager
from java.net import InetSocketAddress, Proxy, InetAddress
from java.util import HashMap

debug_proxy = Proxy(
    Proxy.Type.HTTP, InetSocketAddress(InetAddress.getByName("127.0.0.1"),
                                       8008))

tiireview_serv = ComponentManager.get(
    "org.sakaiproject.contentreview.service.ContentReviewService")


class SakaiUuid(object):
    """My Current Jython impl doens't seem to have UUID, so re-implementing it 
    for now"""
    def __init__(self):
        self.idmanager = ComponentManager.get(
            "org.sakaiproject.id.api.IdManager")

    def uuid1(self):
        return self.idmanager.createUuid()