pom.xml
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
java代码片段
import java.util.StringTokenizer;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public String runSftpConnect(HttpServletRequest request,String server,String port, String username, String password, String root,String fileName,int sku_no) throws Exception{
String EDIFile="";
Connection connection = null;
Session sess = null;
InputStream stdout = null;
BufferedReader stdoutReader = null;
try {
int ipPort = 2222;
if(port!=null&&!"".equals(port)){
ipPort = Integer.parseInt(port);
}
connection = new Connection(server,ipPort);
connection.connect();
boolean isAuthenticated = connection.authenticateWithPassword(username, password);
if (!isAuthenticated) {
throw new IOException("authentication failed");
}
sess = connection.openSession();
//send commands.
String command = "";
StringBuffer output = new StringBuffer();
command = "cd "+root+";egrep -l ~"+ sku_no+"~ "+fileName;
sess.execCommand(command);
stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr());
stdoutReader = new BufferedReader(
new InputStreamReader(stdout));
while (true) {
String line = stdoutReader.readLine();
if(line!=null&&!"null".equals(line)){
output.append(line);
}else if (line == null) {
break;
}
}
String fileExist = "N";
if ((output.indexOf(fileName) >=0) && (output.indexOf("egrep") == -1)) {
fileExist = "Y";
}
sess.close();
if("Y".equals(fileExist)){
sess = connection.openSession();
command = "cd "+root+";grep ~"+ sku_no+"~ "+fileName;
sess.execCommand(command);
stdout = new StreamGobbler(sess.getStdout());
stdoutReader = new BufferedReader( new InputStreamReader(stdout));
output.setLength(0);
while (true) {
String line = stdoutReader.readLine();
output.append(line);
if (line == null)
break;
}
StringTokenizer st = new StringTokenizer(output.toString(), "\n");
String tmp1 = "";
while (st.hasMoreTokens()) {
tmp1 = st.nextToken();
if ((tmp1.indexOf(String.valueOf(sku_no))>=0) && (tmp1.indexOf("grep") == -1)){
EDIFile = tmp1;
break;
}
}
}
} catch (Exception e) {
request.setAttribute("error", e);
throw e;
} finally {
if (EDIFile.equals("")){
request.setAttribute("error", "There is no EDI raw data for this sku!");
}
stdoutReader.close();
stdout.close();
sess.close();
connection.close();
}
return EDIFile;
}