package ma.ma01; import drjava.util.StringUtil; import net.luaos.tb.tb07.PasswordUtil; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.xfer.InMemorySourceFile; import net.schmizz.sshj.xfer.scp.SCPFileTransfer; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TinyBrainSCPUploader { public static void uploadIndexPHP(String hostKey, String url, String text) throws IOException { Matcher matcher = Pattern.compile("http://tinybrain.de:8080/(.*/)").matcher(url); if (!matcher.matches()) throw new RuntimeException("URL not matched: " + url); String remoteDir = "/root/www-8080/" + matcher.group(1); String remoteFilePath = remoteDir + "index.php"; String host = "tinybrain.de", user = "root"; System.out.println("Uploading to: " + remoteFilePath); System.out.print("Password for " + user + "@" + host + ": "); char[] pw = PasswordUtil.readPasswordFromConsole(); final SSHClient client = new SSHClient(); client.loadKnownHosts(); if (!StringUtil.isEmpty(hostKey)) client.addHostKeyVerifier(hostKey); client.connect(host); try { client.authPassword(user, pw); client.newSFTPClient().mkdirs(remoteDir); uploadBySCP(client, remoteFilePath, text); System.out.println("File copied!"); } finally { client.disconnect(); } } private static void uploadBySCP(SSHClient client, String remoteFilePath, String text) throws IOException { uploadBySCP(client, remoteFilePath, text.getBytes("UTF-8")); } private static void uploadBySCP(SSHClient client, String remoteFilePath, final byte[] data) throws IOException { SCPFileTransfer fileTransfer = client.newSCPFileTransfer(); fileTransfer.upload(new InMemorySourceFile() { public String getName() { return "index.php"; } public long getLength() { return data.length; } public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(data); } }, remoteFilePath); } }