SFTP Trust Public key configuration and Jsch Library

Source: Internet
Author: User

1. SFTP Credit Public key configuration
1.1 Client-generated key pair

Take the DSA Example:

Ssh-keygen–t DSA

After the command is executed, ID_DSA and id_dsa.pub two files are generated under the home/user name/.ssh directory

1.2 will id_dsa.pub the public key file is uploaded to the server home/ User name /.ssh directory under

SCP id_dsa.pub username @ server-side ip:/home/user name/.ssh

You also need to enter a password

1.3 Adding a trusted public key to the server

Log on to the server, enter the/home/user name/.ssh directory, and add the contents of the Id_dsa.pub file that you just copied to the Authorized_keys file

Cat Id_dsa.pub >> Authorized_keys

1.4 Service side modified separately Authorized_key files and . SSH the permissions for - and the the

chmod Authorized_keys

chmod. SSH

1.5 Testing

Execute on client:

sftp–oport= port User name @ server-side IP

If you do not need to enter a password to connect, then the configuration is successful

2. Jsch Library-based SFTP operation Java code
  1. public class Sftputil {
  2. Private final static Logger log = Loggerfactory.getlogger (Sftputil.class);
  3. /** SFTP */
  4. public static final String sftp = "SFTP";
  5. /** Channel */
  6. Private CHANNELSFTP channel;
  7. /** Session */
  8. Private session session;
  9. /** Avoiding multithreading concurrency */
  10. private static threadlocal<sftputil> sftplocal = new threadlocal<sftputil> ();
  11. /**
  12. * Get Sftpchannel
  13. *
  14. * @param connectconfig Connection Configuration
  15. * @return
  16. * @throws Exception
  17. * @throws jschexception
  18. */
  19. private void init (Connectconfig connectconfig) throws Exception {
  20. String host = Connectconfig.gethost ();
  21. int port = Connectconfig.getport ();
  22. String userName = Connectconfig.getusername ();
  23. Create a Jsch object
  24. Jsch Jsch = new Jsch ();
  25. Add private key (trust login mode)
  26. if (Stringutils.isnotblank (Connectconfig.getprivatekey ())) {
  27. Jsch.addidentity (Connectconfig.getprivatekey ());
  28. }
  29. Session = Jsch.getsession (UserName, host, Port);
  30. if (log.isinfoenabled ()) {
  31. Log.info ("Jsch Session created,sftphost = {}, sftpusername={}", host, UserName);
  32. }
  33. Set Password
  34. if (Stringutils.isnotblank (Connectconfig.getpassword ())) {
  35. Session.setpassword (Connectconfig.getpassword ());
  36. }
  37. Properties Config = new properties ();
  38. Config.put ("stricthostkeychecking", "no");
  39. Session.setconfig (config);
  40. Set timeout
  41. Session.settimeout (Connectconfig.gettimeout ());
  42. Establish a connection
  43. Session.connect ();
  44. if (log.isinfoenabled ()) {
  45. Log.info ("Jsch Session connected.sftphost = {}, sftpusername={}", host, UserName);
  46. }
  47. Open the SFTP Channel
  48. Channel = (CHANNELSFTP) session.openchannel (SFTP);
  49. Establishing the connection to the SFTP channel
  50. Channel.connect ();
  51. if (log.isinfoenabled ()) {
  52. Log.info ("Connected successfully to Sftphost = {}, sftpusername={}", host, UserName);
  53. }
  54. }
  55. /**
  56. * is connected
  57. *
  58. * @return
  59. */
  60. Private Boolean isconnected () {
  61. return null! = Channel && channel.isconnected ();
  62. }
  63. /**
  64. * Get the SFTP client for local thread storage
  65. *
  66. * @return
  67. * @throws Exception
  68. */
  69. public static Sftputil Getsftputil (Connectconfig connectconfig) throws Exception {
  70. Sftputil sftputil = Sftplocal.get ();
  71. if (null = = Sftputil | |!sftputil.isconnected ()) {
  72. Sftplocal.set (New Sftputil (Connectconfig));
  73. }
  74. return Sftplocal.get ();
  75. }
  76. /**
  77. * Release the SFTP client for local thread storage
  78. */
  79. public static void release () {
  80. if (null! = Sftplocal.get ()) {
  81. Sftplocal.get (). Closechannel ();
  82. Sftplocal.set (NULL);
  83. }
  84. }
  85. /**
  86. * Constructor function
  87. * <p>
  88. * Non-thread safe, so permissions are private
  89. * </p>
  90. *
  91. * @throws Exception
  92. */
  93. Private Sftputil (Connectconfig connectconfig) throws Exception {
  94. Super ();
  95. Init (connectconfig);
  96. }
  97. /**
  98. * Close the Channel
  99. *
  100. * @throws Exception
  101. */
  102. public void Closechannel () {
  103. if (null! = Channel) {
  104. try {
  105. Channel.disconnect ();
  106. } catch (Exception e) {
  107. Log.error ("An exception occurred while closing the SFTP channel:", e);
  108. }
  109. }
  110. if (null! = session) {
  111. try {
  112. Session.disconnect ();
  113. } catch (Exception e) {
  114. Log.error ("Sftp off Session Exception:", E);
  115. }
  116. }
  117. }
  118. /**
  119. * Download File
  120. *
  121. * @param downdir Download catalogue
  122. * @param src source file
  123. * @param the file name or directory after DST is saved
  124. * @throws Exception
  125. */
  126. public void Downfile (string downdir, string src, string dst) throws Exception {
  127. CHANNEL.CD (Downdir);
  128. Channel.get (SRC, DST);
  129. }
  130. /**
  131. * Delete Files
  132. *
  133. * @param filePath File full path
  134. * @throws sftpexception
  135. */
  136. public void DeleteFile (String filePath) throws Sftpexception {
  137. CHANNEL.RM (FilePath);
  138. }
  139. @SuppressWarnings ("Unchecked")
  140. Public list<string> listfiles (String dir) throws Sftpexception {
  141. vector<lsentry> files = channel.ls (dir);
  142. if (null! = files) {
  143. list<string> fileNames = new arraylist<string> ();
  144. Iterator<lsentry> iter = Files.iterator ();
  145. while (Iter.hasnext ()) {
  146. String fileName = Iter.next (). GetFileName ();
  147. if (Stringutils.equals (".", FileName) | | Stringutils.equals ("..", FileName)) {
  148. Continue
  149. }
  150. Filenames.add (FileName);
  151. }
  152. return fileNames;
  153. }
  154. return null;
  155. }
  156. }

