예제 #1
0
파일: scp.py 프로젝트: ddonnelly19/dd-git
def resolveIPByINet(hostname, port):
    ipAddresses = []
    try:
        if port:
            logger.debug('Try to resolve host name by INet:%s(%s)' % (hostname, type(hostname)))
            inetAddress = InetSocketAddress(hostname, port).getAddress()
            if inetAddress:
                ipAddresses.append(inetAddress.getHostAddress())
    except:
        logger.debug('Fail to resolve host name by INet:%s' % hostname)
    return ipAddresses
예제 #2
0
def _get_inet_addr(addr):
    # FIXME how should this function take in account various families?
    # FIXME better error parsing; follow CPython, this must be defined
    if addr is None:
        return InetSocketAddress(0)
    host, port = addr
    if host is None:
        if port is None:
            return InetSocketAddress(0)
        return InetSocketAddress(port)
    return InetSocketAddress(host, port)
예제 #3
0
파일: scp.py 프로젝트: deezeesms/dd-git
def resolveIPByINet(hostname, port):
    ipAddresses = []
    try:
        if port:
            logger.debug('Try to resolve host name by INet:%s(%s)' %
                         (hostname, type(hostname)))
            inetAddress = InetSocketAddress(hostname, port).getAddress()
            if inetAddress:
                ipAddresses.append(inetAddress.getHostAddress())
    except:
        logger.debug('Fail to resolve host name by INet:%s' % hostname)
    return ipAddresses
예제 #4
0
    def getIpFromUrlObject(self):
        if not self.ipAddresses:
            hostname = self.urlObject.getHost()
            if netutils.isValidIp(hostname):
                self.ipAddresses.append(hostname)
            else:
                port = self.getPortFromUrlObject()
                if port:
                    inetAddress = InetSocketAddress(hostname, port).getAddress()
                    if inetAddress:
                        self.ipAddresses.append(inetAddress.getHostAddress())

        return self.ipAddresses
예제 #5
0
def getIpFromUrlObject(urlObject):
    portResolveMap = {'http':80, 'https':443 }
    hostname = urlObject.getHost()
    if netutils.isValidIp(hostname):
        return hostname
    else:
        port = urlObject.getPort()
        if (port <= 0):
            proto = urlObject.getProtocol()
            if portResolveMap.has_key(proto):
                port = portResolveMap[proto]
        inetAddress = InetSocketAddress(hostname, port).getAddress()
        if inetAddress:
            return inetAddress.getHostAddress()
예제 #6
0
def getIpFromUrlObject(urlObject):
    portResolveMap = {'http':80, 'https':443 }
    hostname = urlObject.getHost()
    if netutils.isValidIp(hostname):
        return hostname
    else:
        port = urlObject.getPort()
        if (port <= 0):
            proto = urlObject.getProtocol()
            if portResolveMap.has_key(proto):
                port = portResolveMap[proto]
        inetAddress = InetSocketAddress(hostname, port).getAddress()
        if inetAddress:
            return inetAddress.getHostAddress()
예제 #7
0
    def getIpFromUrlObject(self):
        if not self.ipAddresses:
            hostname = self.urlObject.getHost()
            if netutils.isValidIp(hostname):
                self.ipAddresses.append(hostname)
            else:
                port = self.getPortFromUrlObject()
                if port:
                    inetAddress = InetSocketAddress(hostname,
                                                    port).getAddress()
                    if inetAddress:
                        self.ipAddresses.append(inetAddress.getHostAddress())

        return self.ipAddresses
예제 #8
0
def checkTcpConnectivity(ipAddress, portNumber, timeout):
    """
    Checks the  TCP connection to the given ipAddress on the given port.
    @param ipAddress: IP address of the remote computer to check
    @type ipAddress: String
    @param portNumber: The port number to check
    @type portNumber: int
    @param timeout: connection timeout in millisecondes
    @type timeout: int
    @return 1 if the TCP connection succeeded, else
    """
    socket = None
    try:
        socket = Socket()
        socket.connect(InetSocketAddress(ipAddress, portNumber), timeout)
        logger.debug('Connected to port:', portNumber, ' on host by ip:',
                     ipAddress)
        #check that the object is not null
        if (socket != None):
            try:
                #try to close the socket
                socket.close()
            except:
                #we failed to close the socket - let's log it...
                logger.debug('Failed to close socket')
        return 1
    except IOException, e:
        logger.debug('Failed to connect to port:', portNumber,
                     ' on host by ip:', ipAddress, ' IOException(',
                     e.getMessage(), ')')
        return 0
