{"id":69410,"date":"2020-09-07T06:06:23","date_gmt":"2020-09-07T06:06:23","guid":{"rendered":"https:\/\/www.baeldung.com\/?p=86717"},"modified":"2020-09-07T06:06:23","modified_gmt":"2020-09-07T06:06:23","slug":"ssh-connection-with-java","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2020\/09\/07\/ssh-connection-with-java\/","title":{"rendered":"SSH Connection With Java"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<h2 data-id=\"introduction\">1. Introduction<\/h2>\n<div class=\"bd-anchor\" id=\"introduction\"><\/div>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/cs\/ssh-intro\">SSH<\/a>, also known as Secure Shell or Secure Socket Shell, is a network protocol that allows <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/linux\/secure-shell-ssh\">one computer to securely connect to another computer<\/a> over an unsecured network. In this tutorial, we&#8217;ll show how to <strong>establish a connection to a remote SSH server with Java using the JSch and Apache MINA SSHD libraries<\/strong>.<\/p>\n<p>In our examples, we&#8217;ll first open the SSH connection, then execute one command, read the output and write it to the console, and, finally, close the SSH connection. We&#8217;ll keep the sample code as simple as possible.<\/p>\n<h2 data-id=\"jsch\">2. JSch<\/h2>\n<div class=\"bd-anchor\" id=\"jsch\"><\/div>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~www.jcraft.com\/jsch\/\">JSch<\/a> is the Java implementation of SSH2 that allows us to connect to an SSH server and use port forwarding, X11 forwarding, and file transfer. Also, it is licensed under the BSD style license and provides us with an easy way to establish an SSH connection with Java.<\/p>\n<p>First, let&#8217;s add the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/search.maven.org\/search?q=g:com.jcraft%20AND%20a:jsch\">JSch Maven dependency<\/a> to our <em>pom.xml<\/em> file:<\/p>\n<pre><code class=\"language-xml\">&lt;dependency&gt;\r\n    &lt;groupId&gt;com.jcraft&lt;\/groupId&gt;\r\n    &lt;artifactId&gt;jsch&lt;\/artifactId&gt;\r\n    &lt;version&gt;0.1.55&lt;\/version&gt;\r\n&lt;\/dependency&gt;<\/code><\/pre>\n<h3 data-id=\"1-implementation\">2.1. Implementation<\/h3>\n<div class=\"bd-anchor\" id=\"1-implementation\"><\/div>\n<p><strong>To establish an SSH connection using JSch, we need a username, password, host URL, and SSH port<\/strong>. The default SSH port is 22, but it could happen that we&#8217;ll configure the server to use other port for SSH connections:<\/p>\n<pre><code class=\"language-java\">public static void listFolderStructure(String username, String password, \r\n  String host, int port, String command) throws Exception {\r\n    \r\n    Session session = null;\r\n    ChannelExec channel = null;\r\n    \r\n    try {\r\n        session = new JSch().getSession(username, host, port);\r\n        session.setPassword(password);\r\n        session.setConfig(\"StrictHostKeyChecking\", \"no\");\r\n        session.connect();\r\n        \r\n        channel = (ChannelExec) session.openChannel(\"exec\");\r\n        channel.setCommand(command);\r\n        ByteArrayOutputStream responseStream = new ByteArrayOutputStream();\r\n        channel.setOutputStream(responseStream);\r\n        channel.connect();\r\n        \r\n        while (channel.isConnected()) {\r\n            Thread.sleep(100);\r\n        }\r\n        \r\n        String responseString = new String(responseStream.toByteArray());\r\n        System.out.println(responseString);\r\n    } finally {\r\n        if (session != null) {\r\n            session.disconnect();\r\n        }\r\n        if (channel != null) {\r\n            channel.disconnect();\r\n        }\r\n    }\r\n}<\/code><\/pre>\n<p>As we can see in the code, we first create a client session and configure it for connection to our SSH server. Then, we create a client channel used to communicate with the SSH server where we provide a channel type &#8211; in this case, <em>exec,<\/em> which means that we&#8217;ll be passing shell commands to the server.<\/p>\n<p>Also, we should set the output stream for our channel where the server response will be written. After we establish the connection using the\u00a0<em>channel.connect()<\/em> method, the command is passed, and the received response is written on the console.<\/p>\n<p>Let&#8217;s see <strong>how to use different configuration parameters that JSch offers<\/strong>:<\/p>\n<ul>\n<li><em>StrictHostKeyChecking<\/em> &#8211; it indicates whether the application will check if the host public key could be found among known hosts. Also, available parameter values are <em>ask<\/em>, <em>yes,<\/em> and <em>no<\/em>, where <em>ask<\/em> is the default. If we set this property to <em>yes<\/em>, JSch will never automatically add the host key to the <em>known_hosts<\/em> file, and it&#8217;ll refuse to connect to hosts whose host key has changed. This forces the user to manually add all new hosts. If we set it to\u00a0<em>no<\/em>, JSch will automatically add a new host key to the list of known hosts<\/li>\n<li><em>compression.s2c<\/em> &#8211; specifies whether to use compression for the data stream from the server to our client application. Available values are <em>zlib<\/em> and <em>none<\/em> where the second is the default<\/li>\n<li><em>compression.c2s<\/em> &#8211; specifies whether to use compression for the data stream in the client-server direction. Available values are <em>zlib<\/em> and <em>none<\/em> where the second is the default<\/li>\n<\/ul>\n<p>It&#8217;s important to <strong>close the session and the SFTP channel after the communication with the server is over to avoid memory leaks<\/strong>.<\/p>\n<h2 data-id=\"apache-mina-sshd\">3. Apache MINA SSHD<\/h2>\n<div class=\"bd-anchor\" id=\"apache-mina-sshd\"><\/div>\n<p><a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/mina.apache.org\/sshd-project\/\">Apache MINA SSHD<\/a> provides SSH support for Java-based applications. This library is based on Apache MINA, a scalable and high-performance asynchronous IO library.<\/p>\n<p>Let&#8217;s add the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/search.maven.org\/search?q=a:apache-sshd\">Apache Mina SSHD Maven dependency<\/a>:<\/p>\n<pre><code class=\"language-xml\">&lt;dependency&gt;\r\n    &lt;groupId&gt;org.apache.sshd&lt;\/groupId&gt;\r\n    &lt;artifactId&gt;sshd-core&lt;\/artifactId&gt;\r\n    &lt;version&gt;2.5.1&lt;\/version&gt;\r\n&lt;\/dependency&gt;<\/code><\/pre>\n<h3 data-id=\"1-implementation-1\">3.1. Implementation<\/h3>\n<div class=\"bd-anchor\" id=\"1-implementation-1\"><\/div>\n<p>Let&#8217;s see the code sample of connecting to the SSH server using Apache MINA SSHD:<\/p>\n<pre><code class=\"language-java\">public static void listFolderStructure(String username, String password, \r\n  String host, int port, long defaultTimeoutSeconds, String command) throws IOException {\r\n    \r\n    SshClient client = SshClient.setUpDefaultClient();\r\n    client.start();\r\n    \r\n    try (ClientSession session = client.connect(username, host, port)\r\n      .verify(defaultTimeoutSeconds, TimeUnit.SECONDS).getSession()) {\r\n        session.addPasswordIdentity(password);\r\n        session.auth().verify(defaultTimeoutSeconds, TimeUnit.SECONDS);\r\n        \r\n        try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream(); \r\n          ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {\r\n            channel.setOut(responseStream);\r\n            try {\r\n                channel.open().verify(defaultTimeoutSeconds, TimeUnit.SECONDS);\r\n                try (OutputStream pipedIn = channel.getInvertedIn()) {\r\n                    pipedIn.write(command.getBytes());\r\n                    pipedIn.flush();\r\n                }\r\n            \r\n                channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), \r\n                TimeUnit.SECONDS.toMillis(defaultTimeoutSeconds));\r\n                String responseString = new String(responseStream.toByteArray());\r\n                System.out.println(responseString);\r\n            } finally {\r\n                channel.close(false);\r\n            }\r\n        }\r\n    } finally {\r\n        client.stop();\r\n    }\r\n}<\/code><\/pre>\n<p>When working with the Apache MINA SSHD, we have a pretty similar sequence of events as with JSch. First, we establish a connection to an SSH server using the <em>SshClient<\/em> class instance. If we initialize it with <em>SshClient.setupDefaultClient(),<\/em> we&#8217;ll be able to work with the instance that has a default configuration suitable for most use cases. This includes ciphers, compression, MACs, key exchanges, and signatures.<\/p>\n<p>After that, we&#8217;ll create <em>ClientChannel<\/em> and attach the <em>ByteArrayOutputStream<\/em> to it, so that we&#8217;ll use it as a response stream. As we can see, SSHD requires defined timeouts for every operation. It also allows us to define how long it will wait for server response after the command is passed by using <em>Channel.waitFor()<\/em> method.<\/p>\n<p>It&#8217;s important to notice that<strong> SSHD will write complete console output into the response stream. JSch will do it only with the command execution result.<\/strong><\/p>\n<p>Complete documentation on Apache Mina SSHD is available on the <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/apache\/mina-sshd\/tree\/master\/docs\">project&#8217;s official GitHub repository<\/a>.<\/p>\n<h2 data-id=\"conclusion\">4. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>This article illustrated how to establish an SSH connection with Java using two of the available Java libraries &#8211; JSch and Apache Mina SSHD. We also showed how to pass the command to the remote server and get the execution result. Also, complete code samples are available <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/libraries-security\">over on GitHub<\/a>.<\/p>\n<p>The post <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-ssh-connection\/\" >SSH Connection With Java<\/a> first appeared on <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/\" >Baeldung<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/635165251\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/635165251\/baeldung,\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-ssh-connection#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-ssh-connection\/feed\/\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Learn how to establish an SSH connection with Java using two of the available Java libraries &#8211; JSch and Apache Mina SSHD.<\/p>\n<p>The post <a rel=\"NOFOLLOW noopener noreferrer\" href=\"https:\/\/feeds.feedblitz.com\/~\/635165251\/0\/baeldung~SSH-Connection-With-Java\/\" target=\"_blank\">SSH Connection With Java<\/a> first appeared on <a rel=\"NOFOLLOW noopener noreferrer\" href=\"https:\/\/www.baeldung.com\/\" target=\"_blank\">Baeldung<\/a>.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>&nbsp;<a title=\"Share on Google+\" href=\"https:\/\/feeds.feedblitz.com\/_\/30\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/googleplus20.png\"><\/a>&nbsp;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/635165251\/baeldung,\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>&nbsp;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>&nbsp;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>&nbsp;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/635165251\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>&nbsp;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-ssh-connection#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&nbsp;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-ssh-connection\/feed\/\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&nbsp;<\/div>\n<\/div>","protected":false},"author":214,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"SSH Connection With Java - ITTeacherITFreelance.hk","description":"Learn how to establish an SSH connection with Java using two of the available Java libraries - JSch and Apache Mina SSHD. The post SSH Connection With Java firs"},"footnotes":""},"categories":[6],"tags":[],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/69410"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/214"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=69410"}],"version-history":[{"count":7,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/69410\/revisions"}],"predecessor-version":[{"id":77032,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/69410\/revisions\/77032"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=69410"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=69410"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=69410"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}