[JAVA,LINUX] JAVA 이용해서 IP PORT 오픈여부 체크하는 SH 파일 만들기

2024. 3. 15. 10:18SERVER/Linux

 

서버가 여러대 일때 각 방화벽 IP PORT 오픈 여부를 체크해서 관리할 필요가 있어서 JAVA 사용해 jar 파일을 만들고 이를 이용해 리눅스에서 sh 파일을 만들어서 작업하였다.

 

SocketClient

 

import java.io.IOEXception;

public class SocketClient {
	public static void main(String[] args) throws IOException {
    	Socket client = null;
        SocketAddress socketAddress = null;
        
        String ip = null;
        String str_port = null;
        
        try {
        	if(args.length > 0) {
            	ip = args[0];
                str_port = args[1];
                
                cleint = new Socket();
                
                int port = Integer.parseInt(args[1]);
                
                socketAddress = new InetSocketAddress(args[0],port);
                
                client.connect(socketAddress, 1000);
                
                if(client.isConnected())
                	System.out.println(ip+":"+str_port+" "+"===> connected");
                    
                
            } catch (Exception e) {
              System.out.println(ip+":"+str_port+" " + "===> failed");
            } finally {
              client.close();
            }
        
        }
    
    }



}

 

 

#!/bin/bash


# IP와 포트를 담은 배열

IpChkPortLst="127.0.0.1 8000
172.0.0.1 8001
172.0.0.1 8002"

IFS=$'\n' read -r -d '' -a IpChkPortArr <<< "$IpChkPortLst"

#로그 파일 초기화
> chkIp.log

#배열 크기에 따라 반복

for ipPort in "${IpChkPortArr[@]}";do

	#배열 요소를 공백을 기준으로 분리하여 변수에 할당
    tip=$(echo "$ipPort" | awk '{print $1}')
    tPort=$(echo "$ipPort" | awk '{print $2}')
    
    echo "IP AND PORT: $ipPort"
    
    java SocketClient "$tip" "$tPort" >> chkIp.log 2>&1
 done

 

같은 위치에 넣고 위의 sh 파일을 실행시키면

chkIp.log 에 체크된 내용이 출력되는걸 확인할 수 있다.

반응형