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
- public class Sftputil {
- Private final static Logger log = Loggerfactory.getlogger (Sftputil.class);
- /** SFTP */
- public static final String sftp = "SFTP";
- /** Channel */
- Private CHANNELSFTP channel;
- /** Session */
- Private session session;
- /** Avoiding multithreading concurrency */
- private static threadlocal<sftputil> sftplocal = new threadlocal<sftputil> ();
- /**
- * Get Sftpchannel
- *
- * @param connectconfig Connection Configuration
- * @return
- * @throws Exception
- * @throws jschexception
- */
- private void init (Connectconfig connectconfig) throws Exception {
- String host = Connectconfig.gethost ();
- int port = Connectconfig.getport ();
- String userName = Connectconfig.getusername ();
- Create a Jsch object
- Jsch Jsch = new Jsch ();
- Add private key (trust login mode)
- if (Stringutils.isnotblank (Connectconfig.getprivatekey ())) {
- Jsch.addidentity (Connectconfig.getprivatekey ());
- }
- Session = Jsch.getsession (UserName, host, Port);
- if (log.isinfoenabled ()) {
- Log.info ("Jsch Session created,sftphost = {}, sftpusername={}", host, UserName);
- }
- Set Password
- if (Stringutils.isnotblank (Connectconfig.getpassword ())) {
- Session.setpassword (Connectconfig.getpassword ());
- }
- Properties Config = new properties ();
- Config.put ("stricthostkeychecking", "no");
- Session.setconfig (config);
- Set timeout
- Session.settimeout (Connectconfig.gettimeout ());
- Establish a connection
- Session.connect ();
- if (log.isinfoenabled ()) {
- Log.info ("Jsch Session connected.sftphost = {}, sftpusername={}", host, UserName);
- }
- Open the SFTP Channel
- Channel = (CHANNELSFTP) session.openchannel (SFTP);
- Establishing the connection to the SFTP channel
- Channel.connect ();
- if (log.isinfoenabled ()) {
- Log.info ("Connected successfully to Sftphost = {}, sftpusername={}", host, UserName);
- }
- }
- /**
- * is connected
- *
- * @return
- */
- Private Boolean isconnected () {
- return null! = Channel && channel.isconnected ();
- }
- /**
- * Get the SFTP client for local thread storage
- *
- * @return
- * @throws Exception
- */
- public static Sftputil Getsftputil (Connectconfig connectconfig) throws Exception {
- Sftputil sftputil = Sftplocal.get ();
- if (null = = Sftputil | |!sftputil.isconnected ()) {
- Sftplocal.set (New Sftputil (Connectconfig));
- }
- return Sftplocal.get ();
- }
- /**
- * Release the SFTP client for local thread storage
- */
- public static void release () {
- if (null! = Sftplocal.get ()) {
- Sftplocal.get (). Closechannel ();
- Sftplocal.set (NULL);
- }
- }
- /**
- * Constructor function
- * <p>
- * Non-thread safe, so permissions are private
- * </p>
- *
- * @throws Exception
- */
- Private Sftputil (Connectconfig connectconfig) throws Exception {
- Super ();
- Init (connectconfig);
- }
- /**
- * Close the Channel
- *
- * @throws Exception
- */
- public void Closechannel () {
- if (null! = Channel) {
- try {
- Channel.disconnect ();
- } catch (Exception e) {
- Log.error ("An exception occurred while closing the SFTP channel:", e);
- }
- }
- if (null! = session) {
- try {
- Session.disconnect ();
- } catch (Exception e) {
- Log.error ("Sftp off Session Exception:", E);
- }
- }
- }
- /**
- * Download File
- *
- * @param downdir Download catalogue
- * @param src source file
- * @param the file name or directory after DST is saved
- * @throws Exception
- */
- public void Downfile (string downdir, string src, string dst) throws Exception {
- CHANNEL.CD (Downdir);
- Channel.get (SRC, DST);
- }
- /**
- * Delete Files
- *
- * @param filePath File full path
- * @throws sftpexception
- */
- public void DeleteFile (String filePath) throws Sftpexception {
- CHANNEL.RM (FilePath);
- }
- @SuppressWarnings ("Unchecked")
- Public list<string> listfiles (String dir) throws Sftpexception {
- vector<lsentry> files = channel.ls (dir);
- if (null! = files) {
- list<string> fileNames = new arraylist<string> ();
- Iterator<lsentry> iter = Files.iterator ();
- while (Iter.hasnext ()) {
- String fileName = Iter.next (). GetFileName ();
- if (Stringutils.equals (".", FileName) | | Stringutils.equals ("..", FileName)) {
- Continue
- }
- Filenames.add (FileName);
- }
- return fileNames;
- }
- return null;
- }
- }
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
- Add private key (trust login mode)
- if (Stringutils.isnotblank (Connectconfig.getprivatekey ())) {
- Jsch.addidentity (Connectconfig.getprivatekey ());
- }
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
- /**
- * Get the SFTP client for local thread storage
- *
- * @return
- * @throws Exception
- */
- public static Sftputil Getsftputil (Connectconfig connectconfig) throws Exception {
- Sftputil sftputil = Sftplocal.get ();
- if (null = = Sftputil | |!sftputil.isconnected ()) {
- Sftplocal.set (New Sftputil (Connectconfig));
- }
- return Sftplocal.get ();
- }
- /**
- * Release the SFTP client for local thread storage
- */
- public static void release () {
- if (null! = Sftplocal.get ()) {
- Sftplocal.get (). Closechannel ();
- Sftplocal.set (NULL);
- }
- }