Tcpreplay ubuntu как пользоваться

Обновлено: 06.07.2024

tcpreplay is a tool for replaying network traffic from files saved with tcpdump or other tools which write pcap(3) files.

DESCRIPTION

The basic operation of tcpreplay is to resend all packets from the input file(s) at the speed at which they were recorded, or a specified data rate, up to as fast as the hardware is capable.

Optionally, the traffic can be split between two interfaces, written to files, filtered and edited in various ways, providing the means to test firewalls, NIDS and other network devices.

OPTIONS

-d number, --dbug=number

Enable debugging output. This option may appear up to 1 times. This option takes an integer number as its argument. The value of number is constrained to being:

in the range 0 through 5

The default number for this option is:
0

If configured with --enable-debug, then you can specify a verbosity level for debugging output. Higher numbers increase verbosity.

-q, --quiet

Print nothing except the statistics at the end of the run

-T string, --timer=string

Select packet timing mode: select, ioport, gtod, nano. This option may appear up to 1 times. The default string for this option is:
gtod

Allows you to select the packet timing method to use:

nano - Use nanosleep() API

select - Use select() API

ioport - Write to the i386 IO Port 0x80

gtod [default] - Use a gettimeofday() loop

--maxsleep=number

Sleep for no more then X milliseconds between packets. This option takes an integer number as its argument. The default number for this option is:
0

Set a limit for the maximum number of milliseconds that tcpreplay will sleep between packets. Effectively prevents long delays between packets without effecting the majority of packets. Default is disabled.

-v, --verbose

Print decoded packets via tcpdump to STDOUT. This option may appear up to 1 times.

-A string, --decode=string

Arguments passed to tcpdump decoder. This option may appear up to 1 times. This option must appear in combination with the following options: verbose.

When enabling verbose mode (-v) you may also specify one or more additional arguments to pass to tcpdump to modify the way packets are decoded. By default, -n and -l are used. Be sure to quote the arguments like: -A "-axxx" so that they are not interpreted by tcpreplay. Please see the tcpdump(1) man page for a complete list of options.

-K, --preload-pcap

Preloads packets into RAM before sending.

This option loads the specified pcap(s) into RAM before starting to send in order to improve replay performance while introducing a startup performance hit. Preloading can be used with or without --loop. This option also suppresses flow statistics collection for every iteration, which can significantly reduce memory usage. Flow statistics are predicted based on options supplied and statistics collected from the first loop iteration.

-c string, --cachefile=string

Split traffic via a tcpprep cache file. This option may appear up to 1 times. This option must appear in combination with the following options: intf2. This option must not appear in combination with any of the following options: dualfile.

If you have a pcap file you would like to use to send bi-directional traffic through a device (firewall, router, IDS, etc) then using tcpprep you can create a cachefile which tcpreplay will use to split the traffic across two network interfaces.

-2, --dualfile

Replay two files at a time from a network tap. This option may appear up to 1 times. This option must appear in combination with the following options: intf2. This option must not appear in combination with any of the following options: cachefile.

If you captured network traffic using a network tap, then you can end up with two pcap files- one for each direction. This option will replay these two files at the same time, one on each interface and inter-mix them using the timestamps in each.

-i string, --intf1=string

Client to server/RX/primary traffic output interface. This option may appear up to 1 times.

Required network interface used to send either all traffic or traffic which is marked as ’primary’ via tcpprep. Primary traffic is usually client-to-server or inbound (RX) on khial virtual interfaces.

-I string, --intf2=string

Server to client/TX/secondary traffic output interface. This option may appear up to 1 times.

Optional network interface used to send traffic which is marked as ’secondary’ via tcpprep. Secondary traffic is usually server-to-client or outbound (TX) on khial virtual interfaces. Generally, it only makes sense to use this option with --cachefile.

List available network interfaces and exit.

-l number, --loop=number

Loop through the capture file X times. This option may appear up to 1 times. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 0

The default number for this option is:
1

--loopdelay-ms=number

Delay between loops in milliseconds. This option must appear in combination with the following options: loop. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 0

The default number for this option is:
0

Override the snaplen and use the actual packet len. This option may appear up to 1 times.

By default, tcpreplay will send packets based on the size of the "snaplen" stored in the pcap file which is usually the correct thing to do. However, occasionally, tools will store more bytes then told to. By specifying this option, tcpreplay will ignore the snaplen field and instead try to send packets based on the original packet length. Bad things may happen if you specify this option.

-L number, --limit=number

Limit the number of packets to send. This option may appear up to 1 times. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 1

The default number for this option is:
-1

By default, tcpreplay will send all the packets. Alternatively, you can specify a maximum number of packets to send.

--duration=number

Limit the number of seconds to send. This option may appear up to 1 times. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 1

