/** * SSH 29.03.2012 * * @author Philipp Haussleiter * */ package de.javastream.javassh; import de.javastream.javassh.parser.BooleanPP; import de.javastream.javassh.parser.ProcessParser; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author philipp */ public class SSH { protected Runtime r; private String prefix = ""; private int status = 255; private final static Logger LOG = Logger.getLogger(SSH.class.getName()); private Host host; public SSH(final Host host) { if (Utils.isWindows()) { throw new UnsupportedOperationException("Windows is currently not supported!"); } this.host = host; this.prefix = " ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no " + host.user + "@" + host.url + " -p" + host.port; r = Runtime.getRuntime(); } public void runCommand(final String command, final ProcessParser pp) { if (host == null) { LOG.log(Level.SEVERE, "Host needs to be set!"); } try { LOG.log(Level.FINE, "running: {0} {1}", new Object[]{this.prefix, command}); Process p = r.exec(this.prefix + " " + command); if (!needPassword()) { runProcess(p, pp); } else { status = 255; LOG.log(Level.SEVERE, "{0} needs a password. Please add the public ssh-key to {1}", new Object[]{host, host}); } } catch (IOException ex) { LOG.log(Level.SEVERE, ex.getLocalizedMessage()); } } /** * Checks if a ssh-connections needs a password. thx to * http://freeunixtips.com/2009/03/ssh-pw-prompt/ */ public boolean needPassword() throws IOException { BooleanPP bp = new BooleanPP(); LOG.log(Level.FINE, "check: {0} -qo PasswordAuthentication=no echo 0 || echo 1", this.prefix); Process p = r.exec(this.prefix + " -qo PasswordAuthentication=no echo 0 || echo 1"); runProcess(p, bp); return bp.getResult(); } protected void runProcess(Process p, ProcessParser pp) throws IOException { InputStream in = p.getInputStream(); BufferedInputStream buf = new BufferedInputStream(in); InputStreamReader inread = new InputStreamReader(buf); BufferedReader bufferedreader = new BufferedReader(inread); pp.parse(bufferedreader); try { status = p.waitFor(); LOG.log(Level.FINE, "exit value = {0}", status); } catch (InterruptedException e) { LOG.log(Level.SEVERE, e.getLocalizedMessage()); } finally { // Close the InputStream bufferedreader.close(); inread.close(); buf.close(); in.close(); } } public int getStatus() { return status; } }