9

I've written the following systemd service tcpdumpd.service to kick off a persistent tcpdump recording.

[Unit]
Description=TCPDumpd
After=multi-user.target network.target

[Service]
Type=simple
ExecStart=/usr/sbin/tcpdump -pni eth0 -s65535 -G 3600 -w '/var/log/tcpdump/trace_%Y-%m-%d_%H:%M:%S.pcap' -z gzip
Restart=on-abort

[Install]
WantedBy=multi-user.target

tcpdump allows strftime-placeholders like %H for hour, %M for minute and so on to allow you to create time stamped files.

However, systemd has special specifiers than can be used in it, like (%n, %N, %p, %i, %U, %u, %m, %H, %b, %v) So any of the specifiers that overlap, like %m and %H pass through the information from systemd and don't allow the placeholder to be passed through to tcpdump to make the time stamp.

Does anyone know if there is a way to escape the specifiers in systemd so I can pass the %m and %H through to tcpdump?

Ben Sooter
  • 317
  • 1
  • 3
  • 11

2 Answers2

10

I've tried to escape special specifiers like %%m, \%m without luck.

But, if you need the work to be done, here is workaround:

Create file tcpdumpd.environment containing definition of TCPDUMP_FORMAT variable.

TCPDUMP_FORMAT=%Y-%m-%d_%H:%M:%S

Modify tcpdumpd.service: add EnvironmentFile= option to it and replace format string with ${TCPDUMP_FORMAT}.

[Unit]
Description=TCPDumpd
After=multi-user.target network.target

[Service]
Type=simple
EnvironmentFile=tcpdumpd.environment
ExecStart=/usr/sbin/tcpdump -pni eth0 -s65535 -G 3600 -w '/var/log/tcpdump/trace_${TCPDUMP_FORMAT}.pcap' -z gzip
Restart=on-abort

[Install]
WantedBy=multi-user.target
alexander
  • 2,703
  • 18
  • 16
  • This is the solution. Found [this answer](http://stackoverflow.com/questions/28881758/how-can-i-use-spaces-in-systemd-command-line-arguments?rq=1) that got me to your exact solution. Thanks! – Ben Sooter Nov 10 '16 at 17:15
  • 1
    With `systemd` version 215 you can use `Environment="TCPDUMP_FORMAT=%%Y-%%m-%%d_%%H:%%M:%%S"` instead of an `EnvironmentFile`. – Iskren Jun 22 '17 at 16:21
5

Does anyone know if there is a way to escape the specifiers in systemd so I can pass the %m and %H through to tcpdump?

Yes: %%m and %%H.

See man systemd.unit:

"%%" | Single percent sign | Use "%%" in place of "%" to specify a single percent sign.

Heinrich Hartmann
  • 1,205
  • 11
  • 13