The default number for this option is:
-1

By default, tcpreplay will send all the packets. Alternatively, you can specify a maximum number of seconds to transmit.

-x string, --multiplier=string

Modify replay speed to a given multiple. This option may appear up to 1 times. This option must not appear in combination with any of the following options: pps, mbps, oneatatime, topspeed.

Specify a value to modify the packet replay speed. Examples:
2.0 will replay traffic at twice the speed captured
0.7 will replay traffic at 70% the speed captured

-p string, --pps=string

Replay packets at a given packets/sec. This option may appear up to 1 times. This option must not appear in combination with any of the following options: multiplier, mbps, oneatatime, topspeed.

Specify a value to regulate the packet replay to a specific packet-per-second rate. Examples:
200 will replay traffic at 200 packets per second
0.25 will replay traffic at 15 packets per minute

-M string, --mbps=string

Replay packets at a given Mbps. This option may appear up to 1 times. This option must not appear in combination with any of the following options: multiplier, pps, oneatatime, topspeed.

Specify a floating point value for the Mbps rate that tcpreplay should send packets at.

-t, --topspeed

Replay packets as fast as possible. This option must not appear in combination with any of the following options: mbps, multiplier, pps, oneatatime.

-o, --oneatatime

Replay one packet at a time for each user input. This option must not appear in combination with any of the following options: mbps, pps, multiplier, topspeed.

Allows you to step through one or more packets at a time.

--pps-multi=number

Number of packets to send for each time interval. This option must appear in combination with the following options: pps. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 1

The default number for this option is:
1

When trying to send packets at very high rates, the time between each packet can be so short that it is impossible to accurately sleep for the required period of time. This option allows you to send multiple packets at a time, thus allowing for longer sleep times which can be more accurately implemented.

Modify IP addresses each loop iteration to generate unique flows. This option must appear in combination with the following options: loop.

Ensure IPv4 and IPv6 packets will be unique for each --loop iteration. This is done in a way that will not alter packet CRC, and therefore will genrally not affect performance. This option will significantly increase the flows/sec over generated over multiple loop iterations.

--unique-ip-loops=string

Number of times to loop before assigning new unique ip. This option may appear up to 1 times. This option must appear in combination with the following options: unique-ip.

Number of --loop iterations before a new unique IP is assigned. Default is 1. Assumes both --loop and --unique-ip.

Write packets directly to netmap enabled network adapter.

This feature will detect netmap capable network drivers on Linux and BSD systems. If detected, the network driver is bypassed for the execution duration, and network buffers will be written to directly. This will allow you to achieve full line rates on commodity network adapters, similar to rates achieved by commercial network traffic generators. Note that bypassing the network driver will disrupt other applications connected through the test interface. See INSTALL for more information.

This feature can also be enabled by specifying an interface as ’netmap:<intf>’ or ’vale:<intf>. For example ’netmap:eth0’ specifies netmap over interface eth0.

--nm-delay=number

Netmap startup delay. This option takes an integer number as its argument. The default number for this option is:
10

Number of seconds to delay after netmap is loaded. Required to ensure interfaces are fully up before netmap transmit. Requires netmap option. Default is 10 seconds.

--no-flow-stats

Suppress printing and tracking flow count, rates and expirations.

Suppress the collection and printing of flow statistics. This option may improve performance when not using --preload-pcap option, otherwise its only function is to suppress printing.

The flow feature will track and print statistics of the flows being sent. A flow is loosely defined as a unique combination of a 5-tuple, i.e. source IP, destination IP, source port, destination port and protocol.

If --loop is specified, the flows from one iteration to the next will not be unique, unless the packets are altered. Use --unique-ip or tcpreplay-edit to alter packets between iterations.

--flow-expiry=number

Number of inactive seconds before a flow is considered expired. This option must not appear in combination with any of the following options: no-flow-stats. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 0

The default number for this option is:
0

This option will track and report flow expirations based on the flow idle times. The timestamps within the pcap file are used to determine the expiry, not the actual timestamp of the packets are replayed. For example, a value of 30 suggests that if no traffic is seen on a flow for 30 seconds, any subsequent traffic would be considered a new flow, and thereby will increment the flows and flows per second (fps) statistics.

This option can be used to optimize flow timeout settings for flow products. Setting the timeout low may lead to flows being dropped when in fact the flow is simply slow to respond. Configuring your flow timeouts too high may increase resources required by your flow product.

Note that using this option while replaying at higher than original speeds can lead to inflated flows and fps counts.

Default is 0 (no expiry) and a typical value is 30-120 seconds.

-P, --pid

Print the PID of tcpreplay at startup.

--stats=number

Print statistics every X seconds, or every loop if ’0’. This option takes an integer number as its argument. The value of number is constrained to being:

greater than or equal to 0

