本示例是從一個節點上讀取文件,並經過調用接口將文件傳輸另外一個節點上,並存儲在數據庫java
思路是從源服務器上下載時要將文件流存儲到一個臨時文件裏,而後將臨時文件讀取爲base64的轉碼,將base64的轉碼發送到目標服務器的接口上就實現了node
我理解,無論是java仍是js裏,圖片和文檔都是轉爲base64的轉碼,而後經過rest方式來傳輸的,但若是文件比較大了,那應該不能這麼作了數據庫
public static void main(String[] args) { JSONObject transferpdf = File2Json.getConfig("transferpdf"); //這個是讀取配置文件的 JSONArray nodes = transferpdf.getJSONArray("node"); nodes.forEach(item -> { JSONObject jsonObject = JSONObject.parseObject(item.toString()); String ip = jsonObject.getString("ip"); String password = jsonObject.getString("password"); String username = jsonObject.getString("username"); String dir = jsonObject.getString("dir"); SshClient client = new SshClient(); BufferedOutputStream bos = null; FileOutputStream fos = null; try { String hosts = "/root/.ssh/known_hosts"; ConsoleKnownHostsKeyVerification console = new ConsoleKnownHostsKeyVerification(hosts); client.connect(ip, 22, console);//IP和端口 //設置用戶名和密碼 PasswordAuthenticationClient pwd = new PasswordAuthenticationClient(); pwd.setUsername(username); pwd.setPassword(password); int result = client.authenticate(pwd); String reg = "[A-Za-z0-9]{10,}_[0-9]{10,}_[0-9]{8,}.pdf"; Pattern pattern = Pattern.compile(reg); Matcher matcher = null; if (result == AuthenticationProtocolState.COMPLETE) {//若是鏈接完成 SftpClient sftp = client.openSftpClient(); List<SftpFile> list = sftp.ls(dir); for (SftpFile f : list) { String name = f.getFilename(); matcher = pattern.matcher(name); if (matcher.matches()) { String path = f.getAbsolutePath(); System.out.println(path); String filename = name.split("\\.")[0]; String fpqqlsh = filename.split("_")[0]; File file = File.createTempFile(filename, ".pdf"); //建立臨時文件 fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); FileAttributes fa = sftp.get(f.getAbsolutePath(), bos); bos.write(fa.toByteArray()); String pdf = PDFToBase64(file); file.deleteOnExit(); JSONObject reqJson = new JSONObject(); reqJson.put("filename", filename); reqJson.put("pdf", pdf); reqJson.put("fpqqlsh", "7E275D9B64FB43BCB56"); InvoiceAPI invoiceAPI = InvoiceAPI.getInstance(); String url = "http://192.168.13.52:33890/einvoice/apis/v1.0/uploadInvoice"; JSONObject respJson = invoiceAPI.executeRequest(reqJson.toJSONString(), url); System.out.println(respJson); } } } } catch (IOException e) { e.printStackTrace(); } finally { client.disconnect(); if (fos != null) { try { fos.close(); } catch (IOException e) { } } if (bos != null) { try { bos.close(); } catch (IOException e) { } } } }); }
public static String PDFToBase64(File file) { BASE64Encoder encoder = new BASE64Encoder(); FileInputStream fin = null; BufferedInputStream bin = null; ByteArrayOutputStream baos = null; BufferedOutputStream bout = null; try { fin = new FileInputStream(file); bin = new BufferedInputStream(fin); baos = new ByteArrayOutputStream(); bout = new BufferedOutputStream(baos); byte[] buffer = new byte[1024]; int len = bin.read(buffer); while (len != -1) { bout.write(buffer, 0, len); len = bin.read(buffer); } //刷新此輸出流並強制寫出全部緩衝的輸出字節 bout.flush(); byte[] bytes = baos.toByteArray(); String base64 = encoder.encodeBuffer(bytes).trim(); // System.out.println(base64); return base64; } catch (IOException e) { e.printStackTrace(); } finally { try { fin.close(); bin.close(); bout.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
import com.sshtools.j2ssh.SshClient; import com.sshtools.j2ssh.authentication.AuthenticationProtocolState; import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient; import com.sshtools.j2ssh.sftp.SftpFile; import com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification; import com.sshtools.j2ssh.transport.InvalidHostFileException; import com.sshtools.j2ssh.transport.publickey.SshPublicKey; import java.io.*; import java.util.List; /** * Created by garila on 2017/6/28. */ public class ConsoleKnownHostsKeyVerification extends AbstractKnownHostsKeyVerification { public ConsoleKnownHostsKeyVerification() throws InvalidHostFileException { super(new File(System.getProperty("user.home"), ".ssh" + File.separator + "known_hosts").getAbsolutePath()); } public ConsoleKnownHostsKeyVerification(String knownhosts) throws InvalidHostFileException { super(knownhosts); } public void onHostKeyMismatch(String host, SshPublicKey pk, SshPublicKey actual) { try { System.out.println("The host key supplied by " + host + " is: " + actual.getFingerprint()); System.out.println("The current allowed key for " + host + " is: " + pk.getFingerprint()); getResponse(host, pk); } catch (Exception e) { e.printStackTrace(); } } public void onUnknownHost(String host, SshPublicKey pk) { try { System.out.println("The host " + host + " is currently unknown to the system"); System.out.println("The host key fingerprint is: " + pk.getFingerprint()); getResponse(host, pk); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取用戶輸入的信息,判斷是否接受主機公匙 * <p> * 修改:xxx ,去掉從流中獲取信息,直接接受公匙,註釋掉的代碼爲源碼 * * @param host 主機ip * @param pk 主機公匙 * @throws InvalidHostFileException * @throws IOException */ private void getResponse(String host, SshPublicKey pk) throws InvalidHostFileException, IOException { // if (isHostFileWriteable()) { // } allowHost(host, pk, true); } }
在getResponse方法中,我在本機上測試驗證是經過的,可是提交到服務器以後驗證就不經過,報異常:json
Could not open or read /root/.ssh/known_hosts: ecdsa-sha2-nistp256 is not supportedwindows
沒有找到是什麼緣由,不是文件的讀寫權限的問題,我已經改過了,並且在windows上測試的時候是經過的,後來我就直接將isHostFileWriteable註釋掉,強行驗證經過就能夠用了,沒有找到根本緣由,還得繼續找,先這麼用着api