자바 sftp 및 원 격 실행 명령 구현
package com.icbc.SFTP;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class MediaSftp {
public Session session;
private String usr;
private String pwd;
public MediaSftp(String usr,String pwd,String ip) throws JSchException {
this.usr = usr;
this.pwd=pwd;
Connect(ip);
}
public void Connect(String ip) throws JSchException{
JSch jsch = new JSch();
try{
this.session = jsch.getSession(this.usr, ip,22);
if(session != null){
session.setPassword(this.pwd);
session.setConfig("StrictHostKeyChecking","no");
session.setTimeout(30000);
session.connect();
System.out.println("connect to "+ip);
if(session != null && !session.isConnected()){
this.close();
}
}
}catch(JSchException e){
throw e;
}
}
public void close(){
if(session != null && session.isConnected()){
session.disconnect();
// this.isConnectSSH = false;
}else{
}
}
public boolean download(String downloadFile,String saveFile) throws Exception{
try {
ChannelSftp sftp = (ChannelSftp)
session.openChannel("sftp");
sftp.connect();
sftp.cd("/opt/activemq/apache-activemq-5.13.4/webapps/fileserver/media/");
File file = new File(saveFile);
System.out.println(saveFile);
File parentFile = file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
InputStream in = null;
FileOutputStream outputStream = new FileOutputStream(file);
in = sftp.get(downloadFile);
// byte
byte[] buffer = new byte[20480];
int count = 0;
while ((count = in.read(buffer)) != -1) {
if (count == 0) break;
outputStream.write(buffer, 0, count);
}
in.close();
outputStream.close();
outputStream.flush();
sftp.disconnect();
this.close();
return true;
} catch (Exception e) {
throw e;
}
}
}
호출 할 때 먼저 이 종 류 를 예화 한 다음 에 다운 로드 방법 을 직접 호출 하면 됩 니 다.입 참 은 다운로드 할 파일 이름과 로 컬 에 저장 할 경로 입 니 다. 그리고 로 컬 파일 이름 을 맞 춰 download 방법 으로 들 어 갑 니 다.반환 값 은 다운로드 시간 입 니 다.
public long getMedia(String hostip,String fileName, String localPath) throws Exception {
MediaSftp sftp = new MediaSftp("username","passwords",hostip);
String localFile = localPath+fileName;
long start = System.currentTimeMillis();
sftp.download(fileName, localFile);
return System.currentTimeMillis()-start;
}
이 밖 에 jsch 는 원 격 ssh 프로 토 콜 로그 인 후 명령 을 수행 하 는 방법 도 제공 했다.디 렉 터 리 에 최근 에 업 데 이 트 된 파일 이름 을 가 져 오 는 명령 을 실행 하 는 방법 입 니 다. 이 방법 을 MediaSftp 클래스 에 추가 할 수 있 습 니 다. MedisSftp 클래스 를 예화 하여 연결 을 만 든 후 이 방법 을 사용 할 수 있 습 니 다.
public String getLatestFileName(String patterns) throws Exception {
// , patterns
String cmd = "ls -ltr /opt/activemq/apache-activemq-5.13.4/webapps/fileserver/media/|grep "+patterns+"|tail -1|awk {'print $NF'}
";
ByteArrayOutputStream retOut = new ByteArrayOutputStream();
ChannelShell channelShell = (ChannelShell)session.openChannel("shell");
PipedInputStream cmdIn = new PipedInputStream();
PipedOutputStream cmdOut = new PipedOutputStream(cmdIn);
channelShell.setInputStream(cmdIn);
channelShell.setOutputStream(retOut);
channelShell.connect(30000);
cmdOut.write(cmd.getBytes());
cmdOut.flush();
//
Thread.sleep(2000);
cmdOut.close();
cmdIn.close();
String retMsg = retOut.toString();
retOut.close();
channelShell.disconnect();
// ,
String[] retArr= retMsg.split("
");
return retArr[retArr.length-2].trim();
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.