Note that timed delays are a "best effort" and long delays between sending packets may cause equally long delays between printing statistics.

-V, --version

Print version information.

-h, --less-help

Display less usage information and exit.

-H, --help

Display usage information and exit.

-!, --more-help

Pass the extended usage information through a pager.

--save-opts [=cfgfile]

Save the option state to cfgfile. The default is the last configuration file listed in the OPTION PRESETS section, below. The command will exit after updating the config file.

--load-opts=cfgfile, --no-load-opts

Load options from cfgfile. The no-load-opts form will disable the loading of earlier config/rc/ini files. --no-load-opts is handled early, out of order.

OPTION PRESETS

Any option that is not marked as not presettable may be preset by loading values from configuration ("RC" or ".INI") file(s). The homerc file is "$$/", unless that is a directory. In that case, the file ".tcpreplayrc" is searched for within that directory.

FILES

See OPTION PRESETS for configuration files.

EXIT STATUS

One of the following exit values will be returned:
0 (EXIT_SUCCESS)

Successful program execution.

The operation failed or the command syntax was not valid.

A specified configuration file could not be loaded.

AUTHORS

COPYRIGHT

Copyright (C) 2000-2018 Aaron Turner and Fred Klassen all rights reserved. This program is released under the terms of the GNU General Public License, version 3 or later.

NOTES

This manual page was AutoGen-erated from the tcpreplay option definitions.

tcpreplay has evolved quite a bit over the years. In the 1.x days, it merely read packets and sent then back on the wire. In 2.x, tcpreplay was enhanced significantly to add various rewriting functionality but at the cost of complexity, performance and bloat. In 3.x, tcpreplay has returned to its roots to be a lean packet sending machine and the editing functions have moved to tcprewrite and a powerful tcpreplay-edit which combines the two.

In 4.x [IP FLow][flow] and netmap features where added. Minor edit capabilities were added, but not at the cost of performance. Essentially tcpreplay is intended to be fast, and all options are designed to work at wire rates. Options that may affect performance such as run-time packet editing have been moved to tcpreplay-edit.

Basic usage

To replay a given pcap as it was captured all you need to do is specify the pcap file and the interface to send the traffic out interface eth0 :

Examples

The following examples use one of provided sample captures on an i7 processors with multi-port Intel 82599 10GigE adapters.

By default the pcap file is played back at the same rate that it was captured at. If you prefer to play back at a specific speed, add the --mbps option.

To replay as with zero time between packets:

Now notice that you can substitute -t for --topspeed . You could also get the same result with --mbps=0 . Repeat the sending of the pcap file with the --loop option and notice that performance increases somewhat.

Now let’s see a performance boost with the -K option, which will cause packets to be read from memory instead of disk. You may want to consider using this option whenever there is enough memory available for the pcap file.

Advanced Usage

To obtain near wire rate you need to compile and install [netmap]nm] network drivers. This will bypass the network driver for the duration of the test and allow tcpreplay to write to the network hardware directly. Note that the network stack will not be operational on the selected interface while the test is running.

To increase the flows per second (fps) you need to ensure that the IP addreses are unique for every loop iteration by specifying the --unique-ip option.

If you need to control the flows per second you can do so by trying different values of --mbps (or -M ) option:

Testing Routers or Switches

On your tcpreplay device you will need to use two network adapters attached to input and output ports of the device under test (DUT). See tcpprep help for examples that illustrate how to classify traffic. For example you can classify packets inside a pcap file as either client or server. Or you could classify private vs. public.

The result of tcprep is a cache file which allows tcpreplay to send traffic through a device in two directions through a device, and thereby maintaining state.

Alternatively, if you have already split your traffic into two files, as in the case of capturing traffic using a network tap, then tcpreplay can read two files at the same time, one for each interface:

This section is designed to get you up and running quickly and easily by supplying step-by-step examples of various scenarios.

The following how-to examples use one of provided sample captures. Two identical machines are used, each with i7 processors and multi-port Intel 82599 10GigE adapters. The 10GigE adapters are connected back-to-back with patch cables. LAN connectivity with SSH is via one of the GigE interfaces. GigE interfaces are numbered eth0 through eth5. The 10GigE interfaces are eth6 and eth7.

Both systems are running Ubuntu 10.04 with a Linux version 3.1.10 kernel.

There are several screencast videos available that are related this section. The entire play list of screencasts are available here, or you can watch all screencasts below. If you are more interested in detailed descriptions, skip the screencasts and proceed to the next section.

How to do a Performance Test for an IP Flow Appliance

Use this example if you need to test the performance of a device that captures and reports IP Flow/NetFlow statistics. In this example we are sending to a device under test (DUT) running nprobe. We will use the nprobe logging features to measure how many packets, bytes and flows per second are captured.

