Redirection port monitor linux

Linux iptables: Port Redirection Example

H ow do I redirect 80 port to 8123 using iptables?

You can easily redirect incoming traffic by inserting rules into PREROUTING chain of the nat table. You can set destination port using the REDIRECT target.

Syntax

The syntax is as follows to redirect tcp $srcPortNumber port to $dstPortNumber:

The syntax is as follows to redirect udp $srcPortNumber port to $dstPortNumber:

Replace eth0 with your actual interface name. The following syntax match for source and destination ips:

Examples:

The following example redirects TCP port 25 to port 2525:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

In this example all incoming traffic on port 80 redirect to port 8123

Quoting from the iptables man page:

The OUTPUT chain example:

How Do I View NAT Rules?

Type the following command:

How Do I Save NAT Redirect Rules?

Type the following command:

References:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Just came across this one.Never tried but good idea.

gotta love this site.

thanks for the 1000th time 😉

Please check my query and update me if it is possible by iptables or any other software…

I have 2 application servers (i.e. A and B)

A ip is :- 192.168.11.22 and port :- 7013 (single lan card)

B ip is :- 10.10.10.22 and port :- 8014 (single lan card)

Now i want to set port fowarding/ redirection. When any client request to 192.168.11.22:7013 it will redirect to 10.10.10.22:8014 . How it is possible by iptables or any other way ?

I think for nat , two lan cards are required……

and can we pass one machine traffic to other which are on internet via port redirection….?

Thank you! I always forget how to redirect

Well heck. I thought this was my answer but adding the iptables rule to redirect outbound port 25 traffic to port 2525 has no effect. (Ubuntu 10.04)

Mixmaster is giving me cat fits because ISPs have decided that we are not allowed to send RFC compliant e-mail any more. Ever. No matter what. Any suggestions?

Can we see packet , means redirection from port 80 to port 3128 or redirect of confiugred ports in iptables rule.

My question is that , is there any tool or utility, by use of it we can see how packet handle by iptables.

How about redirecting an internal request to go out over a different interface.

I got bond0 and wlan0.

The request for a specific server let’s call it foobar on port 443. I always want to go out over wlan0 and never over bond0.

God bless you. I’ve been looking for these!

all connections are being redirected to the proxy … Why, if it is set different from the 172.16.0.0/12 and those connections I’m also going through the proxy

$IPTABLES -A PREROUTING -t nat -p tcp -i eth2 -s 10.18.83.0/24 -d ! 172.16.0.0/12 -m multiport –dports 80,443 -j DNAT –to 172.19.100.206:3128

Thanks, this was very helpful 🙂

Hi, I’ve got a quite funny setup. I connect with ssh to server1 and establish a tunnel. Packets are generated I mark the packets on the OUTPUT chain and redirect them with ip route through a vpn gateway. This works fine.

But I want to redirect the port from 80 to 3028 and this does not work on the output chain. The rule is ignored. How can I redirect the port on the Postrouting chain?

single rule doesnt work if You have a big script. Could You please publish complete firewall script with all settings ?

Does this syntax guarantee the return path from $dstPortNumber back to $srcPortNumber as well? I tried this out and it seems that my client can receive packets on the dstPort just fine, but those sent back are lost somehow.

Can you do it without iptables?

every packet arriving to port 25 will be forward to 2525, but what happens to packets arriving to port 2525? I would like to redirect them to 25, should I also add this rule?

iptables -t nat -A PREROUTING -i venet0 -p tcp –dport 1:20 -j REDIRECT –to-port 411
following request:
iptables: No chain/target/match by that name.

You want to redirect 2525 -> 25, and 25 -> 2525 – why on earth would you think that’s a great idea?

I am trying to redirect request on port 80 to 8080 (as tomcat is listening on this);

Following are the rules I added;

iptables -I INPUT -p tcp –dport 80 -j ACCEPT
iptables -t nat -I PREROUTING -p tcp –dport 80 -j REDIRECT –to-ports 8080

But, I am unable to see the tomcat page when I hit http://xxx.xx.xx.xx/ from outside.

But, when I also add the following in the IPTABLES, it works;
iptables -I INPUT -p tcp –dport 8080 -j ACCEPT

But, my question is why do I also need to expose port 8080. Because, that way http://xxx.xx.xx.xx:8080/ and http://xxx.xx.xx.xx/ would both work.

could someone help me with a better solution in this regard.

