반응형
자바코드에서 NTP 서버 정보를 전달하는 방법에 대해 알아보겠습니다.
윈도우, 우분투 모두 Runtime을 이용하여 구현합니다. 다만 OS마다 명령어나 설정방법이 다르기 때문에 아래 코드를 참고해주세요.
윈도우
private void addNTPServer(String serverAddress) throws IOException {
try {
String command = "w32tm.exe /config /manualpeerlist:" + serverAddress + " /syncfromflags:manual /reliable:yes /update";
Process process = Runtime.getRuntime().exec("cmd /c " + command);
process.waitFor();
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
process.destroy();
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
private void clearNTPServers() throws IOException {
try {
String command = "w32tm.exe /config /update /manualpeerlist:\"\"";
Process process = Runtime.getRuntime().exec("cmd /c " + command);
process.waitFor();
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
process.destroy();
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
private void restartNTPService() throws IOException {
try {
Process process = Runtime.getRuntime().exec("cmd /c net stop w32time && net start w32time");
process.waitFor();
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
process.destroy();
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
우분투
private void editNtpConf(String newNtpServer) throws IOException {
FileReader fileReader = new FileReader("/etc/ntp.conf");
BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fileWriter = new FileWriter("/etc/ntp.conf.tmp");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("server ")) {
continue;
}
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedWriter.write("server " + newNtpServer);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
// 기존 파일 삭제
boolean result = new File("/etc/ntp.conf").delete();
if (result) {
result = new File("/etc/ntp.conf.tmp").renameTo(new File("/etc/ntp.conf"));
}
}
private void restartNTPService() throws IOException {
try {
Process process = Runtime.getRuntime().exec("sudo service ntp restart");
process.waitFor();
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
process.destroy();
} catch (InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
반응형
'Spring' 카테고리의 다른 글
[Spring] mapStruct에서 LocalDateTime을 epoch Milli로 변경하는 방법 (0) | 2023.03.24 |
---|---|
[Spring] 조회메서드에 @Transactional(readOnly=true)를 사용해야하는 이유 (0) | 2023.03.23 |
[Spring] Springdoc Swagger 그룹, 정렬, 카테고리 접기 (0) | 2023.03.21 |
[Spring] Springdoc swagger에서 글로벌 header를 설정하는 방법 (0) | 2023.03.10 |
[Spring] Springdoc을 이용한 Swagger 적용 (0) | 2023.03.02 |
댓글