1 package de.hacksaar.javatuer;
3 import com.jcraft.jsch.JSchException;
4 import com.jcraft.jsch.UserInfo;
6 import java.io.IOException;
7 import java.io.InputStreamReader;
8 import java.io.OutputStreamWriter;
10 public class TyshellClient {
11 private static final String TAG = "TyshellClient";
12 public static final char END_OF_COMMAND = '\n';
13 private final String hostname;
14 private final int port;
15 private final TuerLogging log;
16 private SshClient client;
17 private InputStreamReader inputStream;
18 private OutputStreamWriter outputStream;
20 public TyshellClient(String hostname, int port) {
21 this(hostname, port, new DummyLogging());
24 public TyshellClient(String hostname, int port, TuerLogging log) {
26 this.hostname = hostname;
30 public void connect(String username, String password) {
32 client = new SshClient(hostname, username, port, log);
33 client.login(password);
34 inputStream = new InputStreamReader(client.getInputStream());
35 outputStream = new OutputStreamWriter(client.getOutputStream());
36 } catch (JSchException | IOException e) {
37 log.exception(TAG, e);
41 public void connect(String username, String keyFile, String passphrase) {
43 client = new SshClient(hostname, username, port, log);
44 client.addPrivateKey(keyFile, passphrase);
46 inputStream = new InputStreamReader(client.getInputStream());
47 outputStream = new OutputStreamWriter(client.getOutputStream());
48 } catch (JSchException | IOException e) {
49 log.exception(TAG, e);
53 public void connect(String username, String keyFile, UserInfo interactiveLogin) {
55 client = new SshClient(hostname, username, port, log);
56 client.addPrivateKey(keyFile);
57 client.login(interactiveLogin);
58 inputStream = new InputStreamReader(client.getInputStream());
59 outputStream = new OutputStreamWriter(client.getOutputStream());
60 } catch (JSchException | IOException e) {
61 log.exception(TAG, e);
65 public void disconnect() {
69 } catch (IOException e) {
70 log.exception(TAG, e);
75 boolean isConnected() {
76 return (client.isConnected() && inputStream != null && outputStream != null);
79 public InputStreamReader getInputStream() {
83 public void sendCommand(String command) {
86 assert outputStream != null;
87 log.debug(TAG, "Sending: " + command);
88 outputStream.write((command + END_OF_COMMAND).toCharArray());
90 } catch (IOException e) {
91 log.exception(TAG, e);