The ability to generate wire-rate traffic and extremely high flows-per-second is new in Tcpreplay v4.0.0. The physical setup is very simple. In our experience Tcpreplay will greatly outperform the receiving station. Therefore it is important to track the amount of traffic sent and received, and determine the amount of data lost.

  • Download and install the latest release of Tcpreplay on the test machine
  • Download bigFlows.pcap onto the test machine (see captures wiki for details)
  • Download and install nprobe on the DUT
  • Start nprobe on DUT …
  • On the test station, send some traffic …
    • The --unique-ip option will ensure that IP addresses are unique for every loop iteration, which will result in unique flows for every iteration
    • The -K option will preload the PCAP file into memory before testing. Omit if you do not have enough memory for this option.
    • The -t option will send as quickly as possible. If you want to reduce the rate, replace -t with --mbps option
    • In this example we are only sending for about 20 seconds, but we recommending increasing --loop option to generate several minutes of traffic
    • On the DUT observe the flow statistics received …
      • Notice that when the DUT is receiving 100K flows/sec it is not able to process everything. This is common for many flow products.
      • Loss will most likely increase with the amount of processing that flow tool is asked to do. For example, we would expect loss to increase if we were to enable deep packet inspection (DPI) to classify the application type.
      • Industry expects flow tools to process 5 fps per Mbps. Therefore this 10GigE link should be able to perform at 50Kfps (50,000 flows per second)

      Reducing Flows Per Second

      To reduce the flow rate to 50Kfps you adjust the --mbps option …

      Increasing Flows Per Second with netmap

      We have already shown that the maximum rate that we can send is just over 7 Gbps. To increase flow rate to maximum possible with selected capture file you must install netmap, which will allow Tcpreplay to write directly to the network adapters TX buffers.

      Note: Using netmap is invasive and is not for the faint of heart. You should be somewhat familiar with compiling kernel modules before proceeding. Also, be aware that the network stack will be disconnected from the selected network adapter for the duration of the test. If you use SSH, do not connect via the same interface that you are testing on.

      • Download netmap tarball and extract. Note that you will have to eventually compile netmap but it isn’t necessary to do so if you are simply compiling Tcpreplay with netmap capabilities. If you are able to extract into /usr/src or /usr/local/src you can simply go to your Tcpreplay source directory and enter …
      • If you extract elsewhere you will need to supply the location of the netmap source, for example …
      • You will need to compile netmap using instructions in its README file. Specifics on how to install the driver is beyond the scope of this document. However, here is a script that we developed which will allow us to temporarily install the netmap_lin module and the netmap-enabled ixgbe 10GigE driver …
      • When you have the netmap drivers installed, tcpreplay will be able to exploit this feature when using the --netmap option. Otherwise the drivers run in normal mode and applications will run normally …
        • Notice that the link is saturated and therefore 135 Kfps is the maximum we can achieve with this pcap file and this 10GigE link
        • If you download smallFlows.pcap you may see even higher flows per second. This capture has smaller flows and therefore is able to generate up to 157 Kfps before the link is saturated.
          • When using netmap, the size of the flows within the capture file is the limiting factor in determining maximum fps. We have been able to generate 18 Mfps using a capture with only 64 byte packets

          How to do a Performance Test for a Packet Capture Device

          When testing to a packet capture device or a capture application such as tcpdump, the setup is similar to the IP Traffic Flow Appliance example above. Instead of nprobe run your packet capture application.


          tcpreplay — набор консольных C (си) утилит для инициирования сессий на основе перехваченного трафика, утилиты для редактирования и воспроизведения PCAP-файлов.


          Набор утилит tcpreplay изначально разрабатывался для воспроизведения шаблонов вредоносного трафика и предотвращения вторжений. В дальнейшем утилиты претерпели множество изменений, включая возможность воспроизведения на веб-серверах.



          Давшая название набору утилита tcpreplay воспроизводит PCAP файлы с произвольной скоростью, tcprewrite позволяет редактировать и создавать PCAP файлы, tcpreplay-edit редактирует PCAP файлы и воспроизводит их в сети, tcpprep создаёт файлы кеша определений клиент/сервер (используемых tcpreplay и tcprewrite).



          Утилита tcpbridge обеспечивает соединение двух сегментов сети (с помощью tcprewrite), tcpliveplay воспроизводит распознаваемые серверами TCP PCAP файлы, tcpcapinfo предназначается для декодирования и отладки PCAP-файлов (например созданных утилитой tcpdump).


          Повторная генерация потока с помощью набора утилит tcpreplay может быть полезна для оценки поведения различных приложений на различные атаки, при изучении причин сбоев в сетевом программном обеспечения или проведения нагрузочного тестирования (можно менять интенсивность отправки пакетов).

          Читайте также: