본문 바로가기

TroubleShooting/Linux

IP / Port 연결 테스트

728x90

서비스 중인 port 연결 확인을 위해 보통 telnet 을 많이 사용한다. 웹이라면 curl 이나 wget 을 사용할 것이다.

그런데, telnet 이 설치가 안되어 있는 환경(컨테이너 또는 보안상 telnet 설치를 못하는) 에서 연결 테스트하기가 난감하다.

 

그럴때, 리눅스에 기본적으로 설치되는 외부 명령어인 echo 를 이용하면 연결 테스트를 할 수 있다.

# echo > /dev/tcp/www.naver.com/80
#
-> 실행 즉시 바로 프롬프트가 나오면 정상 연결

# echo > /dev/tcp/www.naver.com/80
-bash: connect: Connection timed out
-bash: /dev/tcp/www.naver.com/8081: Connection timed out
-> 실행후 타임아웃 메시지가 나오면 연결 실패

위의 방법을 응용해서 다음과 같은 스크립트를 작성할 수 있다.

# vi connect-test.sh
------------------
#! /bin/bash
 
while read -a LINE
do
  echo > /dev/tcp/${LINE[0]}/${LINE[1]} && echo "${LINE[0]} ${LINE[1]} up" || echo "${LINE[0]} ${LINE[1]} down"
done < servers.txt
# vi server.txt
apis.naver.com 443
www.googleapis.com 443
kapi.kakao.com 443
api.kakao.com 443

# ./connect-test.sh
apis.naver.com 443 up
www.googleapis.com 443 up
kapi.kakao.com 443 up
api.kakao.com 443 up

또다른 방법으로는 curl 에서 지원하는 프로토콜 방식으로 확인할 수 있다.

curl 로 보통 주소 앞에 http 나 https 대신에 telnet 으로 바꾸고 "-v" 으로 추가해서 진행 메시지를 확인한다(-verbose).

-v 옵션을 추가안하면 "Trying ...", "connet to" 메시지가 안 보이니 추가해주는게 좋다.

% curl -v telnet://10.166.114.208:29309
*   Trying 10.166.114.208:29309...
* connect to 10.166.114.208 port 29309 failed: Connection refused
* Failed to connect to 10.166.114.208 port 29309 after 9 ms: Connection refused
* Closing connection 0
curl: (7) Failed to connect to 10.166.114.208 port 29309 after 9 ms: Connection refused

% curl -v telnet://10.166.114.208:29306
*   Trying 10.166.114.208:29306...
* Connected to 10.166.114.208 (10.166.114.208) port 29306 (#0)
Warning: Binary output can mess up your terminal. Use "--output -" to tell 
Warning: curl to output it to your terminal anyway, or consider "--output 
Warning: <FILE>" to save to a file.
* Failure writing output to destination
* Closing connection 0

예제에서는 open 안되어 있는 29309 포트로는 실패하고, open 되어 있는 29306 포트로는 연결 성공했다.