Java SSH Library: Apache sshd Library and Jsch library (Java Secure Channel)

Source: Internet
Author: User
Tags ssh server

1.Apache sshd

Apache sshd is a 100% pure Java Library of SSH protocol that supports both client and server. The SSHD library is based on the Apache Mina project (a scalable, high-performance asynchronous IO Library). Official website: http://mina.apache.org/sshd-project/documentation.html

Client Sample code:

     Public voidClenttest ()throwsioexception {String cmd= "Ifconfig"; Sshclient Client=sshclient.setupdefaultclient ();        Client.start (); Clientsession Session=client.connect ("bellring", "10.2.48.179", 22). await (). GetSession (); Session.addpasswordidentity ("Bellring"); if(!Session.auth (). await (). Issuccess ()) System.out.println ("Auth Failed"); Channelexec EC=Session.createexecchannel (CMD);        Ec.setout (System.out);        Ec.open (); Ec.waitfor (clientchannel.closed,0);                Ec.close ();    Client.stop (); }
     Public voidSshdclientsftptest ()throwsIOException, interruptedexception {Path src=paths.get ("Src_sshd.txt");        Files.deleteifexists (SRC);        Files.createfile (SRC); Files.write (SRC,"Adsfa\nsdfs". GetBytes ()); Sshclient Client=sshclient.setupdefaultclient ();        Client.start (); Clientsession Session=client.connect ("bellring", "10.2.48.179", 22). await (). GetSession (); Session.addpasswordidentity ("Bellring"); if(!Session.auth (). await (). Issuccess ()) System.out.println ("Auth Failed"); Sftpclient sftp=session.createsftpclient ();  for(Direntry De:sftp.readDir ("."))) System.out.println (De.filename+" "+De.attributes.type); OutputStream OS=sftp.write ("Test/dst_sshd.txt");        Files.copy (src, OS);                Os.close (); //sftp.remove ("Delete_file.txt");InputStream is=sftp.read ("Test/dst_sshd.txt"); Path DST=paths.get ("Dst1_sshd.txt");        Files.deleteifexists (DST);        Files.copy (is, DST);                Is.close ();        Sftp.close ();    Client.stop (); }

Server-side Sample code:

     Public voidServertest ()throwsIOException, interruptedexception {sshserver sshd=Sshserver.setupdefaultserver (); Sshd.setport (22); //*give host key Generator a path, when sshd server restart, the same key would be load and used to authenticate the Serv ERSshd.setkeypairprovider (NewSimplegeneratorhostkeyprovider (Paths.get ("Hostkey.ser"))); Sshd.setpasswordauthenticator (NewPasswordauthenticator () {@Override Public BooleanAuthenticate (string username, string password, serversession session) {SYSTEM.OUT.PRINTLN ("Authen:user=" +username+ "password=" +password); if("Bellring". Equals (username) && "123456". Equals (password))return true; return false;                }}); //Use file ~/.ssh/authorized_keysSshd.setpublickeyauthenticator (NewDefaultauthorizedkeysauthenticator (false)); //* Commandfactory can userd in addition to the Shellfactory,//* It can also be used instead of the shellfactory. //* The commandfactory is used when direct commands was sent to the SSH server,//* As this was when running SSH localhost shutdown or scp xxxScpcommandfactory scpcmdfactory=Newscpcommandfactory (); Scpcmdfactory.setdelegatecommandfactory (Newcommandfactory () { Publiccommand CreateCommand (String command) {System.out.println ("Command = \" "+ Command +" \ ""); return NewProcessshellfactory ("cmd/c" +command). Split ("") . Create ();        }        });                Sshd.setcommandfactory (scpcmdfactory); Sshd.start ();    }

2.JSch (Java Secure Channel)

Jsch is also a pure Java implementation of SSH2. Dependent on the JavaTM Cryptography Extension (JCE). Jsch supports clients.

Official website: http://www.jcraft.com/jsch/

Example: http://www.jcraft.com/jsch/examples/

Example of client remote command execution:

     Public voidTestjschclient ()throwsjschexception, interruptedexception {Jsch Jsch=NewJsch (); Session Session=jsch.getsession ("bellring", "10.2.48.179", 22); Session.setconfig ("Stricthostkeychecking", "no"); //Set Auth info interactively//Session.setuserinfo (New UserInfo () {...});Session.setpassword ("Bellring");                Session.connect (); Com.jcraft.jsch.ChannelExec EC= (com.jcraft.jsch.ChannelExec) session.openchannel ("Exec"); Ec.setcommand ("Ifconfig"); Ec.setinputstream (NULL);        Ec.seterrstream (System.err);        Ec.setoutputstream (System.out);                Ec.connect ();  while(!ec.isclosed ()) Thread.Sleep (500);        Ec.disconnect ();    Session.disconnect (); }

SFTP File Operation Example

     Public voidTestjschsftp ()throwsjschexception, Interruptedexception, Sftpexception, IOException {Jsch Jsch=NewJsch (); Session Session=jsch.getsession ("bellring", "10.2.48.179", 22); Session.setconfig ("Stricthostkeychecking", "no"); //Set Auth info interactively//Session.setuserinfo (New UserInfo () {...});Session.setpassword ("Bellring");                Session.connect (); Com.jcraft.jsch.ChannelSftp Sftpchannel= (com.jcraft.jsch.ChannelSftp) session.openchannel ("Sftp");                Sftpchannel.connect (); Path src=paths.get ("Src.txt");        Files.deleteifexists (SRC);        Files.createfile (SRC); Files.write (SRC,"Adsfasdfs". GetBytes ()); Vector Vector=sftpchannel.ls (".");  for(Object obj:vector) System.out.println (obj); SFTPCHANNEL.CD ("Test"); Sftpchannel.put ("Src.txt", "Dst.txt"); Sftpchannel.get ("Dst.txt", "Dst1.txt"); SFTPCHANNEL.RM ("Dst.txt");        Sftpchannel.disconnect ();        Session.disconnect (); System.out.println ("Done"); }

Java SSH Library: Apache sshd Library and Jsch library (Java Secure Channel)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.