文件读取
package test;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author lw
* @createTime 2018/8/3 16:55
* @description 日志服务器
*/
public class LogSvr {
private long lastTimeFileSize = 0;
/**
* 实时读取指定文件的内容
* @param logFile
* @throws FileNotFoundException
*/
public void realtimeShowLog(File logFile) throws FileNotFoundException {
//指定文件可读可写
final RandomAccessFile randomAccessFile = new RandomAccessFile(logFile, "rw");
//启动一个线程每10秒钟读取新增的日志信息
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
try {
//获得变化部分的
randomAccessFile.seek(lastTimeFileSize);
String tmp = "";
while ( (tmp = randomAccessFile.readLine()) != null) {
// 输出文件内容
System.out.println(new String(tmp.getBytes("ISO8859-1")));
lastTimeFileSize = randomAccessFile.length();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 10, TimeUnit.SECONDS);
}
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String msgInfo = "this is a message";
/**
* 实时写入日志到指定文件
* @throws IOException
*/
public void writerLog() throws IOException {
final File logFile = new File("D:\\driver\\loadtest\\debug\\mock.log");
if(!logFile.exists()) {
logFile.createNewFile();
}
//启动一个线程每2秒钟向日志文件写一次数据
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new Runnable(){
public void run() {
try {
if(logFile == null) {
throw new IllegalStateException("logFile can not be null!");
}
Writer txtWriter = new FileWriter(logFile,true);
txtWriter.write(dateFormat.format(new Date()) +"\t"+ msgInfo +"\n");
txtWriter.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, 0, 2, TimeUnit.SECONDS);
}
public static void main(String[] args) throws Exception {
LogSvr view = new LogSvr();
view.writerLog();
final File tmpLogFile = new File("D:\\driver\\loadtest\\debug\\mock.log");
view.realtimeShowLog(tmpLogFile);
}
}
linux文件命令读取
package test;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Properties;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.letv.shop.et.service.impl.JmeterServiceImpl;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @author lw
* @createTime 2018/8/3 15:49
* @description ssh登陆主机 输入密码登陆并执行命令
*/
public class LinuxShh {
private static Logger logger = LogManager.getLogger(LinuxShh.class);
final static String userName = "root";// 用户名
final static String password = "76214489";// 密码
final static String host = "182.31.54.221";// 服务器地址
final static int port = 22;// 端口号
final static int timeout = 60000000;
/**
* <dependency>
* <groupId>com.jcraft</groupId>
* <artifactId>jsch</artifactId>
* <version>0.1.54</version>
* </dependency>
*/
public static void main(String[] args) throws JSchException, IOException {
JSch jsch = new JSch(); // 创建JSch对象
//String cmd = "vmstat 1 1";// 要运行的命令
String cmd = "uname -a && date && uptime && who && vmstat 1> /home/linux_shell/m/vmstat.txt";
Session session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象
session.setPassword(password); // 设置密码
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
String buf = "/home/linux_shell/m/vmstat.txt";
StringBuffer sb = new StringBuffer();
System.out.println("您的IP是:" + host);
logger.info("您的IP是:" + host);
System.out.println("以下是:系统资源信息:");
/*final File tmpLogFile = new File("/home/linux_shell/m/vmstat.txt");
LogSvr.realtimeShowLog(new File(String.valueOf(tmpLogFile)));*/
while ((buf = reader.readLine()) != null) {
sb.append(buf);
System.out.println(buf);// 打印控制台输出
}
reader.close();
channelExec.disconnect();
if (null != session) {
session.disconnect();
}
/* Process p = Runtime.getRuntime().exec("ls -al /");
InputStream inputStream = p.getInputStream();
OutputStream out = new FileOutputStream("/tmp/list.out");
byte[] b = new byte[1024];
int r;
while((r=inputStream.read(b))>-1)
out.write(b,0,r);
out.flush();
out.close();*/
/*
for (int i = 0; i < 10; i++) {
String res = exeCommand(host, port, userName, password, cmd);
System.out.println(res);
}*/
}
public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
session.setTimeout(timeout); // 设置timeout时间
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();
String out = IOUtils.toString(in, "UTF-8");
channelExec.disconnect();
session.disconnect();
return out;
}
}