So I finally managed to solve my problem. I was almost ready to write my own openvpn plugin to solve that problem. Luckily I didn't have to.
First Try: I wrote a small script using expect that did exactly what I wanted
#!/usr/bin/expect
set timeout 1
set ip localhost
set port 7505
spawn telnet $ip $port
#expect "‘^]’."
sleep 2
send -- "help\r"
expect "END"
send -- "log on\r"
expect "*SUCCESS*"
send -- "bytecount 10\r"
expect "SUCCESS"
interact
And I started that script via:
chmod a+x myscript.sh
./myscript.sh
And this worked fine. The next step was trying to automate that as a linux service. So I tried starting the script with different using different ways
./myscript.sh >/var/log/myscript.log &
./myscript.sh /var/log/myscript.log | at now +1m
nohup myscript.sh &
To no success!! I failed utterly to achieve my goal. Either not all commands would be executed or the window just hangs and I cannot cancel the command and restore control over the window.
Finally I managed to solve my problem using 'screen' . I started a screen and was able to send all kinds of commands to that screen. Even better, the telnet session remains active (do not know for how long though). Anyways here's the solution:
#First create the screen session or else nothing will work
screen -dmS "abc"
#The next line logs everything from that screen into the file /var/log/myscript.log
screen -S "abc" -X stuff "script -f /var/log/myscript.log \r"
#Starting from here are all commands that you'd usually type into the open telnet session to interact with openvpn management
screen -S "abc" -X stuff "telnet localhost 7505 \r"
screen -S "abc" -X stuff "log on \r"
screen -S "abc" -X stuff "bytecount 10 \r"
If you only have one screen, you can even omit (-S "abc") parameter in the last three commands sent to telnet.
This way I'm able to automate all interaction with openvpn management.
One last trick. I also wanted to issue commands to the management console and be able to parse their output. The problem is that /var/log/myscript.log logs everything. So I did the following, which can also be part of a script:
#Tailing the log file, but start after the last line, i.e. empty log
tail -n 0 -f /var/log/telnet.log > my_command_output.log &
#Send arbitrary openvpn management console command which we are interested in its output
screen -S "abc" -X stuff "state on \r"
#kill the tail process
kill %1
#Show the command output
cat /var/log/telnet.log
May someone finds helps in this answer