Coverage Report - com.jcabi.ssh.SSH
 
Classes in this File Line Coverage Branch Coverage Complexity
SSH
62%
22/35
0%
0/14
1.333
 
 1  
 /**
 2  
  * Copyright (c) 2014-2015, jcabi.com
 3  
  * All rights reserved.
 4  
  *
 5  
  * Redistribution and use in source and binary forms, with or without
 6  
  * modification, are permitted provided that the following conditions
 7  
  * are met: 1) Redistributions of source code must retain the above
 8  
  * copyright notice, this list of conditions and the following
 9  
  * disclaimer. 2) Redistributions in binary form must reproduce the above
 10  
  * copyright notice, this list of conditions and the following
 11  
  * disclaimer in the documentation and/or other materials provided
 12  
  * with the distribution. 3) Neither the name of the jcabi.com nor
 13  
  * the names of its contributors may be used to endorse or promote
 14  
  * products derived from this software without specific prior written
 15  
  * permission.
 16  
  *
 17  
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 18  
  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 19  
  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 20  
  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 21  
  * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 22  
  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 23  
  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 24  
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 25  
  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 26  
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 27  
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 28  
  * OF THE POSSIBILITY OF SUCH DAMAGE.
 29  
  */
 30  
 package com.jcabi.ssh;
 31  
 
 32  
 import com.jcabi.aspects.RetryOnFailure;
 33  
 import com.jcabi.aspects.Tv;
 34  
 import com.jcabi.log.Logger;
 35  
 import com.jcraft.jsch.JSch;
 36  
 import com.jcraft.jsch.JSchException;
 37  
 import com.jcraft.jsch.Session;
 38  
 import java.io.File;
 39  
 import java.io.IOException;
 40  
 import java.net.InetAddress;
 41  
 import java.net.URL;
 42  
 import java.net.UnknownHostException;
 43  
 import java.util.concurrent.TimeUnit;
 44  
 import lombok.EqualsAndHashCode;
 45  
 import lombok.ToString;
 46  
 import org.apache.commons.io.FileUtils;
 47  
 import org.apache.commons.io.IOUtils;
 48  
 import org.apache.commons.lang3.CharEncoding;
 49  
 
 50  
 /**
 51  
  * Single SSH Channel.
 52  
  *
 53  
  * <p>This class implements {@link Shell} interface. In order to use
 54  
  * it, just make an instance and call
 55  
  * {@link #exec(String,InputStream,OutputStream,OutputStream)} exec()}:
 56  
  *
 57  
  * <pre> String hello = new Shell.Plain(
 58  
  *   new SSH(
 59  
  *     "ssh.example.com", 22,
 60  
  *     "yegor", "-----BEGIN RSA PRIVATE KEY-----..."
 61  
  *   )
 62  
  * ).exec("echo 'Hello, world!'");</pre>
 63  
  *
 64  
  * <p>It is highly recommended to use classes from {@link Shell} interface,
 65  
  * they will simplify operations.</p>
 66  
  *
 67  
  * @author Yegor Bugayenko (yegor@teamed.io)
 68  
  * @version $Id: ab39f22a4b0650e2c706221da5c0bc0ccbe76188 $
 69  
  * @since 1.0
 70  
  * @see <a href="http://www.yegor256.com/2014/09/02/java-ssh-client.html">article by Yegor Bugayenko</a>
 71  
  */
 72  21
 @ToString
 73  0
 @EqualsAndHashCode(of = { "key" }, callSuper = true)
 74  
 @SuppressWarnings("PMD.TooManyMethods")
 75  
 public final class SSH extends AbstractSSHShell {
 76  
 
 77  
     /**
 78  
      * Default SSH port.
 79  
      */
 80  
     public static final int PORT = 22;
 81  
 
 82  
     /**
 83  
      * Private SSH key.
 84  
      */
 85  
     private final transient String key;
 86  
 
 87  
     /**
 88  
      * Constructor.
 89  
      * @param adr IP address
 90  
      * @param user Login
 91  
      * @param priv Private SSH key
 92  
      * @throws IOException If fails
 93  
      * @since 1.4
 94  
      */
 95  
     public SSH(final String adr, final String user, final URL priv)
 96  
         throws IOException {
 97  0
         this(adr, SSH.PORT, user, priv);
 98  0
     }
 99  
 
 100  
     /**
 101  
      * Constructor.
 102  
      * @param adr IP address
 103  
      * @param user Login
 104  
      * @param priv Private SSH key
 105  
      * @throws IOException If fails
 106  
      * @since 1.4
 107  
      */
 108  
     public SSH(final InetAddress adr, final String user, final URL priv)
 109  
         throws IOException {
 110  0
         this(adr, SSH.PORT, user, priv);
 111  0
     }
 112  
 
 113  
     /**
 114  
      * Constructor.
 115  
      * @param adr IP address
 116  
      * @param user Login
 117  
      * @param priv Private SSH key
 118  
      * @throws UnknownHostException If fails
 119  
      * @since 1.4
 120  
      */
 121  
     public SSH(final String adr, final String user, final String priv)
 122  
         throws UnknownHostException {
 123  0
         this(adr, SSH.PORT, user, priv);
 124  0
     }
 125  
 
 126  
     /**
 127  
      * Constructor.
 128  
      * @param adr IP address
 129  
      * @param user Login
 130  
      * @param priv Private SSH key
 131  
      * @throws UnknownHostException If fails
 132  
      * @since 1.4
 133  
      */
 134  
     public SSH(final InetAddress adr, final String user, final String priv)
 135  
         throws UnknownHostException {
 136  0
         this(adr.getCanonicalHostName(), SSH.PORT, user, priv);
 137  0
     }
 138  
 
 139  
     /**
 140  
      * Constructor.
 141  
      * @param adr IP address
 142  
      * @param prt Port of server
 143  
      * @param user Login
 144  
      * @param priv Private SSH key
 145  
      * @throws IOException If fails
 146  
      * @checkstyle ParameterNumberCheck (6 lines)
 147  
      * @since 1.4
 148  
      */
 149  
     public SSH(final String adr, final int prt,
 150  
         final String user, final URL priv) throws IOException {
 151  1
         this(adr, prt, user, IOUtils.toString(priv));
 152  1
     }
 153  
 
 154  
     /**
 155  
      * Constructor.
 156  
      * @param adr IP address
 157  
      * @param prt Port of server
 158  
      * @param user Login
 159  
      * @param priv Private SSH key
 160  
      * @throws IOException If fails
 161  
      * @checkstyle ParameterNumberCheck (6 lines)
 162  
      * @since 1.4
 163  
      */
 164  
     public SSH(final InetAddress adr, final int prt,
 165  
         final String user, final URL priv) throws IOException {
 166  0
         this(adr.getCanonicalHostName(), prt, user, IOUtils.toString(priv));
 167  0
     }
 168  
 
 169  
     /**
 170  
      * Constructor.
 171  
      * @param adr IP address
 172  
      * @param prt Port of server
 173  
      * @param user Login
 174  
      * @param priv Private SSH key
 175  
      * @throws UnknownHostException If fails
 176  
      * @checkstyle ParameterNumberCheck (6 lines)
 177  
      */
 178  
     public SSH(final String adr, final int prt,
 179  
         final String user, final String priv) throws UnknownHostException {
 180  3
         super(adr, prt, user);
 181  3
         this.key = priv;
 182  3
     }
 183  
 
 184  
     /**
 185  
      * Escape SSH argument.
 186  
      * @param arg Argument to escape
 187  
      * @return Escaped
 188  
      */
 189  
     public static String escape(final String arg) {
 190  1
         return String.format("'%s'", arg.replace("'", "'\\''"));
 191  
     }
 192  
 
 193  
     // @checkstyle ProtectedMethodInFinalClassCheck (10 lines)
 194  
     @Override
 195  
     @RetryOnFailure(
 196  
         attempts = Tv.SEVEN,
 197  
         delay = 1,
 198  
         unit = TimeUnit.MINUTES,
 199  
         verbose = false,
 200  
         randomize = true,
 201  
         types = IOException.class
 202  
     )
 203  
     protected Session session() throws IOException {
 204  
         try {
 205  3
             JSch.setConfig("StrictHostKeyChecking", "no");
 206  3
             JSch.setLogger(new JschLogger());
 207  3
             final JSch jsch = new JSch();
 208  3
             final File file = File.createTempFile("jcabi-ssh", ".key");
 209  3
             FileUtils.forceDeleteOnExit(file);
 210  3
             FileUtils.write(
 211  
                 file,
 212  
                 this.key.replaceAll("\r", "")
 213  
                     .replaceAll("\n\\s+|\n{2,}", "\n")
 214  
                     .trim(),
 215  
                 CharEncoding.UTF_8
 216  
             );
 217  3
             jsch.setHostKeyRepository(new EasyRepo());
 218  3
             jsch.addIdentity(file.getAbsolutePath());
 219  3
             Logger.debug(
 220  
                 this,
 221  
                 "Opening SSH session to %s@%s:%s (%d bytes in RSA key)...",
 222  
                 this.getLogin(), this.getAddr(), this.getPort(),
 223  
                 file.length()
 224  
             );
 225  3
             final Session session = jsch.getSession(
 226  
                 this.getLogin(), this.getAddr(), this.getPort()
 227  
             );
 228  3
             session.setServerAliveInterval(
 229  
                 (int) TimeUnit.SECONDS.toMillis(Tv.TEN)
 230  
             );
 231  3
             session.setServerAliveCountMax(Tv.MILLION);
 232  3
             session.connect();
 233  3
             FileUtils.deleteQuietly(file);
 234  3
             return session;
 235  0
         } catch (final JSchException ex) {
 236  0
             throw new IOException(ex);
 237  
         }
 238  
     }
 239  
 
 240  
 }