想在FTP中完成 命令cp功能


1.先从FTP的原目录下载到服务器本地目录, 再从服务器本地目录上传到ftp的目标目录,

2 直接让用户远程登录机器,调用cp命令

考虑到腾讯云的带宽费用原因,采用第二种方法

ganymed-ssh2-build210.jar

______________________________

String ip = yourip;
String username2 = yourusername;
String password = yourpassword;
RemoteCommand rcmd = new RemoteCommand(ip,username2,password);
if( rcmd.login())
{
String srcdirpath = "/chroot/mysftp01/upload/testSrcDir2";
String destdirpath = "/chroot/mysftp02/download";
cmd = "cp -r " + srcdirpath + " "+destdirpath;
System.out.println( cmd );
String resultStr = rcmd.execmd(cmd);
System.out.println(resultStr);
}
*********************************************
package com.jtxy.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class RemoteCommand {
private static Logger logger = LoggerFactory.getLogger(RemoteCommand.class);
private String DEFAULTCHARTSET = "UTF-8";
private Connection conn;
private String ip;
private String username;
private String password;
//用密码登录
public RemoteCommand(String ip,String username,String password){
this.ip = ip;
this.username = username;
this.password = password;
}
public Boolean login() {
boolean flag = false;
try {
conn = new Connection(ip);
conn.connect();
flag = conn.authenticateWithPassword(username, password);
if (flag) {
System.out.println("成功!");
} else {
System.out.println("失败!");
conn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public String execmd(String cmd)
{
String result = "";
try{
if (conn != null) {
Session session = conn.openSession();
session.execCommand(cmd);// 执行命令
result = processStdout(session.getStdout(), DEFAULTCHARTSET);
System.out.println(result);
conn.close();
session.close();
}
} catch (IOException e) {
System.out.println("执行命令失败,链接conn:" + conn + ",执行的命令:" + cmd + " " + e);
e.printStackTrace();
}
return result;
}

private String processStdout(InputStream in, String charset) {
InputStream stdout = new StreamGobbler(in);
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line + "\n");
System.out.println(line);
}
br.close();
} catch (UnsupportedEncodingException e) {
System.out.println("解析脚本出错:" + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.println("解析脚本出错:" + e.getMessage());
e.printStackTrace();
}
return buffer.toString();
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM