Пример #1
0
def Connect(rasEntryName, numRetries=5):
    """Make a connection to the specified RAS entry.
	
	Returns a tuple of (bool, handle) on success.
	- bool is 1 if a new connection was established, or 0 is a connection already existed.
	- handle is a RAS HANDLE that can be passed to Disconnect() to end the connection.
	
	Raises a ConnectionError if the connection could not be established.
	"""
    assert numRetries > 0
    for info in win32ras.EnumConnections():
        if info[1].lower() == rasEntryName.lower():
            print "Already connected to", rasEntryName
            return 0, info[0]

    dial_params, have_pw = win32ras.GetEntryDialParams(None, rasEntryName)
    if not have_pw:
        print "Error: The password is not saved for this connection"
        print "Please connect manually selecting the 'save password' option and try again"
        sys.exit(1)

    print "Connecting to", rasEntryName, "..."
    retryCount = numRetries
    while retryCount > 0:
        rasHandle, errCode = win32ras.Dial(None, None, dial_params, None)
        if win32ras.IsHandleValid(rasHandle):
            bValid = 1
            break
        print "Retrying..."
        win32api.Sleep(5000)
        retryCount = retryCount - 1

    if errCode:
        raise ConnectionError(errCode, win32ras.GetErrorString(errCode))
    return 1, rasHandle
Пример #2
0
def Connect(entryName, bUseCallback):
    if bUseCallback:
        theCallback = Callback
        win32event.ResetEvent(callbackEvent)
    else:
        theCallback = None
    #       in order to *use* the username/password of a particular dun entry, one must
    #       explicitly get those params under win95....
    try:
        dp, b = win32ras.GetEntryDialParams( None, entryName )
    except:
        print("Couldn't find DUN entry: %s" % entryName)
    else:
        hras, rc = win32ras.Dial(None, None, (entryName, "", "", dp[ 3 ], dp[ 4 ], ""),theCallback)
    #       hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
    #       print hras, rc
        if not bUseCallback and rc != 0:
            print("Could not dial the RAS connection:", win32ras.GetErrorString(rc))
            hras = HangUp( hras )
        #       don't wait here if there's no need to....
        elif bUseCallback and win32event.WaitForSingleObject(callbackEvent, 60000)!=win32event.WAIT_OBJECT_0:
            print("Gave up waiting for the process to complete!")
            #       sdk docs state one must explcitly hangup, even if there's an error....
            try:
                cs = win32ras.GetConnectStatus( hras )
            except:
                #       on error, attempt a hang up anyway....
                hras = HangUp( hras )
            else:
                if int( cs[ 0 ] ) == win32ras.RASCS_Disconnected:
                    hras = HangUp( hras )
    return hras, rc
Пример #3
0
 def autoDail(self, account, password, callback):
     retrytimes = 0  # 重试次数
     max_retry = 3  # 最大重试次数
     dial_name = 'Netkeeper'
     while settings.RUNNING:
         conns = self.get_conn()
         if not conns:
             real_account = self.getRealAccount(account)
             handle, result = self.connect(real_account, password, dial_name)
             if result == 0:
                 curtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
                 self.saveData(True, curtime)
                 threading.Thread(target=callback, args=(time.time(), 13213132313))
                 logger.info("E信登录成功!    " + repr(account))
             elif result == 691:
                 self.disconnect()
                 if retrytimes == max_retry:
                     logger.info("重试次数过多!取消拨号!")
                     return
                 reason = win32ras.GetErrorString(result).decode('GBK').encode('utf-8')
                 logger.info("登录失败!  " + reason + "(Code:" + result + ")")
                 logger.info("3秒后重试")
                 time.sleep(3)
                 retrytimes += 1
             elif result == 623:
                 dial_name = dial_name[4:] if 'Simp' in dial_name else 'SimpNetkeeper'
         else:
             time.sleep(30)
Пример #4
0
def Callback(hras, msg, state, error, exterror):
    #       print "Callback called with ", hras, msg, state, error, exterror
    stateName = stateMap.get(state, "Unknown state?")
    print("Status is %s (%04lx), error code is %d" % (stateName, state, error))
    finished = state in [win32ras.RASCS_Connected]
    if finished:
        win32event.SetEvent(callbackEvent)
    if error != 0 or int(state) == win32ras.RASCS_Disconnected:
        #       we know for sure this is a good place to hangup....
        print("Detected call failure: %s" % win32ras.GetErrorString(error))
        HangUp(hras)
        win32event.SetEvent(callbackEvent)
Пример #5
0
def re_connect(rasEntryName, user, pwd):
    global bohao_count
    bohao_count += 1
    path = os.getenv("WINDIR")
    if not path:
        raise ConnectionError
    path = path + "\\system32"
    if not os.path.exists(path + "\\rasdial.exe"):
        raise ConnectionError
    cmd = '%s\\cmd /c  %s\\rasdial "%s" /disconnect  &&  %s\\rasdial "%s" %s %s' % (
        path, path, rasEntryName, path, rasEntryName, user, pwd)
    # cmd = 'cmd /c  rasdial "%s" /disconnect  &&  rasdial "%s" %s %s' % (rasEntryName, rasEntryName, user, pwd)
    proc = subprocess.Popen(cmd, shell=True)
    try:
        errCode = wait_connect_proc_exit(proc)
    except RetryOvertimesException:
        raise ConnectionError()
    proc.terminate()
    if errCode:
        errinfo = win32ras.GetErrorString(errCode)
        if errCode in [651, 678, 691, 628]:
            time.sleep(30)
            print("reconnect error %s[%s], sleep 30 sec and retry" %
                  (errinfo, errCode))
            raise RetryException()
        elif errCode in [718, 720]:
            time.sleep(1)
            print("reconnect error1 %s[%s], sleep 1 sec and retry" %
                  (errinfo, errCode))
            raise RetryException()
        elif errCode in [692]:
            time.sleep(5)
            print("reconnect error2 %s[%s], sleep 5 sec and retry" %
                  (errinfo, errCode))
            raise RetryException()
        elif errCode in [623]:
            print("reconnect error3 %s[%s], stop" % (errinfo, errCode))
            raise Exception()
        else:
            print("reconnect not handle error %s[%s], 30 sec wait" %
                  (errinfo, errCode))
            time.sleep(30)
            raise RetryException()
    print("re_connect ok %s" % bohao_count)

    return True