As far as I know the PREROUTING rules are applied before the INPUT rules. More in general the rules from the nat table are applied before the rules in the filter table. So, in your case, any packet going to port 80 is redirected to port 8080 (iptables -t nat -I PREROUTING -p tcp –dport 80 -j REDIRECT –to-ports 8080) and then it is filtered by the default DROP policy of the INPUT chain, which I assume you are using, in fact it doesn’t match the ACCEPT rule on port 80 (iptables -I INPUT -p tcp –dport 80 -j ACCEPT).

You have already verified it, as you said if you add a rule to accept INPUT packets on port 8080, both http://xxx.xx.xx.xx:8080/ and http://xxx.xx.xx.xx/ work properly. The former because it connects to port 8080 which is open, the latter because it connects to port 80 and gets redirected to port 8080 which is open.
To further verify it you should run iptables -L -n -v more times and check that the packet counter of the rule iptables -I INPUT -p tcp –dport 80 -j ACCEPT remains 0 even if you connect to http://xxx.xx.xx.xx/ between a run and the other.
As last option, for debugging purposes, you could add a LOG rule for packets on the 80 port and study the logs to see if any packet is accepted (syntax is easy, where the logs are depends on your system). Just remember to add it in the table just before the related ACCEPT rule and not after, otherwise the LOG rule would be ignored.

As last thing, don’t worry about how scary and difficult iptables can seem as everything I’ve told you I’ve learned this afternoon just by googling around and the good old trial and error 😉
Good luck

Hey I need help in port Redirection
This is my setup and it does not work
#iptables -A FORWARD -i eth1 -o eth0 -p tcp –dport 3390 -d 192.168.200.2 -j ACCEPT
#iptables -t nat -A PREROUTING -p tcp -i eth1 –dport 3389 -j DNAT –to 192.168.200.2:3389
I have ubuntu server 12.04 with two network card
This eth0 LAN
This eth1 WAN

I need to access from any to the addresses 192.168.200.2 Port 3390 and redirect to Port 3389 to (RDP)
My firewall is disabled

Is there a way to redirect only the allowed traffic to a specific port?
Either I am able to redirect or drop but not both of them together.

doesn’t make the config persistent, that just dumps out the running config. You’ll need to backup

/etc/sysconfig/iptables then run

to make the running config persistent accross reboots

Источник

Мониторинг портов с уведомлением сисадмина

Недавно возникла потребность в периодическом мониторинге серваков на предмет падения некоторых сервисов (читай портов) и уведомления админа (те меня) при возникновении ошибки.

Решение — под катом

Итак что мы несколько серваков, кучу портов. проверяем порт на открытость классически — nmap’ом
пример вывода:

/scripts# nmap 192.168.1.1 -p3389
Starting Nmap 4.11 ( www.insecure.org/nmap ) at 2009-05-06 14:54 GMT-4
Interesting ports on 192.168.1.1:
PORT STATE SERVICE
3389/tcp open ms-term-serv
MAC Address: 00:50:8D:EB:7E:08 (Abit Computer)

Nmap finished: 1 IP address (1 host up) scanned in 0.132 seconds

это значит что сервер терминалов поднят, и скорее всего работает 🙂
если вместо опен будет написано чтото иное — соответственно косяк, надо сообщать.

Долго придумывал систему сообщения. Пришел от сложнейшего — к простейшему. У пчелайна есть такой сервис mailtosms, если на ящик формата 890912345678@sms.beemail.ru отправить письмо — то оно одойдет смской содержащей текст письма.

итак задача — из списка серваков и портов сканить все подряд и что не открыто — выписывать в отдельный файл и отправлять нам на мыло.

#!/bin/bash
for a in $ ( servers ) ; do nmap ` echo $a | sed -e ‘s/:/ -p /’ ` | grep -q «/tcp *open » || echo $a ; done > / var / test / serverlist;
DATENOW =$ ( date + % d- % m- % Y_ % T )
if ( ! ( [ -z $ ( cat / var / test / serverlist ) ] ) ) ; then
echo $DATENOW >> / var / test / log
cat / var / test / serverlist >> / var / test / log
mail 7909 *******@ sms.beemail.ru / var / test / serverlist
fi
exit

