java 에서 원격 ssh 명령어 실행

java 에서 원격 ssh 명령어 실행

[Linux Server 모니터링을 위한 첫 단계] java에서 명령어 날리기

JSch 라이브러리를 사용해 java 에서 특정 linux server에 명령어 날리는 코드

String username = "****"; // ssh login ID String host = "***.***.***.***"; // ssh ip int port = 22; String password = "****"; // ssh login password System.out.println("==> Connecting to " + host); Session session = null; Channel channel = null; // Session 객체 생성 try { // JSch 객체 생성 JSch jsch = new JSch(); session = jsch.getSession(username, host, port); // 패스워드 설정 session.setPassword(password); // 세션과 관련된 정보 설정 session.setConfig("StrictHostKeyChecking", "no"); // 접속 session.connect(); // sftp 채널 channel = session.openChannel("exec"); // 채널을 SSH용 채널 객체로 캐스팅 ChannelExec channelExec = (ChannelExec) channel; System.out.println("==> Connected to " + host); // 명령어 날리는 부분 channelExec.setCommand("touch /Test/ss_test/jschTest.txt"); channelExec.connect(); System.out.println("==> Connected to " + host); } catch (JSchException e) { e.printStackTrace(); } finally { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } }

=> 실행 결과 jschTest.txt 가 정상적으로 생성된 것을 확인할 수 있다.

# ls deleteTrashDoc.sh hello.sh jschTest.txt test.sh test_restart.log

from http://cdssp.tistory.com/3 by ccl(A) rewrite - 2021-09-27 09:02:18