سؤال

ما هي أفضل طريقة أداء scp نقل عن طريق لغة البرمجة جافا?يبدو أنني قد تكون قادرة على أداء هذا عبر JSSE, JSch أو نطاط القلعة المكتبات جافا.أيا من هذه الحلول يبدو أن إجابة سهلة.

هل كانت مفيدة؟

المحلول

وانتهى بي الأمر باستخدام Jsch - كان صريحا جدا، وبدا لرفع مستوى جيد جدا ( كنت الاستيلاء على بضعة آلاف من الملفات كل بضع دقائق).

نصائح أخرى

والمكونات: sshj هو الخيار الوحيد عاقل! نرى هذه الأمثلة لتبدأ: <لأ href = "https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SCPDownload.java" يختلط = "نوفولو noreferrer"> تحميل و <لأ href = "https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SCPUpload. جافا "يختلط =" نوفولو noreferrer "> تحميل .

نلقي نظرة هنا

وهذا هو مصدر رمز النمل SCP المهمة.رمز في "تنفيذ" الأسلوب هو حيث الصواميل والمسامير من ذلك.هذا يجب أن تعطيك فكرة عادلة من ما هو مطلوب.ويستخدم JSch أعتقد.

وبدلا من ذلك يمكنك أيضا مباشرة تنفيذ هذه النملة مهمة من شفرة جافا.

وأنا ملفوفة Jsch مع بعض الأساليب فائدة لجعله أكثر ودا قليلا ويطلق عليه

تحليل Jscp

والمتوفرة هنا: https://github.com/willwarren/jscp

وفائدة SCP لالقطران مجلد، والرمز البريدي ذلك، واللجنة الدائمة في مكان ما، ثم فك الضغط.

والاستعمال:

// create secure context
SecureContext context = new SecureContext("userName", "localhost");

// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));

// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());

Jscp.exec(context, 
           "src/dir",
           "destination/path",
           // regex ignore list 
           Arrays.asList("logs/log[0-9]*.txt",
           "backups") 
           );

ويشمل أيضا فئات مفيدة - الدائمة واكسيك، وTarAndGzip، والتي تعمل في حد كبير بنفس الطريقة

هذا هو عالية المستوى الحل, لا تحتاج إلى إعادة اختراع.سريعة وقذرة!

1) أولا: http://ant.apache.org/bindownload.cgi وتحميل أحدث أباتشي النمل الثنائية.(في الوقت الحاضر ، apache-ant-1.9.4-bin.zip).

2) استخراج الملف الذي تم تنزيله و العثور على جرة ant-jsch.jar ("apache-ant-1.9.4/lib/ant-jsch.jar"). هذا إضافة جرة في المشروع الخاص بك.أيضا ant-launcher.jar و ant.jar.

3) انتقل إلى Jcraft jsch SouceForge المشروع و تحميل جرة.في الوقت الحاضر ، jsch-0.1.52.jar.أيضا هذا إضافة جرة في المشروع الخاص بك.

الآن يمكنك easyly في كود جافا النمل الطبقات Scp لـ نسخ الملفات عبر الشبكة أو SSHExec بالنسبة الأوامر في خوادم SSH.

4) رمز المثال Scp:

// This make scp copy of 
// one local file to remote dir

org.apache.tools.ant.taskdefs.optional.ssh.Scp scp = new Scp();
int portSSH = 22;
String srvrSSH = "ssh.your.domain";
String userSSH = "anyuser"; 
String pswdSSH = new String ( jPasswordField1.getPassword() );
String localFile = "C:\\localfile.txt";
String remoteDir = "/uploads/";

scp.setPort( portSSH );
scp.setLocalFile( localFile );
scp.setTodir( userSSH + ":" + pswdSSH + "@" + srvrSSH + ":" + remoteDir );
scp.setProject( new Project() );
scp.setTrust( true );
scp.execute();

المفتوح مشروع يسرد عدة بدائل جافا، <وأ href = "HTTP: // www.trilead.com/Products/Trilead_SSH_for_Java/ "يختلط =" نوفولو noreferrer "> Trilead SSH لجاوا يبدو لتناسب ما كنت طالبا.

وأنا استخدم هذا SFTP API الذي دعا SCP Zehon، انه لشيء رائع، من السهل جدا للاستخدام مع الكثير من التعليمات البرمجية. هنا هو http://www.zehon.com

لقد بحثت في الكثير من هذه الحلول لم يعجبكم العديد منهم.لأن معظمها مزعج خطوة من الحاجة إلى تحديد المعروف المضيفين.و JSCH في السخرية مستوى منخفض بالنسبة إلى الأوامر الدائمة.

وجدت المكتبة التي لا تتطلب هذا لكنه المجمعة و استخدام أداة سطر الأوامر. https://code.google.com/p/scp-java-client/

