1 | package ma.ma01;
|
2 |
|
3 | import drjava.util.StringUtil;
|
4 | import net.luaos.tb.tb07.PasswordUtil;
|
5 | import net.schmizz.sshj.SSHClient;
|
6 | import net.schmizz.sshj.xfer.InMemorySourceFile;
|
7 | import net.schmizz.sshj.xfer.scp.SCPFileTransfer;
|
8 |
|
9 | import java.io.ByteArrayInputStream;
|
10 | import java.io.IOException;
|
11 | import java.io.InputStream;
|
12 | import java.util.regex.Matcher;
|
13 | import java.util.regex.Pattern;
|
14 |
|
15 | public class TinyBrainSCPUploader {
|
16 | public static void uploadIndexPHP(String hostKey, String url, String text) throws IOException {
|
17 | Matcher matcher = Pattern.compile("http://tinybrain.de:8080/(.*/)").matcher(url);
|
18 | if (!matcher.matches())
|
19 | throw new RuntimeException("URL not matched: " + url);
|
20 |
|
21 | String remoteDir = "/root/www-8080/" + matcher.group(1);
|
22 | String remoteFilePath = remoteDir + "index.php";
|
23 | String host = "tinybrain.de", user = "root";
|
24 |
|
25 | System.out.println("Uploading to: " + remoteFilePath);
|
26 | System.out.print("Password for " + user + "@" + host + ": ");
|
27 | char[] pw = PasswordUtil.readPasswordFromConsole();
|
28 |
|
29 | final SSHClient client = new SSHClient();
|
30 | client.loadKnownHosts();
|
31 | if (!StringUtil.isEmpty(hostKey))
|
32 | client.addHostKeyVerifier(hostKey);
|
33 | client.connect(host);
|
34 | try {
|
35 | client.authPassword(user, pw);
|
36 | client.newSFTPClient().mkdirs(remoteDir);
|
37 | uploadBySCP(client, remoteFilePath, text);
|
38 | System.out.println("File copied!");
|
39 | } finally {
|
40 | client.disconnect();
|
41 | }
|
42 | }
|
43 |
|
44 | private static void uploadBySCP(SSHClient client, String remoteFilePath, String text) throws IOException {
|
45 | uploadBySCP(client, remoteFilePath, text.getBytes("UTF-8"));
|
46 | }
|
47 |
|
48 | private static void uploadBySCP(SSHClient client, String remoteFilePath, final byte[] data) throws IOException {
|
49 | SCPFileTransfer fileTransfer = client.newSCPFileTransfer();
|
50 | fileTransfer.upload(new InMemorySourceFile() {
|
51 | public String getName() {
|
52 | return "index.php";
|
53 | }
|
54 |
|
55 | public long getLength() {
|
56 | return data.length;
|
57 | }
|
58 |
|
59 | public InputStream getInputStream() throws IOException {
|
60 | return new ByteArrayInputStream(data);
|
61 | }
|
62 | }, remoteFilePath);
|
63 | }
|
64 | }
|