예제 #9
0
    def __init__(self, *args):
        addresses = ArrayList(len(args))
        for item in args:
            addresses.add(InetSocketAddress(item[0], item[1]))

        self.java_obj = org.vertx.java.platform.impl.JythonVerticleFactory.createDnsClient(
            addresses)
예제 #10
0
    def __init__(self, port, debug=False):

        # HTTP server declaration
        self.server = HttpServer.create(InetSocketAddress(int(port)), 0)
        self.server.createContext("/cmd",
                                  self.MyHandler(self)).getFilters().add(
                                      self.ParameterParser())
        self.server.setExecutor(None)
        self.server.start()
        logger.info("SlaveHttp - Server is listening on port %d" % (int(port)))
        self.token = HttpToken(10)
        self.sleeperQueue = SetQueue()
예제 #11
0
 def __init__(self, initStr, debug=False):
     try:
         tps,port = initStr.split(',')
     except:
         logger.error( 'Invalid - format : <tps>,<port>')
         raise
     self.set(tps)
     
     # HTTP server declaration
     self.server = HttpServer.create(InetSocketAddress(int(port)), 0);
     self.server.createContext("/cmd", self.MyHandler(self)).getFilters().add(self.ParameterParser())
     self.server.setExecutor(None)
     self.server.start()
     logger.info("HttpCadencer - Server is listening on port %d" % (port)) 
예제 #12
0
 def start(cls):
     try:
         inetSocketAddress = InetSocketAddress(cls.host, cls.port)
         cls.httpServer = HttpServer.create(inetSocketAddress,
                                            cls.socketBackLog)
         cls.httpServer.createContext("/callback", CallbackHandler())
         cls.httpServer.createContext("/start", StartHandler())
         cls.httpServer.setExecutor(
             Executors.newFixedThreadPool(cls.poolsize))
         cls.httpServer.start()
         logger.info("HTTPServerCallback is listening on %s %s" %
                     (cls.host, cls.port))
     except IOException, e:
         logger.error('(start) %s : stacktrace=%s' % (cls.__name__, e))
         raise UnboundLocalError('(start) %s : stacktrace=%s' %
                                 (cls.__name__, e))
예제 #13
0
    def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        """Sends PreparedRequest object. Returns Response object.

        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
        :param stream: (optional) Whether to stream the request content.
        :param timeout: (optional) How long to wait for the server to send
            data before giving up, as a float, or a :ref:`(connect timeout,
            read timeout) <timeouts>` tuple.
        :type timeout: float or tuple
        :param verify: (optional) Whether to verify SSL certificates.
        :param cert: (optional) Any user-provided SSL certificate to be trusted.
        :param proxies: (optional) The proxies dictionary to apply to the request.
        """

        # setup proxy object
        proxy = select_proxy(request.url,proxies)
        if proxy:
            if not self._my_proxy_obj:
                proxy = proxy[proxy.find('//')+2:]
                host,port = proxy.split(':')
                self._my_proxy_obj = Proxy(Proxy.Type.HTTP,InetSocketAddress(str(host),int(port)))
        else:
            self._my_proxy_obj = None

        # build the request
        #print 'request.method',request.method -- ignored
        #print 'request.body',request.body -- ignored
        #url = self.request_url(request, proxies) -- ignored - just the params

        u = URL(request.url)
        conn = u.openConnection(self._my_proxy_obj) if self._my_proxy_obj else u.openConnection()
        conn.setAllowUserInteraction(False)
        conn.setDoInput(True);

        self.add_headers(request)
        for k,v in request.headers.iteritems():
            conn.addRequestProperty(k,v)

        # make the request!
        try: conn.connect()
        except java.net.ConnectException, e:
            raise ConnectionError(e.getMessage())
예제 #14
0
def test_pure_java_request():
    """
    Test making a get request without using Python's requests module
    you'll need to set the proxy host and port if needed
    returns the status code. May raise errors.
    """
    ignoreJavaSSL() # will raise error if not 'java'
    # setup proxy
    proxyHost = ""
    proxyPort = 0
    if proxyHost:
        #import java.net.Proxy as Proxy # @UnresolvedImport
        #import java.net.InetSocketAddress as InetSocketAddress # @UnresolvedImport
        p = Proxy(Proxy.Type.HTTP,InetSocketAddress(proxyHost,proxyPort))
    else: p = None

    #import java.net.URL as URL # @UnresolvedImport
    u = URL("https://www.google.com/")
    conn = u.openConnection(p) if p else u.openConnection()
    return 'server response: '+repr(conn.getResponseCode())