نظرت من خلال التعليمات البرمجية المصدر و اكتشف كيفية استخدامه دون سطر الأوامر.هنا مثال على تحميل:

    uk.co.marcoratto.scp.SCP scp = new uk.co.marcoratto.scp.SCP(new uk.co.marcoratto.scp.listeners.SCPListenerPrintStream());
    scp.setUsername("root");
    scp.setPassword("blah");
    scp.setTrust(true);
    scp.setFromUri(file.getAbsolutePath());
    scp.setToUri("root@host:/path/on/remote");
    scp.execute();

أكبر الجانب السلبي هو أنه ليس في مخضرم الريبو (أجد).ولكن سهولة الاستخدام هو يستحق ذلك بالنسبة لي.

ومثل بعض هنا، انتهى بي الأمر كتابة التفاف حول المكتبة JSch.

وانه دعا الطريق secshell ويتم استضافتها على جيثب:

https://github.com/objectos/way-secshell

// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
  .file(file)
  .toHost("localhost")
  .at("/tmp")
  .send();

وكتبت خادم اللجنة الدائمة الذي هو أسهل بكثير من غيرها. يمكنني استخدام أباتشي MINA مشروع (أباتشي SSHD) لتطويره. يمكنك إلقاء نظرة هنا: https://github.com/boomz/JSCP كما يمكنك تحميل ملف جرة من دليل /jar. كيف تستعمل؟ نلقي نظرة على: https://github.com/boomz/JSCP/ فقاعة / الماجستير / SRC / Main.java

jsCH عملت كبيرة بالنسبة لي.أدناه هو مثال على الطريقة التي سيتم ربط إلى خادم sftp و تحميل الملفات إلى الدليل المحدد.فمن المستحسن أن تبقى بعيدا عن تعطيل StrictHostKeyChecking.على الرغم من أن أكثر قليلا من الصعب اقامة لأسباب أمنية تحديد المعروف يستضيف ينبغي أن يكون هو القاعدة.

jsch.setKnownHosts("C:\Users est\known_hosts"); أوصت

JSch.setConfig("StrictHostKeyChecking", "لا"); - لا ينصح

import com.jcraft.jsch.*;
 public void downloadFtp(String userName, String password, String host, int port, String path) {


        Session session = null;
        Channel channel = null;
        try {
            JSch ssh = new JSch();
            JSch.setConfig("StrictHostKeyChecking", "no");
            session = ssh.getSession(userName, host, port);
            session.setPassword(password);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.get(path, "specify path to where you want the files to be output");
        } catch (JSchException e) {
            System.out.println(userName);
            e.printStackTrace();


        } catch (SftpException e) {
            System.out.println(userName);
            e.printStackTrace();
        } finally {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }

    }

وJSch هي مكتبة لطيفة للعمل مع. فإنه لا بأس إجابة سهلة لسؤالك.

JSch jsch=new JSch();
  Session session=jsch.getSession(user, host, 22);
  session.setPassword("password");


  Properties config = new Properties();
  config.put("StrictHostKeyChecking","no");
  session.setConfig(config);
  session.connect();

  boolean ptimestamp = true;

  // exec 'scp -t rfile' remotely
  String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
  Channel channel=session.openChannel("exec");
  ((ChannelExec)channel).setCommand(command);

  // get I/O streams for remote scp
  OutputStream out=channel.getOutputStream();
  InputStream in=channel.getInputStream();

  channel.connect();

  if(checkAck(in)!=0){
    System.exit(0);
  }

  File _lfile = new File(lfile);

  if(ptimestamp){
    command="T "+(_lfile.lastModified()/1000)+" 0";
    // The access time should be sent here,
    // but it is not accessible with JavaAPI ;-<
    command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
    out.write(command.getBytes()); out.flush();
    if(checkAck(in)!=0){
      System.exit(0);
    }
  }

ويمكنك العثور على رمز كاملة في

HTTP: //faisalbhagat.blogspot. كوم / 2013/09 / جافا تحميل ملف-بعد-عبر-scp.html

وأحتاج لنسخ مجلد متكرر، بعد محاولة إيجاد حلول مختلفة، في نهاية أخيرا من قبل ProcessBuilder + تتوقع / تفرخ

scpFile("192.168.1.1", "root","password","/tmp/1","/tmp");

public void scpFile(String host, String username, String password, String src, String dest) throws Exception {

    String[] scpCmd = new String[]{"expect", "-c", String.format("spawn scp -r %s %s@%s:%s\n", src, username, host, dest)  +
            "expect \"?assword:\"\n" +
            String.format("send \"%s\\r\"\n", password) +
            "expect eof"};

    ProcessBuilder pb = new ProcessBuilder(scpCmd);
    System.out.println("Run shell command: " + Arrays.toString(scpCmd));
    Process process = pb.start();
    int errCode = process.waitFor();
    System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
    System.out.println("Echo Output:\n" + output(process.getInputStream()));
    if(errCode != 0) throw new Exception();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top