工具类篇-05-往Linux服务器上传文件工具类
package others;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.apache.commons.net.ftp.*;
import java.io.*;
import java.util.Properties;
/**
* 向FTP服务器上传文件
*/
public class FTPUtil {
private static ChannelSftp sftp = null;
/**
* Description: 向FTP服务器上传文件
*
* @param host FTP服务器ip
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录,/home/ftpuser/images
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String host, int port, String username, String password, String basePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
File file = null;
try {
JSch jsch = new JSch();
//获取sshSession 账号-ip-端口
Session sshSession = jsch.getSession(username, host, port);
//添加密码
sshSession.setPassword(password);
Properties sshConfig = new Properties();
//严格主机密钥检查
sshConfig.put("StrictHostKeyChecking", "no");
//设置ssh的DH秘钥交换
sshSession.setConfig("kex", "diffie-hellman-group1-sha1");
//跳过Kerberos username 身份验证提示
sshSession.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
// ("PreferredAuthentications","publickey,keyboard-interactive,password");
sshSession.setConfig(sshConfig);
//开启sshSession链接
sshSession.connect();
//获取sftp通道
Channel channel = sshSession.openChannel("sftp");
//开启
channel.connect();
sftp = (ChannelSftp) channel;
file = new File(basePath);
//设置为被动模式
// ();
//设置上传文件的类型为二进制类型
//进入到要上传的目录 然后上传文件
sftp.cd(basePath);
sftp.put(input, filename);
input.close();
result = true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}
public static void main(String[] args) throws FileNotFoundException {
InputStream input = new FileInputStream("D:\\药企.txt");
String newName = "药企";
boolean t = uploadFile("192.168.72.153", 22, "root", "473791", "/usr/local/src/mysql", newName,
input);
System.out.println("t = " + t);
}
}