Description:

2.1 Connectconfig contains all the parameter information needed to establish an SFTP connection

2.2 If the trusted public key configuration for SFTP is followed by the first step, you need to set the private key ID_DSA in the key pair into Java code by calling the Addidentity method of Jsch
    1. Add private key (trust login mode)
    2. if (Stringutils.isnotblank (Connectconfig.getprivatekey ())) {
    3. Jsch.addidentity (Connectconfig.getprivatekey ());
    4. }
2.3 In order to avoid frequent connection establishment and connection release operations, it is generally defined as a singleton pattern, but there are some business scenarios that need to be freed after the same thread has performed several successive complete business operations. In the case of a singleton, there is a concurrency problem with shared resource contention in multiple-threaded scenarios, such as a thread releasing a connection during the execution of a business by a B thread. Therefore, you can use threadlocal to avoid this problem. Java code
  1. /**
  2. * Get the SFTP client for local thread storage
  3. *
  4. * @return
  5. * @throws Exception
  6. */
  7. public static Sftputil Getsftputil (Connectconfig connectconfig) throws Exception {
  8. Sftputil sftputil = Sftplocal.get ();
  9. if (null = = Sftputil | |!sftputil.isconnected ()) {
  10. Sftplocal.set (New Sftputil (Connectconfig));
  11. }
  12. return Sftplocal.get ();
  13. }
  14. /**
  15. * Release the SFTP client for local thread storage
  16. */
  17. public static void release () {
  18. if (null! = Sftplocal.get ()) {
  19. Sftplocal.get (). Closechannel ();
  20. Sftplocal.set (NULL);
  21. }
  22. }

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.