728x90

WIN10 ipconfig wsl ip

윈도우 wsl ubuntu 아이피가 바겼을때 확인하고 터널링 실행

package com.gaon.client.main;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gaon.client.thread.FileThread;


public class ServiceMain {

	private static final Logger log = LoggerFactory.getLogger(ServiceMain.class);

	public static void main(String[] args) {
		
		try {
		
			//System.out.println("test");
			//TextReadToDbService service = new TextReadToDbService();
			//service.textReadToDb();
			//System.out.println("end");
			
			
			//파일삭제
			//Thread t = new Thread(new FileThread(), "Thread-01");
			//t.start();
			
			execute("wsl -t Ubuntu 2", 0);
			execute("ipconfig", 1);
			


			
		} catch (Exception e) {
			log.warn(ExceptionUtils.getStackTrace(e));
		}

	}
	
	public static void execute(String cmd, int gb) throws Exception{
		
		Thread.sleep(5000);
		
        Process process = null;
        Runtime runtime = Runtime.getRuntime();
        StringBuffer successOutput = new StringBuffer(); // 성공 스트링 버퍼
        StringBuffer errorOutput = new StringBuffer(); // 오류 스트링 버퍼
        BufferedReader successBufferReader = null; // 성공 버퍼
        BufferedReader errorBufferReader = null; // 오류 버퍼
        String msg = null; // 메시지
 
        List<String> cmdList = new ArrayList<String>();
 
        // 운영체제 구분 (window, window 가 아니면 무조건 linux 로 판단)
        if (System.getProperty("os.name").indexOf("Windows") > -1) {
            cmdList.add("cmd");
            cmdList.add("/c");
        } else {
            cmdList.add("/bin/sh");
            cmdList.add("-c");
        }
        // 명령어 셋팅
        cmdList.add(cmd);
        String[] array = cmdList.toArray(new String[cmdList.size()]);
 
        try {
 
            // 명령어 실행
            process = runtime.exec(array);
 
            // shell 실행이 정상 동작했을 경우
            successBufferReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "EUC-KR"));
 
            while ((msg = successBufferReader.readLine()) != null) {
                successOutput.append(msg + System.getProperty("line.separator"));
            }
 
            // shell 실행시 에러가 발생했을 경우
            errorBufferReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "EUC-KR"));
            while ((msg = errorBufferReader.readLine()) != null) {
                errorOutput.append(msg + System.getProperty("line.separator"));
            }
 
            // 프로세스의 수행이 끝날때까지 대기
            process.waitFor();
 
            // shell 실행이 정상 종료되었을 경우
            if (process.exitValue() == 0) {
            	log.warn("성공");
            	log.warn(successOutput.toString());
            } else {
                // shell 실행이 비정상 종료되었을 경우
            	log.warn("비정상 종료");
            	log.warn(successOutput.toString());
            }
 
            
            if(gb == 1) {
            	settingIp(successOutput.toString());
            	
            }
            
            
            log.warn("errorOutput" + errorOutput.toString());
            
            // shell 실행시 에러가 발생
            //if (CommonUtil.notEmpty(errorOutput.toString())) {
                // shell 실행이 비정상 종료되었을 경우
            //    System.out.println("오류");
            //    System.out.println(successOutput.toString());
           // }
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                process.destroy();
                if (successBufferReader != null) successBufferReader.close();
                if (errorBufferReader != null) errorBufferReader.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

	public static void settingIp(String out) {
		
		BufferedReader reader = null; 
		String ip = "";
		
		try {
			
			reader = new BufferedReader(new StringReader(out));
			
		    String line = null;
	        int idx = 0;
	        int ipIdx = 0;
	        
	        while ((line = reader.readLine()) != null  ) {
	        	++idx;
	        	log.warn(line);
	        	if(line.equals("이더넷 어댑터 vEthernet (WSL):")) {
	        		ipIdx = idx;
	        	}
	        	if(ipIdx != 0 && idx == (ipIdx + 4)) {
	        		log.warn("ip : " + line.replace("   IPv4 주소 . . . . . . . . . : ", ""));
	        		ip = line.replace("   IPv4 주소 . . . . . . . . . : ", "");
	        	}
	        }
	        
	        String cmd = "wsl -d ubuntu -u root autossh -f -M 13000 -N -i /home/ksm/key/oracleCloudOpenssh.ppk ubuntu@ksmcloud.duckdns.org -p 22 -o 'StrictHostKeyChecking=no' -o 'ExitOnForwardFailure=yes' -o 'ServerAliveInterval 30' -o 'ServerAliveCountMax 3' -R 32400:#{ip}:32400"; 
	        cmd = cmd.replace("#{ip}", ip);
	        log.warn("cmd : " + cmd);
	        
	        execute(cmd, 0);
	        
	        
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

        
	}

}
728x90

+ Recent posts