質問
Javaプログラミング言語を介してscp転送を実行する最良の方法は何ですか? JSSE、JSch、または弾力性のある城のJavaライブラリを介してこれを実行できる可能性があるようです。これらの解決策はどれも簡単な答えを出していないようです。
解決
Jsch を使用することになりました。これはかなり簡単で、かなりうまくスケールアップしたようです(数分ごとに数千のファイルを取得していました。
他のヒント
こちらをご覧くださいこちら
これがアリのSCPタスクのソースコードです。 "実行"のコードメソッドは、そのナットとボルトがある場所です。これにより、何が必要であるかについて公平な考えが得られるはずです。私は信じているJSchを使用しています。
別の方法として、JavaコードからこのAntタスクを直接実行することもできます。
Jschをいくつかのユーティリティメソッドでラップして少し使いやすくし、呼び出しました
Jscp
ここで利用可能: https://github.com/willwarren/jscp
フォルダをtarし、zip圧縮し、どこかでscpしてからそれを解凍する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")
);
また、ScpとExec、およびTarAndGzipの便利なクラスも含まれています。これらはほぼ同じように機能します。
これは高レベルのソリューションであり、再発明する必要はありません。早くて汚い!
1)まず、 http://ant.apacheにアクセスします。 org / bindownload.cgi にアクセスして、最新のApache Antバイナリをダウンロードします。 (現在、apache-ant-1.9.4-bin.zip)。
2)ダウンロードしたファイルを抽出し、JAR ant-jsch.jar (" apache-ant-1.9.4 / lib / ant-jsch.jar&quot)を見つけます;)。 このJARをプロジェクトに追加します。 ant-launcher.jarおよびant.jarも。
3) Jcraft jsch SouceForgeプロジェクト jarをダウンロードします。今日では、 jsch-0.1。 52.jar 。また、このJARをプロジェクトに追加します。
今、ネットワーク経由でファイルをコピーするためのAntクラス Scp またはSSHサーバーのコマンド用の SSHExec を簡単にJavaコードに使用できます。
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();
opensshプロジェクトには、いくつかのJavaの代替案、 Trilead SSH for Java は、あなたが求めているものに合うようです。
Zehonと呼ばれるSCPを持つこのSFTP APIを使用します。多くのサンプルコードで簡単に使用できます。サイトは http://www.zehon.com
です。これらのソリューションの多くを見て、それらの多くが好きではありませんでした。主に、既知のホストを特定する必要があるという面倒なステップが原因です。それとJSCHはscpコマンドに比べて途方もなく低いレベルです。
これを必要としないライブラリが見つかりましたが、バンドルされており、コマンドラインツールとして使用されています。 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();
最大の欠点は、Mavenリポジトリにないことです(見つけることができます)。しかし、使いやすさは私にとって価値があります。
ここのように、JSchライブラリのラッパーを書くことになりました。
これはway-secshellと呼ばれ、GitHubでホストされます:
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();
他のものよりもはるかに簡単なscpサーバーを作成しました。 Apache MINAプロジェクト(Apache SSHD)を使用して開発しています。こちらをご覧ください: https://github.com/boomz/JSCP
また、 / jar
ディレクトリからjarファイルをダウンロードできます。
使い方?ご覧ください: https://github.com/boomz/JSCP/ blob / master / src / Main.java
jsCHは私にとって素晴らしい仕事をしました。以下は、sftpサーバーに接続し、指定されたディレクトリにファイルをダウンロードする方法の例です。 StrictHostKeyCheckingを無効にしないことをお勧めします。設定が少し難しくなりますが、セキュリティ上の理由から、既知のホストを指定するのが一般的です。
jsch.setKnownHosts(" C:\ Users \ test \ known_hosts"); 推奨
JSch.setConfig(" StrictHostKeyChecking&quot ;," no"); -非推奨
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。 com / 2013/09 / java-uploading-file-remotely-via-scp.html
別のソリューションを試した後、フォルダーを再帰的にコピーする必要があり、最終的にProcessBuilder + expect / spawnになります
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();
}