Amazon EC2に離れた場所からファイルをアップロードする場合のコード
////////////////////////////////////////////////////////////////////////////
package logic;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* EC2FileUpload is for simply upload date from your desktop to Amazon EC2 server.
* You need jar file ganymed-ssh2-build250.jar from http://www.cleondris.ch/ssh2
*/
public class EC2FileUpload {
private static String key = "path to key xx.pem";
private static String hostname = "host name";
private static String username = "user name";
public static void main(String[] args) {
EC2FileUpload f = new EC2FileUpload();
f.upload("local path", "ec2 path");
}
public void upload(String pathFrom, String pathTo) {
File keyfile = new File(key); // or "~/.ssh/id_dsa"
String keyfilePass = ""; // will be ignored if not needed
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);
if (isAuthenticated == false) {
throw new IOException("Authentication failed.");
}
Session sess = conn.openSession();
// sess.execCommand("uname -a && date && uptime && who");
sess.execCommand("ls -l " + pathTo);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
System.out.println("Here is all file you upload to server:");
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
SCPClient scp = conn.createSCPClient();
scp.put(pathFrom, pathTo);
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment