1 package de.hacksaar.javatuer;
3 import com.jcraft.jsch.*;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
9 public class SshClient {
10 private static final String TAG = "SshClient";
11 private final String host;
12 private final String username;
13 private final int port;
14 private final JSch jSch;
15 private final TuerLogging log;
16 private Session session;
17 private Channel channel;
19 public SshClient(String host, String username, int port, TuerLogging log) {
21 this.username = username;
28 public void addPrivateKey(String keyFilePath) throws JSchException {
29 jSch.addIdentity(keyFilePath);
32 public void addPrivateKey(String keyFilePath, String passphrase) throws JSchException {
33 jSch.addIdentity(keyFilePath, passphrase);
36 public void disconnect() {
43 public String getHost() {
47 public InputStream getInputStream() throws IOException {
48 if (channel == null) {
51 return channel.getInputStream();
54 public OutputStream getOutputStream() throws IOException {
55 if (channel == null) {
58 return channel.getOutputStream();
61 public int getPort() {
65 public String getUsername() {
69 public boolean isConnected() {
70 return channel != null && channel.isConnected() && session != null && session.isConnected();
73 public void login(final String password) throws JSchException {
74 login(new UserInfo() {
77 public String getPassphrase() {
82 public String getPassword() {
87 public boolean promptPassphrase(String s) {
92 public boolean promptPassword(String s) {
97 public boolean promptYesNo(String s) {
102 public void showMessage(String s) {
108 public void login() throws JSchException {
109 login(new UserInfo() {
112 public String getPassphrase() {
117 public String getPassword() {
122 public boolean promptPassphrase(String s) {
127 public boolean promptPassword(String s) {
132 public boolean promptYesNo(String s) {
137 public void showMessage(String s) {
143 public void login(UserInfo userInfo) throws JSchException {
144 log.debug(TAG, "Creating session");
145 if (session == null) {
146 session = jSch.getSession(username, host, port);
148 if (!session.isConnected()) {
149 session.setUserInfo(userInfo);
150 log.debug(TAG, "Connecting");
152 log.debug(TAG, "Opening channel");
153 channel = session.openChannel("shell");