2011년 8월 2일 화요일

J2SSH를 이용한 원격 서버 tail

j2ssh-core-0.2.9.jar 필요함



package org.javaya.test.j2ssh;

import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.session.SessionChannelClient;

/**
 * j2ssh 테스트 <br />
 * j2ssh-core-0.2.9.jar 필요 <br />
 * http://sourceforge.net/projects/sshtools <br />
 * PasswordAuthentication 방식으로 인증한다. 서버에서 이 방식을 지원해줘야 인증가능.<br />
 * OpenSSH의 경우 아래와 같은이 PasswordAuth 방식의 인증을 허용해줘야 한다. (sshd_config 파일 참고) <br />
 * #PasswordAuthentication no
 */
public class J2SSHTail {
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) {
String hostname = "127.0.0.1";
String username = null;
String password = null;
int port = 22;
String filename = null;

if (args == null || args.length != 4) {
System.out.println("Usage> SSHTest <hostname> <port> <username> <remote filename>");
System.exit(-1);
}

hostname = args[0];
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException e2) {
e2.printStackTrace();
System.exit(-1);
}
username = args[2];
filename = args[3];


System.out.print("password: ");
try {
password = reader.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}

SshClient ssh = new SshClient();
SessionChannelClient session = null;
try {
ssh.connect(hostname, port);

PasswordAuthenticationClient auth = new PasswordAuthenticationClient();
auth.setUsername(username);
auth.setPassword(password);

List authList = ssh.getAvailableAuthMethods(username);
for (int i = 0; authList != null && i < authList.size(); i++) {
System.out.println(authList.get(i));
}

int result = ssh.authenticate(auth);

if (result == AuthenticationProtocolState.FAILED)
System.out.println("The authentication failed");

if (result == AuthenticationProtocolState.PARTIAL)
System.out.println("The authentication succeeded but another" + "authentication is required");

if (result == AuthenticationProtocolState.COMPLETE)
System.out.println("The authentication is complete");

session = ssh.openSessionChannel();

/** Writing to the session OutputStream */
String command = "tail -f " + filename;
session.executeCommand(command);

/**
* Reading from the session InputStream
*/
InputStream in = session.getInputStream();
byte buffer[] = new byte[255];
int read;
while ((read = in.read(buffer)) > 0) {
String message = new String(buffer, 0, read);
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try { session.close(); } catch (Exception e) {}
try { ssh.disconnect(); } catch (Exception e) {}
}
}

}

댓글 없음:

댓글 쓰기