본문 바로가기
OS/Linux

java 에서 원격 ssh 명령어 실행

by CodeDesigner 2021. 9. 27.

[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

 

'OS > Linux' 카테고리의 다른 글

[CentOS7] Shasum 설치  (0) 2022.04.27
CentOS7 wget 설치  (0) 2022.04.27
linux 에서 listen중인 port 확인  (0) 2022.04.26
-bash-4.1$  (0) 2022.04.22
[CentOS7] Spring boot jar 배포  (0) 2022.01.21

댓글