Python Script to dial a VPN connection, automate VPN routing table updates.
Mark Hammond
MarkH at ActiveState.com
Fri Mar 23 18:15:44 EST 2001
Warren Postma wrote:
> Sorry for the nearly-off-topic nature of this post, but ....
>
> I work from home now, and there's something in Windows 2000 that's
> annoyingly manual:
>
> I have a permanent internet connection via @home cable modem, and I "dial"
> through that to create a VPN connection to the office. The problems are
> two:
>
> (1) Windows won't accept or save my userid, password and the domain name, so
> I have to enter it manually.
>
> (2) After connecting, I have two default gateways in my routing tables
> (ROUTE PRINT) and I need to update it so only the traffic that is destined
> to the office goes through that interface. The IP addresses I get given are
> different each time, making a batch file insufficient, so voila, a perfect
> use for python.
I have very similar problems. Here is a script I wrote for the purpose.
It doesnt handle authentication sa Windows does remember the password
etc for me.
When run with a command-line option being the VPN connection name, it
establishes a connection to the named site.
Once connected, or if an argument is not given it attempts to find the
IP of the VPN connection and manually add a route for the VPN.
Thus, I generally use it with no options after manually connecting - not
for any good reason actually, just that is the way I do it :)
import os
import sys
import win32ras
def Connect(rasEntryName, numRetries = 5):
# See if already connected
for info in win32ras.EnumConnections():
if info[1] == rasEntryName:
print "Already connected to '%s'" % (rasEntryName,)
return 1
dial, 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)
retryCount = numRetries
bValid = 0
print "Connecting to:", rasEntryName
while retryCount > 0:
rasHandle, errCode = win32ras.Dial(None, None, dial, None)
if win32ras.IsHandleValid(rasHandle):
bValid = 1
break
print "Retrying..."
win32api.Sleep(5000)
retryCount = retryCount - 1
return bValid
def FixRoute():
data = os.popen("ipconfig", "r").readlines()
have_ppp = 0
ip_str = None
for line in data:
if line.startswith("PPP"):
have_ppp = 1
if have_ppp and line.strip().startswith("IP Address"):
ip_str = line.split(":")[1].strip()
if ip_str is None:
print "ERROR: could not find the PPP ip address"
else:
print "Your PPP IP address is", ip_str
cmd = "route add 192.168.2.0 mask 255.255.255.0 %s" % (ip_str,)
print cmd
os.system(cmd)
print "Route updated."
if len(sys.argv) == 2:
if not Connect(sys.argv[1]):
print "Could not connect to '%s'" % (sys.argv[1],)
sys.exit(1)
else:
print "No connection name specified - just adding route..."
FixRoute()
More information about the Python-list
mailing list