Ganymed SSH2 analog Similar FileZilla remote transfer file (based on SCP protocol)

Source: Internet
Author: User
Tags filezilla scp command ssh config ssh config file

ganymed SSH2 analog similar FileZilla remote transfer file (based on SCP protocol)


In order to transfer files or directories, we use the Scpclient class in Ganymed SSH2, which implements the SCP command function.

The following code includes the ability to transfer a single file and transfer a directory:

Package Com.doctor.ganymed_ssh2;import Java.io.file;import Java.io.fileinputstream;import java.io.IOException; Import Java.io.inputstream;import Java.nio.charset.standardcharsets;import Org.apache.commons.io.ioutils;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Ch.ethz.ssh2.channelcondition;import Ch.ethz.ssh2.connection;import Ch.ethz.ssh2.scpclient;import Ch.ethz.ssh2.scpoutputstream;import Ch.ethz.ssh2.session;import ch.ethz.ssh2.streamgobbler;/** * 1. Ensure that the connected Linux machine is installed SSH and the service is open; * 2. Password login, need configuration file: * SSH config file:/ect/ssh/sshd_config * Configuration item: Passwordauthentication Yes * * Verify login successful no: SSH 127.0.0.1 (/other) * * @ See http://www.ganymed.ethz.ch/ssh2/FAQ.html * http://www.programcreek.com/java-api-examples/index.php?api= Ch.ethz.ssh2.StreamGobbler * http://www.javawebdevelop.com/3240343/* http://www.programcreek.com/java-api-examp Les/index.php?api=ch.ethz.ssh2.scpclient * @author Doctor * * @time August 5, 2015 */public final class Sshagent {private Log Ger Log = LoggerfactorY.getlogger (GetClass ());p rivate Connection connection;public void Initsession (String hostName, String userName, String passwd) throws IOException {connection = new connection (hostName); Connection.connect (); Boolean Authenticatewithpassword = Connection.authenticatewithpassword (UserName, passwd), if (!authenticatewithpassword) { throw new RuntimeException ("Authentication failed. Please check hostName, userName and passwd ");} /** * Why can ' t I execute several commands in one single session? * If You use Session.execcommand () and then you indeed can only execute one command per Session. This isn't a restriction of the library, but rather an enforcement by the underlying SSH-2 protocol (a Session object mod Els the underlying SSH-2 session). * * There is several solutions: * * Simple:execute several commands in one batch, e.g., something like session.execcom Mand ("Echo Hello && echo Again"). * Simple:the intended way:simply open a new session for each command-once you have Opened a connection, you can ask for as many sessions as you want, they is only a "virtual" construct. * advanced:don ' t use Session.execcommand (), but rather aquire a shell with Session.startshell (). * * @param command * @return * @throws ioexception */public string execcommand (String command) throws IOException {Sessio n session = Connection.opensession (); Session.execcommand (Command, StandardCharsets.UTF_8.toString ()); InputStream Streamgobbler = new Streamgobbler (Session.getstdout ()); String result = ioutils.tostring (Streamgobbler, standardcharsets.utf_8); Session.waitforcondition ( Channelcondition.exit_signal, Long.max_value); if (Session.getexitstatus (). Intvalue () = = 0) {log.info ("ExecCommand: {} Success ", command);} else {log.error ("ExecCommand: {} fail", command);} ioutils.closequietly (Streamgobbler); Session.close (); return result;} /** * Remote transfer of individual files * * @param localfile * @param remotetargetdirectory * @throws ioexception */public void Transferfile (Strin G LocalFile, String RemotetargEtdirectory) throws IOException {File File = new file (LocalFile), if (File.isdirectory ()) {throw new RuntimeException (Loca Lfile + "is not a file");} String fileName = File.getname (); ExecCommand ("CD" + Remotetargetdirectory + "; RM" + FileName + "; Touch "+ fileName); Scpclient scpclient = Connection.createscpclient (); Scpoutputstream Scpoutputstream = Scpclient.put (FileName, File.length (), Remotetargetdirectory, "7777"); String content = ioutils.tostring (new FileInputStream (file)); Scpoutputstream.write (Content.getbytes ( Standardcharsets.utf_8)); Scpoutputstream.flush (); Scpoutputstream.close ();} /** * Transfer Entire Directory * * @param localfile * @param remotetargetdirectory * @throws ioexception */public void Transferdirectory (St Ring localdirectory, String remotetargetdirectory) throws IOException {file Dir = new File (localdirectory); if (!dir.isdir Ectory ()) {throw new RuntimeException (Localdirectory + "is not Directory");} string[] files = dir.list (); for (String file:files) {if (File.startswith (".")) {Continue;}  String fullName = Localdirectory + "/" + file;if (new file (FullName). Isdirectory ()) {string rdir = Remotetargetdirectory + "/" + File;execcommand ("mkdir-p" + remotetargetdirectory + "/" + file); Transferdirectory (FullName, rdir);} else {transferfile (fullName, remotetargetdirectory);}}} public void Close () {connection.close ();} public static void Main (string[] args) throws IOException {sshagent sshagent = new Sshagent (); Sshagent.initsession ("127.0 .0.1 "," root "," xxx "); String execcommand = Sshagent.execcommand ("PWD; Date "); System.out.println ("PWD; Date: "+ execcommand); String ExecCommand2 = Sshagent.execcommand ("who"); System.out.println ("Who:" + ExecCommand2); Sshagent.transferfile ("/home/xx/documents/a", "/home/xx"); Sshagent.transferdirectory ("/home/xx/documents", "/home/xx/book");//Execute Bash Script System.out.println ( Sshagent.execcommand ("Cd/home/xx/book;./test.sh")); Sshagent.close ();}}

The results of the operation are not posted.

When you transfer a directory, you simply traverse the file transfer recursively. The transmission of a single file can also be optimized, with a single file having large, small capacity after all.

The remote file directory also executes system commands to create.
Directory creation We used the mkdir-p, so that the system will automatically be created for us, even if the parents are not recorded.

Copyright NOTICE: This article for Bo Master original article, without BO Master permission cannot reprint [http://blog.csdn.net/doctor_who2004].

Ganymed SSH2 analog Similar FileZilla remote transfer file (based on SCP protocol)

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.