Unix

특정 포트로 들어온 트래픽 다른 호스트로 포워딩하기

ForceCore 2022. 7. 27. 09:19
#!/bin/bash

# 이 스크립트는 sudo로 실행시킬 것

# 이 host에서 `telnet 192.168.111.222 9999` 를 눌러서 접속이 되면 ok,
# 잘못된 곳에 붙으면 아예 connection이 안 될 것임.
# `curl 192.168.111.222:9999` 도 괜찮음.
# curl: (1) Received HTTP/0.9 when not allowed
# 이런 반응이 온다.

# 점검을 한 뒤 forwarding이 실제로 되나 체크

# 참고:
# https://www.digitalocean.com/community/tutorials/how-to-forward-ports-through-a-linux-gateway-with-iptables

DEST=192.168.111.222
PORT=9999
THIS_IP=192.168.111.111

# To turn port forwarding on for this session only, run the following:
echo 1 > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A PREROUTING -i eth0 -p tcp --dport $PORT -j DNAT --to-destination $DEST
iptables -t nat -A POSTROUTING -o eth0 -p tcp --dport $PORT -d $DEST -j SNAT --to-source $THIS_IP

위 예제는 192.168.111.111:9999로 들어온 연결을 192.168.111.222:9999로 포워딩해주는 예제이다. 클라우드의 서버들에서 일일이 방화벽 열기는 싫고 그럴 때 쓸 수 있다?