rastest.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # rastest.py - test/demonstrate the win32ras module.
  2. # Much of the code here contributed by Jethro Wright.
  3. import sys
  4. import os
  5. import win32ras
  6. # Build a little dictionary of RAS states to decent strings.
  7. # eg win32ras.RASCS_OpenPort -> "OpenPort"
  8. stateMap = {}
  9. for name, val in list(win32ras.__dict__.items()):
  10. if name[:6]=="RASCS_":
  11. stateMap[val] = name[6:]
  12. # Use a lock so the callback can tell the main thread when it is finished.
  13. import win32event
  14. callbackEvent = win32event.CreateEvent(None, 0, 0, None)
  15. def Callback( hras, msg, state, error, exterror):
  16. # print "Callback called with ", hras, msg, state, error, exterror
  17. stateName = stateMap.get(state, "Unknown state?")
  18. print("Status is %s (%04lx), error code is %d" % (stateName, state, error))
  19. finished = state in [win32ras.RASCS_Connected]
  20. if finished:
  21. win32event.SetEvent(callbackEvent)
  22. if error != 0 or int( state ) == win32ras.RASCS_Disconnected:
  23. # we know for sure this is a good place to hangup....
  24. print("Detected call failure: %s" % win32ras.GetErrorString( error ))
  25. HangUp( hras )
  26. win32event.SetEvent(callbackEvent)
  27. def ShowConnections():
  28. print("All phone-book entries:")
  29. for (name,) in win32ras.EnumEntries():
  30. print(" ", name)
  31. print("Current Connections:")
  32. for con in win32ras.EnumConnections():
  33. print(" ", con)
  34. def EditEntry(entryName):
  35. try:
  36. win32ras.EditPhonebookEntry(0,None,entryName)
  37. except win32ras.error as xxx_todo_changeme:
  38. (rc, function, msg) = xxx_todo_changeme.args
  39. print("Can not edit/find the RAS entry -", msg)
  40. def HangUp( hras ):
  41. # trap potential, irrelevant errors from win32ras....
  42. try:
  43. win32ras.HangUp( hras )
  44. except:
  45. print("Tried to hang up gracefully on error, but didn't work....")
  46. return None
  47. def Connect(entryName, bUseCallback):
  48. if bUseCallback:
  49. theCallback = Callback
  50. win32event.ResetEvent(callbackEvent)
  51. else:
  52. theCallback = None
  53. # in order to *use* the username/password of a particular dun entry, one must
  54. # explicitly get those params under win95....
  55. try:
  56. dp, b = win32ras.GetEntryDialParams( None, entryName )
  57. except:
  58. print("Couldn't find DUN entry: %s" % entryName)
  59. else:
  60. hras, rc = win32ras.Dial(None, None, (entryName, "", "", dp[ 3 ], dp[ 4 ], ""),theCallback)
  61. # hras, rc = win32ras.Dial(None, None, (entryName, ),theCallback)
  62. # print hras, rc
  63. if not bUseCallback and rc != 0:
  64. print("Could not dial the RAS connection:", win32ras.GetErrorString(rc))
  65. hras = HangUp( hras )
  66. # don't wait here if there's no need to....
  67. elif bUseCallback and win32event.WaitForSingleObject(callbackEvent, 60000)!=win32event.WAIT_OBJECT_0:
  68. print("Gave up waiting for the process to complete!")
  69. # sdk docs state one must explcitly hangup, even if there's an error....
  70. try:
  71. cs = win32ras.GetConnectStatus( hras )
  72. except:
  73. # on error, attempt a hang up anyway....
  74. hras = HangUp( hras )
  75. else:
  76. if int( cs[ 0 ] ) == win32ras.RASCS_Disconnected:
  77. hras = HangUp( hras )
  78. return hras, rc
  79. def Disconnect( rasEntry ):
  80. # Need to find the entry
  81. name = rasEntry.lower()
  82. for hcon, entryName, devName, devType in win32ras.EnumConnections():
  83. if entryName.lower() == name:
  84. win32ras.HangUp( hcon )
  85. print("Disconnected from", rasEntry)
  86. break
  87. else:
  88. print("Could not find an open connection to", entryName)
  89. usage = """
  90. Usage: %s [-s] [-l] [-c connection] [-d connection]
  91. -l : List phone-book entries and current connections.
  92. -s : Show status while connecting/disconnecting (uses callbacks)
  93. -c : Connect to the specified phonebook name.
  94. -d : Disconnect from the specified phonebook name.
  95. -e : Edit the specified phonebook entry.
  96. """
  97. def main():
  98. import getopt
  99. try:
  100. opts, args = getopt.getopt(sys.argv[1:], "slc:d:e:")
  101. except getopt.error as why:
  102. print(why)
  103. print(usage % (os.path.basename(sys.argv[0],)))
  104. return
  105. bCallback = 0
  106. if args or not opts:
  107. print(usage % (os.path.basename(sys.argv[0],)))
  108. return
  109. for opt, val in opts:
  110. if opt=="-s":
  111. bCallback = 1
  112. if opt=="-l":
  113. ShowConnections()
  114. if opt=="-c":
  115. hras, rc = Connect(val, bCallback)
  116. if hras != None:
  117. print("hras: 0x%8lx, rc: 0x%04x" % ( hras, rc ))
  118. if opt=="-d":
  119. Disconnect(val)
  120. if opt=="-e":
  121. EditEntry(val)
  122. if __name__=='__main__':
  123. main()