rasutil.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # A demo of using the RAS API from Python
  2. import sys
  3. import win32ras
  4. # The error raised if we can not
  5. class ConnectionError(Exception):
  6. pass
  7. def Connect(rasEntryName, numRetries = 5):
  8. """Make a connection to the specified RAS entry.
  9. Returns a tuple of (bool, handle) on success.
  10. - bool is 1 if a new connection was established, or 0 is a connection already existed.
  11. - handle is a RAS HANDLE that can be passed to Disconnect() to end the connection.
  12. Raises a ConnectionError if the connection could not be established.
  13. """
  14. assert numRetries > 0
  15. for info in win32ras.EnumConnections():
  16. if info[1].lower()==rasEntryName.lower():
  17. print "Already connected to", rasEntryName
  18. return 0, info[0]
  19. dial_params, have_pw = win32ras.GetEntryDialParams(None, rasEntryName)
  20. if not have_pw:
  21. print "Error: The password is not saved for this connection"
  22. print "Please connect manually selecting the 'save password' option and try again"
  23. sys.exit(1)
  24. print "Connecting to", rasEntryName, "..."
  25. retryCount = numRetries
  26. while retryCount > 0:
  27. rasHandle, errCode = win32ras.Dial(None, None, dial_params, None)
  28. if win32ras.IsHandleValid(rasHandle):
  29. bValid = 1
  30. break
  31. print "Retrying..."
  32. win32api.Sleep(5000)
  33. retryCount = retryCount - 1
  34. if errCode:
  35. raise ConnectionError(errCode, win32ras.GetErrorString(errCode))
  36. return 1, rasHandle
  37. def Disconnect(handle):
  38. if type(handle)==type(''): # have they passed a connection name?
  39. for info in win32ras.EnumConnections():
  40. if info[1].lower()==handle.lower():
  41. handle = info[0]
  42. break
  43. else:
  44. raise ConnectionError(0, "Not connected to entry '%s'" % handle)
  45. win32ras.HangUp(handle)
  46. usage="""rasutil.py - Utilities for using RAS
  47. Usage:
  48. rasutil [-r retryCount] [-c rasname] [-d rasname]
  49. -r retryCount - Number of times to retry the RAS connection
  50. -c rasname - Connect to the phonebook entry specified by rasname
  51. -d rasname - Disconnect from the phonebook entry specified by rasname
  52. """
  53. def Usage(why):
  54. print why
  55. print usage
  56. sys.exit(1)
  57. if __name__=='__main__':
  58. import getopt
  59. try:
  60. opts, args = getopt.getopt(sys.argv[1:], "r:c:d:")
  61. except getopt.error, why:
  62. Usage(why)
  63. retries = 5
  64. if len(args) != 0:
  65. Usage("Invalid argument")
  66. for opt, val in opts:
  67. if opt=='-c':
  68. Connect(val, retries)
  69. if opt=='-d':
  70. Disconnect(val)
  71. if opt=='-r':
  72. retries = int(val)