Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes
419 views
419 views

I have several OpenVPN connections and need to identify the tun device for one of them.

I know the device name is recorded in the system logs when the connection is being established, so I could grep it from there. However, log parsing is always a bit clunky, so I would like to avoid it if possible. ip route output is also not really helpful, since I'd need to know at least the client IP first.

I can get the VPN client PID from /run/openvpn/CONNECTION_NAME.pid, so I thought I might be able to get the information via lsof, but that just gives me /dev/net/tun, not the particular tun device:

me@localhost:~ $ sudo lsof -p 22746
COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF     NODE NAME
...
openvpn 22746 root    5u   CHR             10,200    0t108    10802 /dev/net/tun

Is there another way to get the device from the PID?

in Scripting
by (125)
3 19 33
edit history

Please log in or register to answer this question.

1 Answer

0 votes
 

The name of the device can be obtained from /proc/$PID/fdinfo/5:

root@localhost:~ # cat /proc/22746/fdinfo/5
pos:	52
flags:	02104002
mnt_id:	19
iff:	tun0

So you should be able to obtain the device name like this:

PID="$(cat /run/openvpn/CONNECTION_NAME.pid)"
grep -oP '^iff:\s*\K.*' /proc/"$PID"/fdinfo/5

The parameter -o instructs grep to display only the matched substring instead of the entire line. \K in a Perl-compatible regular expression (-P) is a kind of lookbehind assertion. The part before \K is used for matching the string, but is not included in the string returned from the match, so you get just "tun0" without the leading "iff:".

I think the tundevice is always file descriptor 5. Otherwise you need to enumerate the files under /proc/$PID/fdinfo and pick the one with the tun device entry.

Beware that the fdinfo subdirectories have 0600 permissions, so they're only accessible by the process owner. For VPN processes that means you need root privileges, so you must run the command via su or sudo or similar.


edited by
by (125)
3 19 33
edit history
...