Using Netcat (nc) to query OpenVPN management interface



  • Based on this old thread I am trying to create a simple shell script to query the status of a particular openvpn tunnel using netcat so I can attempt to auto-restart it if it goes down.

    I tried the following variations of the commands

    printf "state 1\r\nexit\r\n" | nc -U /var/etc/openvpn/client1.sock
    
    printf "state 1\nexit\n" | nc -U /var/etc/openvpn/client1.sock
    
    echo -e 'state 1\nexit\n' | nc -U /var/etc/openvpn/client1.sock
    

    each of those output

    >INFO:OpenVPN Management Interface Version 1 -- type 'help' for more info
    

    and then immediately exit without printing the "state" portion

    printf "state 1\r\n" | nc -U /var/etc/openvpn/client1.sock
    

    successfully outputs the VPN status but then "hangs" in nc, I have to CTRL+C to get out (even typing 'quit' does not exit)

    I am on 2.3.2_p1.  Has anyone got any idea how to successfully query this status via script? I looked at the PHP code in the OpenVPN widget and it is using a similar socket interface.



  • Well, nobody answered but I figured out a workaround. Not sure if this is correct or safe but FWIW adding the '-w 1' option causes the nc to time out after 1s which effectively "solves" this problem:

    printf "state 1\r\nstatus 2\r\n" | nc -w 1 -U /var/etc/openvpn/client1.sock



  • @luckman212, unbelievably late to the party here but thank you, this is exactly what I was looking for! Much appreciated for you putting your solution!


Log in to reply