How-to schedule a VPN connection on Synology DSM 6

In this step-by-step guide I will describe how-to schedule a VPN connection on your Synology. I asked Synology if it was possible to do this but they said it couldn’t be done. You can manually start and stop a VPN connection so it didn’t make sense this couldn’t be done automatically. It’s actually pretty simple and i want to share this with you. I even included logging so you can check if the connection was disconnected.

This is last tested with DSM 6.2.1-23824 Update 1

Preparations

  • SSH enabled on your Synology
  • VPN connection created on your Synology
  • Create a share on your Synology we are going to use

How-to schedule a VPN connection on your Synology

vpn2

First you should have created a shared folder. In my environment i used the folder /volume1/scripts. 

Note: When you want to schedule a VPN connection you must stop the package VPN Server on Synology (if you have it). You cannot start a VPN connection when your Synology is a VPN server itself.

vpn1

You also need to have a VPN connection configured (see example above). The creation looks slightly different than the example above.

Open Putty and connect via SSH to your Synology.
Navigate to the VPN client folder:

cd /usr/syno/etc/synovpnclient/

Note: When you first start the VPN connection there will be 2 files created in this folder; vpnc_last_connect and vpnc_connecting. The vpnc_connecting file will disappear in about 2 seconds when you start a VPN connection.

Start your VPN connection and open the created file: vpnc_last_connect

sudo vi ./vpnc_last_connect

Find your conf_id, conf_name and proto. Remember these or write them down. Exit VI with: :q!

Create a new vpnc_connecting file in your scripts folder and add 3 lines. To insert text hit the letter i. When you wrote the 3 lines hit ESC and enter :wq!

sudo vi /volume1/scripts/vpnc_connecting

vpn3

Now we are going to create a task to automatically start and schedule the VPN connection. Go to Control Panel > Task Scheduler. Click Create > User-defined script.

Enter the following information:
Task: the name for your task (e.g. Start VPN)
User: root
User-defined script (only 2 lines):

cp /volume1/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/
/usr/syno/bin/synovpnc connect −−id=o123456789

Note:
When you got trouble making a connection you could try to add a retry in the command as mentioned by Tony in the comments. You can do it like this:

cp /volume1/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/
/usr/syno/bin/synovpnc connect −−id=o123456789 −retry=3 −interval=30

vpn4

Under Schedule enter the time you want to schedule and start this VPN connection.

vpn5

In my example i want to start the VPN connection daily at 3:05 AM. Click OK.

This script copies a file to a directory and then gives a command to start the VPN connection. When you run this task it will start your VPN connection.

Now we want to automatically schedule to stop the VPN connection and log some of the information. Click Create > User-defined script.

Enter the following information:
Task: the name for your task (e.g. Stop VPN)
User: root
User-defined script:

DAY0=`date -I`
touch /volume1/scripts/vpn-$DAY0.log
/usr/syno/bin/synovpnc get_conn >>/volume1/scripts/vpn-$DAY0.log
/usr/syno/bin/synovpnc kill_client
/usr/syno/bin/synovpnc kill_client

Under Schedule enter the time you want to stop the VPN connection.

The first 3 lines will create a log-file per day with the connection information. The last two lines of the user-defined script will stop the VPN connection. This line MUST added twice when you have selected: “Reconnect when the VPN connection is lost”. Otherwise it will reconnect the VPN connection.

vpn6

Example of the log-file:

Current connection info:
Config Name : VPN
Client IP : 10.10.10.10
Client Mask : 255.255.255.255
Uptime : 860 seconds
RX : 170271666
TX : 8085506

When the VPN connection was disconnected and reconnected you will see multiple connections in the same log-file.

That’t it, you have a scheduled VPN connection on your Synology.

Advertisements