Как это работает?
создаем файл servers, ложим рядом с самим скриптом.
содержание файла servers примерно такое:
192.168.1.1:80
192.168.1.2:25
192.168.1.3:110
Ну в общем понятно
команда sed -e ‘s/:/ -p /’` заменяет «:» на «-p»
for a in $( /var/test/serverlist; — выдирает строки если порт не открыт и толкает их в файл serverlist
после чего файл проверяется на наличие в нем чего либо и если там чтото есть, это пишется в лог (для отладки) и отправляется на мыло/телефон одмина.
вуаля. добавляем в кронтаб, раз в час (чтобы не напрягало) и пользуемся

ЗЫЖ я знаю что есть вещи типа nagios и прочие мониторы сети, но они слишком мощны и сложны в конфигурировании когда достаточно просто просканить порты нескольких серваков.

Источник

Печатаем по сети на любом Windows-принтере

Если у вас есть принтер, подключенный к Windows машине, то настроить его для сетевой печати на Mac достаточно просто, даже если драйверов для OSX для этого принтера не существует.

Для этого нужны три вещи:

  • Принтер, исправно работающий на Windows машине
  • Ghostscript — эмулятор PostScript принтера
  • RedMon — Redirection Port Monitor

Скачиваем и устанавливаем дистрибутивы.
Для удобства описания и настройки — производим установку в папку C:\gs

Настройка виртуального принтера в Windows

В моем примере два принтера без OSX драйверов — монхромный, лазерный «Samsung ML2250» и цветной, лазерный «Konica 2400W». Начнем с черно-белого Samsung.
Для начала, нужно создать файл конфигурации для этого принтера, C:\gs\samsung.rsp, его содержимое:

В последней строке необходимо указать точное название реального принтера, установленного и настроенного в системе (можно с пробелами). Для монохромного принтера я добавил строку «-mono».

Теперь нужно настроить виртуальный принтер. Для этого запускаем стандартный wizard и добавляем новый локальный принтер:

В качестве порта выбираем «Redirected Port»:

Wizard создаст новый Redirect-port и предложит его переименовать, оставляем все как есть:

На следующем шаге необходимо выбрать стандартный драйвер для виртуального принтера, и лучше всего для этого подойдет набор драйверов от Apple. Выбираем лазерный черно-белый принтер. Я выбрал «Apple LaserWriter 16/600 PS».

Соглашаемся с предложением сохранить существующий драйвер:

Указываем название принтера:

Сразу можно «расшарить» принтер:

Теперь можно указать дополнительные данные, например пояснить, как именно устанавливать принтер и какие драйвера для этого использовать:

На этом шаге печатать тестовую страницу не нужно:

Установка принтера завершена:

Переходим к настройкам полученного принтера, на закладке «Ports» выбираем только что созданный порт «RPT1: Redirected Port»:

Конфигурация порта «RPT1: Redirected Port»:

В поле «Redirect this port to the program» с помощью «Browse» указываем путь до gswin32c.exe, в нашем случае это C:\gs\gs8.64\bin\gswin32c.exe

В строке «Arguments for this program are:» указываем путь до файла настройки принтера в формате Ghost: @C:\gs\samsung.rsp —

Обратите внимание, очень важно не забыть после имени файла поставить «пробел» и «-».

В селекте «Output» выбираем «Copy temporary file to printer».

В качестве «Printer» выбираем реальный принтер, в моем случае это «Samsung ML-2250».

«Run» — «Hidden» — скрываем все диалоги и окна программы.

На этом настройка принтера на Windows машине закончена, теперь можно проверить работоспособность редиректа напечатав пробную страницу из панели настроек виртуального принтера.

Настройка принтера в Leopard

Запускаем «System Preferences» и выбираем «Print & Fax».

На моем скриншоте уже настроены оба принтера 🙂 Для настройки еще одного — нажимаем «+» и выбираем подключение по «IP».

«Protocol» — «Line Printer Daemon — LPD»

«Address» — IP адрес Windows машины с расшареным принтером.

«Name» — пишем название для принтера.

«Location» — значение, указанное на этапе настройки Windows принтера в поле «Location» (это не обязательное условие, но так акуратнее).

«Print Using» — «Select a driver to use» и пользуясь удобным поиском выбираем «Apple LaserWriter 16/600 PS».

Нажимаем «Add». На этом подключение принтера в Leopard — завершено. Проверяем, радуемся.

Настройка цветного лазерного принтера «Konica 2400W» производилась аналогично. В качестве драйвера был выбран «Apple Color LaserWriter 12/600 PS», а в файле конфигурации принтера был удален параметр -mono.

Источник

Читайте также:  Инвертировать прокрутку тачпада windows 10
Оцените статью