예제 #15
0
 def __init__(self, port, request_handler):
     """
     Initialize and start an HTTP server.
     
     Uses a native HTTP server implementation, in this case
     the com.sun.net.httpserver.HttpServer.
     
     @param port:            The port on which the server should listen.
     @type port:             int
     
     @param request_handler: The request handler class from our generic code.
     @type request_handler:  Any class with a 'handle()' method that can take a
                             RestxHttpRequest. In our case, this is normally the
                             RequestDispatcher class.
     
     """
     self.request_handler = request_handler
     self.__native_server = HttpServer.create(InetSocketAddress(port), 5)
     self.__native_server.createContext(
         settings.DOCUMENT_ROOT if settings.DOCUMENT_ROOT != "" else "/",
         __HttpHandler(request_handler))
     self.__native_server.setExecutor(Executors.newCachedThreadPool())
     self.__native_server.start()
     log("Listening for HTTP requests on port %d..." % port)
예제 #16
0
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()
예제 #17
0
 def initWebServer(self):
     self.hs = HttpServer.create(InetSocketAddress("127.0.0.1", 8002), 0)
     self.hs.createContext("/", FileHttpHandler())
     self.hs.createContext("/ajax", CommandHttpHandler())
     self.hs.setExecutor(None)
     self.hs.start()
예제 #18
0
def download_file():
    '''
    FUNC FOR DOWNLOADING DATA FROM MVD.RF WEBSITE
    '''
    global buffer_size, downloaded
    ins_log('Create proxy settings', 'using ' + str(ODIAgent))
    if ODIAgent == 'Internal':
        proxy_address = TEST_FILE_DOWNLOADS.ProdProxyHost
        proxy_port = TEST_FILE_DOWNLOADS.ProdProxyPort
        proxy_user = '******'
        proxy_passe = "70320DB646F3C6740262E9224E8A88C7"
        proxy_domain = "BANKEXP"
        proxy_pass = cryptor.decrypt(proxy_passe)
    else:
        proxy_address = FILE_DOWNLOADS.ProdProxyHost
        proxy_port = FILE_DOWNLOADS.ProdProxyPort
        proxy_user = "******"
        proxy_passe = "32A47DEE17B2F967BA6094BB609ABF8E"
        proxy_domain = "BANKEXP"
        proxy_pass = cryptor.decrypt(PROXY_PASSE)
    ins_log("Downloading...", url)
    builder = OkHttpClient.Builder()
    #builder.followRedirects(False).followSslRedirects(False);
    builder.connectTimeout(5, TimeUnit.MINUTES).writeTimeout(
        5, TimeUnit.MINUTES).readTimeout(5, TimeUnit.MINUTES)
    httpClient = builder.proxy(
        Proxy(Proxy.Type.HTTP, InetSocketAddress(
            proxy_address,
            proxy_port))).proxyAuthenticator(proxy_authenticator).build()
    call = httpClient.newCall(Request.Builder().url(url).get().build())
    #//Call to server
    response = call.execute()
    #//
    ins_log('Call to web server', str(response))
    #print(response.code())
    if (response.code() == 200):  #//Check Response code
        inputStream = None
        outputStream = None
        target = response.body().contentLength()
        try:
            inputStream = response.body().byteStream()
            #//Get stream of bytes
            buffer = zeros(buffer_size, 'b')
            #//Creating buffer bytes(1024*4)  #bytearray(4096)
            outputStream = FileOutputStream(File(archived_file))
            print_download_process(0, target)
            while (downloaded < target):
                readed = inputStream.read(buffer)
                if (readed == -1):
                    break
                else:
                    outputStream.write(buffer, 0, readed)
                    #//write buff
                    downloaded += readed
                    print_download_process(downloaded, target)
        except Exception:
            ins_log("Downloading Error", str(Exception))
        finally:
            if (inputStream != None):
                inputStream.close()
            elif (outputStream != None):
                outputStream.close()

        ins_log("File downloaded!",
                str(url) + ' filename:' + str(archived_file))