46 thoughts on “How-to schedule a VPN connection on Synology DSM 6

  1. Beste Mick,

    Ik was op zoek naar een manier om een VPN verbinding met een task schedular op te zetten.
    In mijn zoektocht kwam ik op jou uitvoerige uitleg hierover en ben ermee aan de slag gegaan.
    Ondanks de heldere uitleg is het mij nog niet gelukt om een verbinding via taakbeheer te bewerkstelligen.
    Er is op dit moment een werkende VPN verbinding die ik 1keer in de week handmatig opzet naar de Synology van mijn vader om daar een backup naartoe te schrijven. Ik zou het fijn vinden als deze verbinding automatisch gemaakt kan worden en na de backup ook weer verbroken wordt. Ik kan wel een constante verbinding opzetten, maar dan gaan de harde schijven niet meer in slaapstand
    Zou ik jou mogen vragen om te kijken waar het bij mij misgaat, aangezien ik niet handig ben met de commando’s binnen terminal?

    ik maak gebruik van DSM 6.0.2-8451 Update 2 en heb het bestand “vpnc_connecting file” in de gedeelde map scripts geplaatst.

    In taakbeheer heb ik met user root de regels overgenomen uit de beschrijving op de website.

    cp /volume1/scripts/vpnc_connecting
    /usr/syno/etc/synovpnclient/
    /usr/syno/bin/synovpnc connect –id=l1476990807

    Zou het kunnen dat de directory paden anders zijn in DSM 6?

    De volgende foutmelding krijg ik:

    Task: VPN connection
    Start time: Sun, 30 Oct 2016 20:06:22 GMT
    Stop time: Sun, 30 Oct 2016 20:06:22 GMT
    Current status: 255
    Standard output/error:
    cp: missing destination file operand after ‘/volume1/scripts/vpnc_connecting’
    Try ‘cp –help’ for more information.
    sh: line 1: /usr/syno/etc/synovpnclient/: Is a directory
    get arguemnt id: l1476990807

    Hopelijk wil je mij helpen.
    Alvast hartelijk dank,

    Jos Leinders

    Like

    • Beste Jos,

      Ik heb dit nog niet getest onder DSM 6.x. Als ik tijd heb zal ik dit vanavond even testen. Zal gelijk kijken of de paden zijn veranderd.

      Als ik het zo bekijk lijkt het er op dat jouw taak uit 3 regels bestaat in plaats van 2 regels.

      Zit er achter “cp /volume1/scripts/vpnc_connecting” een spatie? gevolgd door “/usr/syno/etc/synovpnclient/”? Het lijkt er namelijk op dat “/usr/syno/etc/synovpnclient/” op een nieuwe regel staat. Als dat het geval is dan weet hij niet waar hij het vpnc_connecting -bestand naar toe moet kopiëren.

      Zou je dit eens willen controleren?

      Like

  2. Hallo Mick,

    Hartelijk dank voor je snelle reactie.
    Het is gelukt met je uitleg. Helemaal goed!
    Ik had het niet zo snel gezien met die 3e regel.
    Deze week ga ik nog aan de slag om de verbinding te verbreken.
    Weet jij of het mogelijk om de verbinding te laten verbreken als de backup uitgevoerd is?
    Nogmaals hartelijk dank. Ik ben er erg blij mee.

    Groeten,
    Jos

    Like

    • Hallo Jos,

      Excuses voor de late reactie. Dit zou wel mogelijk moeten zijn. Welke back-up oplossing gebruik je? Weet je toevallig ook of je via SSH de status van de back-up kan opvragen?

      Weet je ook hoelang de back-up taak duurt? Een work-around zou zijn door de stop-taak iets later uit te voeren nadat de back-up taak klaar is. Echter is dit wel gevaarlijk want als de verbinding trager is waardoor de back-up 2x zo lang duurt dan verbreekt hij de verbinding als hij nog bezig is.

      Like

      • Hallo Mick,
        Ik gebruik Hyper Backup. Beetje afhankelijk van de wijzigingen die ik gemaakt heb in een week zo’n 5 tot 10 minuten. Een work-around oplossing heb ik op dit moment. De verbinding wordt na een half uur in een tweede script via task schedular verbroken. Praktischer zou het zijn als de verbinding direct na de backup wordt verbroken. Ook in het geval van een backup langer dan een half uur.
        Ik weet niet of en hoe ik de SSH status kan opvragen van de huidige backup-taak.
        Groet,
        Jos

        Like

  3. Hey great work. I’m running DSM 6.0.2-8451 Update 9

    Everything works until Schedualing the script. When I ssh to diskstaion and execute

    root@Nas:~# cp /volume1/Daten_GF/IT/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/ /usr/syno/bin/synovpnc connect –id=oXXXXXXXXXX

    i get

    cp: target ‘–id=oXXXXXXXXXX’ is not a directory

    any suggestions?

    Like

    • Hi Josh,

      This needs to be on 1 line:
      cp /volume1/Daten_GF/IT/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/

      This needs to be on a new line:
      /usr/syno/bin/synovpnc connect –id=oXXXXXXXXXX

      So it needs to be 2 lines. The first one is to the copy the vpnc_connecting file to the correct location. The second line is to start the VPN.

      Hope this helps.

      Like

      • Wow. Thanks for the quick reply!!! Unforunately i’m no linux pro. First line fits. Secondline i get a syntax error.

        root@Nas:~#/usr/syno/bin/synovpnc connect –id=oXXXXXXXXXX
        Usage:
        vpnc_tool COMMAND [ARGS]

        available COMMAND:
        get (get config info)
        get_conn (get current connection info)
        kill_client (kill client)
        clear (clear temp files of connection)
        connect (connect)
        reconnect (redial)
        update_conf (sync new keys to old config files)
        available ARGS:
        –name
        –id
        –protocol
        –retry (retry n times if connection failed)
        –interval (time interval between each retry)
        –keepfile (keep reconnection file)
        example:
        get –name=
        get_conn
        kill_client
        connect –id=
        reconnect –protocol= –name= [–retry=5] [–interval=30] [–keepfile]
        update_conf
        clear

        root@Nas:~#

        Like

      • Hi Josh,

        I found a solution. There were 2 problems with the code. The minus ( – ) in your line is different (longer) then mine. When copying code from this website, try using notepad if you want to paste and edit the code. Word can screw things up. The second problem is there are now 2 minus characters needed in the code instead of one.

        So for you this should work:

        cp /volume1/Daten_GF/IT/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/
        /usr/syno/bin/synovpnc connect --id=oXXXXXXXXXX

        Like

  4. Hi Mick,

    thank you for your great post! My script is working and reconnecting the VPN!
    However I had an issue first, I ran into the same problem as Josh. In Chrome for Windows the two “–” show up as a “–”. So nothing with Word but your post already displays it as a “–”. Can you fix this?

    Thanks again for the great post,

    Reto

    Like

    • Hi Reto,

      Thanks for your reply.

      You are totally right. When i try to edit this post i see 2 minus characters in the editor screen. On this page Chrome replaces the 2 minus characters for 1 longer minus character.

      I thought i could not change this. I tried to add a ASCII HTML code for the minus character in the editor screen. It looks like this will work.

      Mick.

      Like

  5. Are Synology change something? I could find “vpnc_connecting” file.
    there was only another file called ***Last Connect ..with many info in it.
    It looks like syno improved the reconnection process.

    Like

  6. Beste Mick,

    Het werkt nog steeds prima! Ik heb het net volgens jouw handleiding ingesteld en dat ging probleemloos. Het enige wat niet overeenkwam is de stelling dat het bestandje wat aangemaakt wordt wanneer de vpn start. In mijn geval heet het anders (vpnc_last_connect en niet vpnc_connecting) en blijft deze ook gewoon bestaan. Ik kwam er achter omdat het via Putty niet te vinden was en ik toen via Winscp ben gaan kijken in de betreffende folder. Daar vond ik dit bestandje en opende ik het in kladblok om zo de id te vinden. (wel als root in Winscp zijn). Daarna ging alles volgens jouw instructie. Bedankt voor de genomen moeite voor deze post!

    groet Sander

    Liked by 1 person

    • Hallo Sander,

      Excuses voor mijn late reactie en bedankt voor je bevindingen. Ik zal mijn post updaten maar heb nog een paar vragen.

      – Klopt het dat vpnc_last_connect dus blijft staan en dat je hierin je ID kan vinden?
      – Staat vpnc_last_connect in dezelfde folder als vpnc_connecting zou moeten staan?
      – Werkt het aanroepen van ” /usr/syno/bin/synovpnc connect –id=o ” als je alleen de file vpnc_last_connect hebt?

      Like

  7. Amazing!
    Was looking for something like this for ages, just tried it out, and it works perfectly! Super satisfying!
    Just wanted to send a massive thanks 🙂

    Liked by 1 person

  8. I know this is an old thread but I figure post an update. I have a DS415+ Running DSM 6.2-23739 Update 2 and this is what worked for me.

    Script to Start the VPN

    cp /volume1/scripts/vpnc_last_connect /usr/syno/etc/synovpnclient/
    /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh start

    Script to stop the VPN

    DAY0=`date -I`
    touch /volume1/homes/Marvin/Scripts/vpn-$DAY0.log
    /usr/syno/bin/synovpnc get_conn >>/volume1/homes/Marvin/Scripts/vpn-$DAY0.log
    /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh disconnect

    Liked by 1 person

  9. Hi Mick,

    Thank you for this post, I am desperately trying to get this working but for some reason I am not succeeding. I am running DSM 6.2.1-23824 Update 1 and have followed Marvin’s post for the Start and stop scripts.

    The stop script works just fine but the start script does not start the VPN running. I have tried different combinations of your script and Marvin’s without success.

    The below is the log sent to my email when I run the Start script:

    Task: Start VPN
    Start time: Wed, 14 Nov 2018 12:54:38 GMT
    Stop time: Wed, 14 Nov 2018 12:54:39 GMT
    Current status: 1 (Interrupted)
    Standard output/error:
    Usages: /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh [start|stop|shutdown|disconnect]
    start: Job is already running: synoscgi

    It keeps saying that the job is already running but the VPN service does not start.

    Any idea what I am doing wrong?

    Please help,

    Many Thanks,

    Dave

    Like

      • Hi Mick,

        I do have an OpenVPN setup, I have tried stopping and restarting a number of times already. Manual works fine, through the task scheduler the stop script works after I have manually started the VPN running, however the start script does not work – the log sent to my email is as posted earlier every time.

        Many Thanks for taking the time out to help me – there is very little information available online for this topic and your blog is the most comprehensive guide I have found.

        Regards,

        Dave

        Like

      • Hi Dave,

        I can remember i had the same problem when i activated OpenVPN. So you did the following? Open VPN Server > tab OpenVPN on the left > removed the check on Enable OpenVPN > apply ?

        I have to test this at home because i use OpenVPN also and cannot uncheck it because i will lose my VPN connection 🙂

        Regards,
        Mick

        Like

  10. Hi Mick,

    I must apologise, I misunderstood your question in relation to OpenVPN. I do not use the Synology VPN Server package. I have an external VPN setup using OpenVPN through NordVPN. I was slightly confused by your response, but after checking the Synology VPN Server package out it made sense what you had written, but it does not apply to my situation though.

    I just started again following your guide from scratch and reset everything up as detailed and I have managed to get the script working. I know where I went wrong too. I originally inserted the script as follows:

    cp /volume1/scripts/vpnc_last_connect
    /usr/syno/etc/synovpnclient/
    /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh
    start

    instead of exactly as Martin has it written like this:

    cp /volume1/scripts/vpnc_last_connect /usr/syno/etc/synovpnclient/
    /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh start

    Problem solved! I misunderstood from the photo above thinking it was supposed to be on 4 separate command lines. My Linux skills are terrible. Thank you for this post and apologies if I wasted your time.

    Best Regards,

    Dave

    Like

    • Hello Dave,

      I saw this message too late. Glad to hear it works for you. Just tested it out myself on DSM 6.2.1.23824 Update 1 and can confirm it still works. What i did was;

      1: Stop the VPN Server package on Synology (only if you use it).
      2: I created via Control Panel > Network > Network Interface a new VPN profile i wanted to use.
      3: Start the newly created VPN profile one time to test if it will connect and works. When you start it, it will create 2 files in /usr/syno/etc/synovpnclient

      It wil create vpnc_last_connect (this file will still be there) and vpnc_connecting (this file will only be available for 2 seconds when you start the VPN profile. The vpnc_last_connect file contains a lot more information but you actually only need the vpnc_connecting file. I looked inside the vpnc_connecting file and it contained 3 lines with my ID, my name i gave to the VPN profile and the protocol:

      conf_id=o1234567890
      conf_name=TESTVPN
      proto=openvpn

      The vpnc_connecting file must be in the /usr/syno/etc/synovpnclient folder before you start the VPN with the command: /usr/syno/bin/synovpnc connect –id=o12345667890

      I will rewrite some of the original text with this update. Again, i’m glad that it works and i’m pleased to hear i helped a lot of people with this.

      Thank you for your input.

      Best regards,
      Mick

      Like

  11. Hello

    I got my Task to connect to the VPN, but it stays at “connecting”.

    Anyone got any idea how to fix this?

    The script i’m using now is:

    cp /volume1/Scripts/vpnc_connecting /usr/syno/etc/synovpnclient/
    /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh start

    Like

    • Hello RB,

      I don’t get your second line:
      /usr/syno/etc/synovpnclient/scripts/synovpnclient.sh start

      My second line is:
      /usr/syno/bin/synovpnc connect –id=o123456789

      Where the ID is the ID in the vpnc_connecting file you are copying.

      Like

  12. Apparently after upgrading the start task no longer works, if I connect vpn mannually it just connects, but automated task does not, any thoughts ?

    Like

  13. Hi mick, where do i find the conf_id, conf_name and proto.?
    “Find your conf_id, conf_name and proto. Remember these or write them down. Exit VI with: :q!”

    Like

    • Hello Pascal,

      Start your VPN connection via the DSM webgui. When it is connected you can disconnect it.
      Via SSH navigate to /usr/syno/etc/synovpnclient/. There you will see a vpnc_last_connect file with the information in it.

      Like

  14. Thanks so much Mick for this tutorial! Very straight forward (except for the issue with displaying “–” which was explained in comments section… so not a big problem).

    This worked for me on DSM 6.2.1.23824 Update 4. One thing I found useful was to add the options “[–retry=3] [–interval=30]” in the connect command as my vpn server is often in sleep state so the first attempt at connection often does not work (whereas the retry does).

    Otherwise works great!

    Like

  15. Hi Mick,

    I wanted to thank you for this tutorial, I ‘ve been using it for a few months now and it works great.
    I try now to find if I can get an alert when the VPN falls, or if it doesn’t reconnect.
    I didn’t check if it was up for a few weeks, and it remained down for 6 days before I see it.
    Do you have an idea of a log analyser that could send me an email when the log shows “no connection”, or an other way to do it?
    I’ve been looking around but didn’t find a solution.

    Regards, ans thank you again for your work!

    Like

    • Yes it is possible. Just follow these steps:

      1: Open the DSM webpage and open Control Panel. Click Notification. If not yet done, fill in your e-mail settings here. I used a GMail account here so my DSM notifies me when scans has been done and problems may occur. You can test with the “Send a test email” button to test if the DSM can send you an e-mail. This must work before you can proceed.

      2: Open Putty or another SSH tool and connect to your DSM. Navigate to your scripts folder (e.g. cd /volume1/scripts).

      Create a new file like “check_vpn.sh”:
      sudo vi ./check_vpn.sh

      3: Press i on your keyboard to insert and paste this script into this file:

      #!/usr/bin/env bash

      vpnstate=”$(/usr/syno/bin/synovpnc get_conn)”

      if [[ $vpnstate =~ “No connection!!” ]]; then
      /usr/syno/bin/synonotify VpncReconnectFail “{\”%VPN_CLIENT%\”: \”VPN\”}”
      fi

      I pasted the script also on pastebin (it looks awefull here without markup): https://pastebin.com/6QGrGPWt

      4: Save the file with the combination :wq!

      5: Open the DSM webpage, go to Control Panel and Task Schedular. Click Create > Scheduled > user-defined script. Let it run every hour and in the Task Settings tab fill in /volume1/scripts/check_vpn.sh

      What this script does is checking what the output of /usr/syno/bin/synovpnc get_conn is. When this output contains: No Connection it means the connection is broken permanent and it triggers the default Synology VPN Reconnection e-mail to be send. %VPN_CLIENT% is a variable which does not automatically is retrieved so i gave it the name VPN. You can change the name VPN to something else if you like.

      Like

  16. Hi Mick,

    Thanks for this guide, helped me a ton!

    Just to mention for others:
    I had to include the –id between single quotes, so the last command becomes:
    /usr/syno/bin/synovpnc connect −−id=’o123456789′

    (I am running DSM 6.2.1-23824 Update 6)

    Nogmaals dank!

    Like

  17. Super veel aan deze guideline gehad dankjewel!

    De reden voor mij voortaan een VPN op me Synology te draaien was Downloadstation en Sabnzbd over NordVPN te laten lopen. Plex heb ik voor vrienden van buitenaf bereikbaar maar dat werkt dus niet bij een reboot want dan pakt die de in Plex het VPN ip.
    Zo kan je dit redelijk eenvoudig omzeilen, hoop dat iemand er iets aan heeft 🙂

    Ik ga ervan uit dat je al een werkende VPN verbinding op je Syno hebt draaien

    WinSCP -> root naar NAS -> /usr/syno/etc/synovpnclient -> open vpnc_last_connect -> verander hier niets maar pak hier de conf_id, conf_name en proto.
    Maak met texteditor 4 bestanden aan op je bureaublad bijv..
    2.1 boot_vpn
    2.2 kill_plex
    2.3 run_plex
    2.4 vpnc_connecting

    2.1 boot_vpn
    Copy / paste. Verander alleen id=********** in jouw id die je uit je vpnc_last_connect hebt gehaald
    (zorg dat er geen spaties na regels, boven script of na script staan in dit bestand

    DAY0=date -I
    touch /volume1/scripts/vpn-$DAY0.log
    /usr/syno/bin/synovpnc get_conn >>/volume1/scripts/vpn-$DAY0.log
    /usr/syno/bin/synovpnc kill_client
    sleep 5
    /volume1/scripts/kill_plex
    sleep 5
    /volume1/scripts/run_plex
    sleep 5
    cp /volume1/scripts/vpnc_connecting /usr/syno/etc/synovpnclient/
    /usr/syno/bin/synovpnc connect –id=***********
    sleep 5

    2.2 kill_plex
    Copy / paste. ook hier weer geen spaties / enters !

    synoservicecfg -stop “pkgctl-Plex Media Server”

    2.3 run_plex
    Copy / paste. ook hier weer geen spaties / enters !

    synoservicecfg -start “pkgctl-Plex Media Server”

    2.4 vpnc_connecting
    Verander hier de conf_id, conf_name en proto die je uit jouw vpnc_last_connect hebt gehaald
    Copy / paste. ook hier weer geen spaties / enters dus max 3 regels

    conf_id=id=***********
    conf_name=***
    proto=*******

    Maak via Filestation gedeelde map aan en noem deze scripts (niet via SSH)
    WinSCP -> kopieer jouw boot_vpn, run_plex, kill_plex en je aangepaste vpnc_connecting naar /volume1/scripts/
    Verander na het uploaden de rechten even voor de zekerheid apart per script met rechtermuis -> properties naar 7777 en apply
    Via Syno dashboard: Configuratie -> Task Schedular -> Create -> Triggered Task -> User-defined Script
    General: NordVPN_Bypass, User: root, Event: Boot-up, Pre-task: LAAT LEEG
    Task Settings: /volume1/scripts/boot_vpn
    Klaar…

    Laat me weten of dit voor jullie ook werkte of dat ik je misschien ergens mee kan helpen 🙂

    Groeten,

    Marc

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s