這個主要實作java遠端通路伺服器的讀寫檔案操作,自動登入讀寫檔案,以上代碼整理來自網際網路,然後自己将很多瑣碎的東西整理在了一起
pom.xml要配置
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
檔案loginServer主要類中有個getProperties這個方法是配置伺服器的位址資訊的,需要先配置位址資訊然後調用login去做登入的操作 LoginServer.login(LoginServer.getProperties(Config.Alertkey1 + ".json"), false);
Config
package com.maxd.utils;
public class Config {
public static String hostname;
public static String username;
public static String password;
public static int port;
public static String sourcePath;
public static String destinationPath;
public static String writePath;
}
LoginServer:
package com.maxd.upload;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.StreamGobbler;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.maxd.utils.Config;
public class LoginServer {
/**
* @param ip 伺服器IP
* @param user 伺服器使用者名
* @param pwd 伺服器密碼
* @param port 端口
* @param privateKeyPath 可為空
* @param passphrase 可為空
* @param sourcePath 本地檔案路徑
* @param destinationPath 上傳路徑
*/
private static void downLoadFile(String ip, String user, String pwd, String port, String privateKeyPath, String passphrase, String sourcePath, String destinationPath) {
doWrite(ip, user, pwd, port, privateKeyPath, passphrase, sourcePath, destinationPath);
}
public static Properties getProperties(String fileName) {
Properties properties = new Properties();
properties.setProperty("ip", Config.hostname);
properties.setProperty("user", Config.username);
properties.setProperty("pwd", Config.password);
properties.setProperty("port", String.valueOf(Config.port));
properties.setProperty("sourcePath", Config.sourcePath + fileName);
properties.setProperty("destinationPath", Config.destinationPath);
return properties;
}
/**
* @param properties
* @param isRead true表示讀取 false表示寫入
*/
public static void login(Properties properties, boolean isRead) {
String ip = properties.getProperty("ip");
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
String port = properties.getProperty("port");
String privateKeyPath = properties.getProperty("privateKeyPath");
String passphrase = properties.getProperty("passphrase");
String sourcePath = properties.getProperty("sourcePath");
String destinationPath = properties.getProperty("destinationPath");
if (!isRead) {
//寫入本地檔案到遠端伺服器
doWrite(ip, user, pwd, port, privateKeyPath, passphrase, sourcePath, destinationPath);
} else {
//讀取遠端檔案到本地
readConnect();
}
}
/**
* @throws IOException
* @description 讀檔案
*/
public static String readTxtFile(File fileName) throws IOException {
String result = null;
FileReader fileReader = null;
BufferedReader bufferedReader = null;
fileReader = new FileReader(fileName);
InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName), "UTF-8");
BufferedReader bufferedReader1 = new BufferedReader(isr);
String read = null;
int count = 0;
while ((read = bufferedReader1.readLine()) != null) {
result = read + "\r\n";
count++;
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (fileReader != null) {
fileReader.close();
}
return result;
}
/**
* @throws UnsupportedEncodingException
* @throws IOException
* @description 寫檔案
*/
public static boolean writeTxtFile(String content, File fileName) throws UnsupportedEncodingException, IOException {
FileOutputStream o = null;
o = new FileOutputStream(fileName);
o.write(content.getBytes("UTF-8"));
o.close();
return true;
}
private static void doWrite(String ip, String user, String pwd, String port, String privateKeyPath, String passphrase, String sourcePath, String destinationPath) {
if (ip != null && !ip.equals("") && user != null && !user.equals("") && port != null && !port.equals("") && sourcePath != null && !sourcePath.equals("") && destinationPath != null && !destinationPath.equals("")) {
if (privateKeyPath != null && !privateKeyPath.equals("")) {
sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,
passphrase, sourcePath, destinationPath);
} else if (pwd != null && !pwd.equals("")) {
sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,
destinationPath);
} else {
Console console = System.console();
System.out.print("Enter password:");
char[] readPassword = console.readPassword();
sshSftp(ip, user, new String(readPassword),
Integer.parseInt(port), sourcePath, destinationPath);
}
} else {
System.out.println("請先設定配置檔案");
}
}
/**
* 密碼方式登入
*
* @param ip
* @param user
* @param psw
* @param port
* @param sPath
* @param dPath
*/
private static void sshSftp(String ip, String user, String psw, int port,
String sPath, String dPath) {
System.out.println("password login");
Session session = null;
JSch jsch = new JSch();
try {
if (port <= 0) {
// 連接配接伺服器,采用預設端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口連接配接伺服器
session = jsch.getSession(user, ip, port);
}
// 如果伺服器連接配接不上,則抛出異常
if (session == null) {
throw new Exception("session is null");
}
// 設定登陸主機的密碼
session.setPassword(psw);// 設定密碼
// 設定第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 設定登陸逾時時間
session.connect(300000);
UpLoadFile.upLoadFile(session, sPath, dPath);
//DownLoadFile.downLoadFile(session, sPath, dPath);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success");
}
/**
* 密匙方式登入
*
* @param ip
* @param user
* @param port
* @param privateKey
* @param passphrase
* @param sPath
* @param dPath
*/
private static void sshSftp2(String ip, String user, int port,
String privateKey, String passphrase, String sPath, String dPath) {
System.out.println("privateKey login");
Session session = null;
JSch jsch = new JSch();
try {
// 設定密鑰和密碼
// 支援密鑰的方式登陸,隻需在jsch.getSession之前設定一下密鑰的相關資訊就可以了
if (privateKey != null && !"".equals(privateKey)) {
if (passphrase != null && "".equals(passphrase)) {
// 設定帶密碼的密鑰
jsch.addIdentity(privateKey, passphrase);
} else {
// 設定不帶密碼的密鑰
jsch.addIdentity(privateKey);
}
}
if (port <= 0) {
// 連接配接伺服器,采用預設端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口連接配接伺服器
session = jsch.getSession(user, ip, port);
}
// 如果伺服器連接配接不上,則抛出異常
if (session == null) {
throw new Exception("session is null");
}
// 設定第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 設定登陸逾時時間
session.connect(300000);
UpLoadFile.upLoadFile(session, sPath, dPath);
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取遠端檔案到本地
*/
private static void readConnect() {
Connection conn = new Connection(Config.hostname, Config.port);
ch.ethz.ssh2.Session ssh = null;
try {
//連接配接到主機
conn.connect();
//使用使用者名和密碼校驗
boolean isconn = conn.authenticateWithPassword(Config.username, Config.password);
if (!isconn) {
System.out.println("使用者名稱或者是密碼不正确");
} else {
System.out.println("已經連接配接OK");
File folder = new File(Config.writePath);
if (!folder.exists()) {
folder.mkdir();
}
SCPClient clt = conn.createSCPClient();
ssh = conn.openSession();
ssh.execCommand("find /app/s3-configuration/ -name '*.json'");
InputStream is = new StreamGobbler(ssh.getStdout());
BufferedReader brs = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = brs.readLine();
if (line == null) {
break;
}
clt.get(line, Config.writePath);
List<File> lf = new ArrayList<File>();
lf = getFileList(new File(Config.writePath), "json");
for (File f : lf) {
/*System.out.println(f.getPath());*/
String path = f.getPath();
File file = new File(path);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s = null;
Pattern p = Pattern.compile(".*?error.*?");
while ((s = br.readLine()) != null) {
Matcher m = p.matcher(s);
if (m.find()) {
/*System.out.println(m.matches());*/
System.out.println(line);
System.out.println("find error!");
}/*else{
System.out.println("no error");
} */
}
br.close();
} catch (FileNotFoundException e) {
System.err.println("file not found");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("檔案輸出成功,請在" + Config.writePath + "中檢視");
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
//連接配接的Session和Connection對象都需要關閉
if (ssh != null) {
ssh.close();
}
if (conn != null) {
conn.close();
}
}
}
private static List<File> getFileList(File fileDir, String fileType) {
List<File> lfile = new ArrayList<File>();
File[] fs = fileDir.listFiles();
for (File f : fs) {
if (f.isFile()) {
if (fileType.equals(f.getName().substring(f.getName().lastIndexOf(".") + 1, f.getName().length())))
lfile.add(f);
} else {
List<File> ftemps = getFileList(f, fileType);
lfile.addAll(ftemps);
}
}
return lfile;
}
}
UpLoadFile
package com.maxd.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
public class UpLoadFile {
public static void upLoadFile(Session session, String sPath, String dPath) {
Channel channel = null;
try {
channel = (Channel) session.openChannel("sftp");
channel.connect(10000000);
ChannelSftp sftp = (ChannelSftp) channel;
try {
//上傳
sftp.cd(dPath);
Scanner scanner = new Scanner(System.in);
/* System.out.println(dPath + ":此目錄已存在,檔案可能會被覆寫!是否繼續y/n?");
String next = scanner.next();
if (!next.toLowerCase().equals("y")) {
return;
}*/
} catch (SftpException e) {
sftp.mkdir(dPath);
sftp.cd(dPath);
}
File file = new File(sPath);
copyFile(sftp, file, sftp.pwd());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
}
public static void copyFile(ChannelSftp sftp, File file, String pwd) {
if (file.isDirectory()) {
File[] list = file.listFiles();
try {
try {
String fileName = file.getName();
sftp.cd(pwd);
System.out.println("正在建立目錄:" + sftp.pwd() + "/" + fileName);
sftp.mkdir(fileName);
System.out.println("目錄建立成功:" + sftp.pwd() + "/" + fileName);
} catch (Exception e) {
// TODO: handle exception
}
pwd = pwd + "/" + file.getName();
try {
sftp.cd(file.getName());
} catch (SftpException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < list.length; i++) {
copyFile(sftp, list[i], pwd);
}
} else {
try {
sftp.cd(pwd);
} catch (SftpException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("正在複制檔案:" + file.getAbsolutePath());
InputStream instream = null;
OutputStream outstream = null;
try {
outstream = sftp.put(file.getName());
instream = new FileInputStream(file);
byte b[] = new byte[1024];
int n;
try {
while ((n = instream.read(b)) != -1) {
outstream.write(b, 0, n);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SftpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
outstream.flush();
outstream.close();
instream.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}