18

connect.bat

rasdial myvpn

disconnect.bat

rasdial myvpn /DISCONNECT

....I assigned those two files a keyboard shortcut to run them and they work perfectly.


QUESTION: is it possible to make a single .bat that does the following:

if(connected)
   disconnect
else
   connect
derfect
  • 622
  • 2
  • 6
  • 14

1 Answers1

40
  • Based on ping in case the VPN server IP is always the same:

    ping -n 1 1.2.3.4 && rasdial myvpn /disconnect || rasdial myvpn
    

    Replace 1.2.3.4 with your VPN server ip (use ipconfig /all when connected) and put this in your batch file or directly in the shortcut properties prepending with cmd /c in the latter case.

  • Based on connection name:

    ipconfig|find/i "myvpn" && rasdial myvpn /disconnect || rasdial myvpn
    

    Replace myvpn with your VPN connection name

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • you're a genius, second method works perfectly. Thank you wOx – derfect Aug 15 '15 at 17:41
  • I tried this method but an alert is shown and told me that the username and password is not correct. However, I've already filled in the username and password while setting up the VPN in the Network console, so I think I should not include them in the BAT? (typing both information in a BAT seems not secure) – Kit Ng Jan 15 '16 at 21:58
  • 1
    @KitNg, as per [Establish a VPN connection in cmd](http://stackoverflow.com/q/14614465) use `*` for password: `rasdial myvpn myusername *` – wOxxOm Jan 16 '16 at 00:57
  • With the use of * , it requests me to input the password everytime I connect. Is there any way to use the saved credential in my VPN property? I'm using PPTP. Thanks. – Kit Ng Jan 16 '16 at 18:17
  • 1
    @KitNg, [nircmd](http://www.nirsoft.net/utils/nircmd.html) can do it: `nircmdc rasdial myvpn` – wOxxOm Jan 16 '16 at 19:59
  • @wOxxOm my VPN service can only be connected through single-sign on application with has password and security question. Is there a way i can modify above script to use for my need ? – Ragova May 02 '20 at 07:11