`
lovehibernate
  • 浏览: 4588 次
  • 性别: Icon_minigender_1
最近访客 更多访客>>
社区版块
存档分类
最新评论

做了一个简单的服务器监视程序。还有些问题没解决

阅读更多
服务器经常不堪重负挂掉,人工重启太麻烦。因此决定写一个自动监视服务器的东东,其中涉及到文件操作、动态编译并执行java文件、模拟Http提交、线程控制等东西。稍作修改也可以做成一个提醒程序。

/**
* This class define some functions to be executed.
* The class to be executed by AutoExec must content a main method.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;

import java.util.Date;
import java.text.SimpleDateFormat;

public class ExecuteJava implements Runnable
{
public boolean serverAlive(String host,int port,String ncFileName)
{
PostData pd=new PostData(host,port);
pd.myNC(ncFileName);
Date now=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeString=sdf.format(now);
//System.out.println(pd.getReceive());
if(pd.getReceive().indexOf("HTTP/1.1 200 OK")<0)
{
System.out.println("["+timeString+"] The server \""+host+"\" has been shutdown!");
return false;
}
else
{
System.out.println("["+timeString+"] The server \""+host+"\" is all right!");
System.out.println("I will see it latter...");
}
pd.close();
return true;
}

public void run()
{
serverAlive("www.c-gec.com",80,"f:\\nc.txt");
}

public static void main(String[] args)
{
System.out.println("=======================================================");
System.out.println("=               ServerStateWatcher V1.0               =");
System.out.println("=                   Code by Einstein                  =");
System.out.println("=             Email:zhuangEinstein@tom.com            =");
System.out.println("=======================================================");
String host="www.cnb2b.cn";
String ncFile="f:\\nc.txt";
int port=80;
ExecuteJava ej=new ExecuteJava();

if(!ej.serverAlive(host,port,ncFile))
{
int aliveNum=0;
for(int i=0;i<10;i++)
{//do this repeating to confirm the host is over....
if(ej.serverAlive(host,port,ncFile))aliveNum++;
if(aliveNum>2)break;
}
if(aliveNum<2)
{//do some reboot job when the server is not alive.
System.out.println("The server "+host+" may be shutdown so let's reboot it now!");
ExecuteFile ef=new ExecuteFile("rebootTomcat.bat");
ef.execute();
}
}
}
}


/**
* 执行外部命令或者外部文件
* @author Einstein
* Email: zhuangEinstein@tom.com
* 创建日期 2005-10-29
*/

package myJava;

import java.io.*;

public class ExecuteFile
{
private String cmd;
private String[] argv;
private String returnString="";

ExecuteFile()
{
this.cmd=null;
this.argv=null;
}

ExecuteFile(String command)
{
this.cmd=command;
}

ExecuteFile(String command,String[] argvs)
{
this.cmd=command;
this.argv=argvs;
}

public String[] getArgv() {
return argv;
}

public void setArgv(String[] argv) {
this.argv = argv;
}

public String getCmd() {
return cmd;
}

public void setCmd(String cmd) {
this.cmd = cmd;
}

public String getReturnString()
{
return returnString;
}

public boolean execute(String cmd,String[] argv)
{
try
{
this.setCmd(cmd);
this.setArgv(argv);
Process p=Runtime.getRuntime().exec("cmd /c "+this.cmd,this.argv);
InputStreamReader isr = new InputStreamReader(p.getInputStream());
LineNumberReader input = new LineNumberReader (isr);
String line = null;
this.returnString="";
            while ((line = input.readLine ()) != null)   
            {//捕获新进程的控制台输出,并作为返回结果存在returnString中
            returnString+=line+"\n";
            //System.out.println(line);
            }
return true;
}catch(Exception ex){return false;}
}

public boolean execute(String cmd)
{
try
{
this.setCmd(cmd);
this.execute(this.cmd,null);
return true;
}catch(Exception ex){return false;}
}

public boolean execute()
{
try
{
if(this.cmd!=null&&this.argv!=null)
{
return this.execute(this.cmd,this.argv);
}
else
{
return this.execute(this.cmd);
}
}catch(Exception ex){return false;}
}
}


/**
*  @(#)PostData.java  05/10/31
*/
package myJava;

import java.net.*;
import java.io.*;

/**
* This Class is a Data-Post class.It is use to
* send string data or byte data to a specify host whith specify port.
* @author Einstein
* Email: zhuangEinstein@tom.com
* Date: 2005-10-31
*/
public class PostData
{
private final int MAX_PORT=65535;
private int MAX_WAIT_TIME=20;//maxt time to wait for the socket receive data;depend on your net state.
private String host="127.0.0.1";
private String postContent="";
private int port=80;
private Socket socket=null;
boolean connected=false;
private String receive="";

/**
* The construction functions.
*/
PostData(){}

PostData(String host,int port)
{
if(port<0||port>MAX_PORT)
{
System.out.println("The port must be between 0 and 65535!");
return;
}
if(host==null||host.trim().equals(""))
{
System.out.println("The host name can't be null!");
return;
}
this.host=host;
this.port=port;
try
{
socket=new Socket(host,port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;
}
}

/**
* Set or get some parameters of this Object whose attribute is readable and writeable.
*/
public boolean isConnected() {
return connected;
}

public void setConnected(boolean connected) {
this.connected = connected;
}

public String getHost() {
return host;
}

public void setHost(String host) {
this.host = host;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public String getPostContent() {
return postContent;
}

public void setPostContent(String postContent) {
this.postContent = postContent;
}

public Socket getSocket() {
return socket;
}

public void setSocket(Socket socket) {
this.socket = socket;
}

public String getReceive() {
return receive;
}

/**
* Connect to the server after set parameters which are needed.
* Return true when success or false when fail.
* @return boolean
*/
public boolean connect()
{
return this.connect(this.host,this.port);
}

public boolean connect(String host,int port)
{
if(host!=null&&port>0)
{
this.host=host;
this.port=port;
try
{
socket=new Socket(this.host,this.port);
connected=true;
}
catch(Exception ex)
{
System.out.println("Can't connect to the server named \""+host+"\" and port "+port);
socket=null;this.host=null;this.port=0;connected=false;return false;
}
return true;
}
else
{
return false;
}
}

public boolean sendData(String content)
{
if(!this.connected||this.socket==null)
{
System.out.println("You can't send data before connect to a host!");
return false;
}
try
{
PrintWriter pout=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);
String[] sendContents=content.split("\\\\n\\\\r");
for(int i=0;i<sendContents.length;i++)
{
//System.out.println("==================>"+sendContents[i]);
pout.println(sendContents[i]);
}
}catch(Exception ex){this.close();return false;}
return true;
}

public boolean sendHttpData(String content)
{
try
{
//System.out.println("Begin to send Data!==================="+new java.util.Date().getTime());
if(sendData(content)&&sendData("")&&sendData(""))
{
socket.setSoTimeout(MAX_WAIT_TIME*1000);//Set the max time to wait for data receiving.
//System.out.println("Begin to receive Data!==================="+new java.util.Date().getTime());
BufferedReader bin=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while((msg=bin.readLine())!=null)
{
receive+=msg+"\n\r";
//System.out.println(msg+"<=================="+"\n");
}
//System.out.println("End to receive Data!==================="+new java.util.Date().getTime());
}
return true;
}catch(Exception ex){return false;}
}

public boolean myNC(String fileName)
{
String content="";
String sendData="";
MyFile mf=new MyFile(fileName);
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
sendData+=content+"\\n\\r";
}
return sendHttpData(sendData);
}

public boolean close()
{
if(this.socket!=null)
{
this.connected=false;
try
{
this.socket.close();
}catch(Exception ex){System.out.println("Close socket Exception!");return false;}
this.socket=null;
return true;
}
return false;
}


}


/**
* This class is used to automatic execute some commands.
* Including normal shell commands , java files and java classes.
* It can be used to do some repetitive job.
* @author Einstein
* Create date 2005-11-1
*/
package myJava;

import java.lang.Runnable;
import java.lang.reflect.*;

public class AutoExec implements Runnable
{
//Command or java file to execute.
private String command="";

//Mode COMMAND_MODE is to execute command,including executable files.
private final int COMMAND_MODE=0;

//Mode FILE_MODE is to execute java files.
private final int FILE_MODE=1;

private final int CLASS_MODE=2;

//Time between tow commands.
private long sleepSeconds=1000*1;

private long executeTimes=0;

private int execMode=COMMAND_MODE;

private ExecuteFile executer=new ExecuteFile();

/**
* The package of the class which will be executed.
*/
private String javaPackage="myJava";

/**
* The class_path of this file(AutoExec.java).
* You can change it by the set method when it needed.
*/
private String ownClassPath="E:\\myHibernate\\class\\";

AutoExec()
{}

AutoExec(String cmd)
{
this(cmd,0);
}

AutoExec(String cmd,long seconds)
{
if(cmd!=null)
{
this.command=cmd;
executer.setCmd(cmd);
}
if(seconds>0)this.sleepSeconds=seconds*1000;
}


public String getJavaPackage()
{
return javaPackage;
}

public void setJavaPackage(String javaPackage)
{
this.javaPackage = javaPackage;
}

public String getOwnClassPath()
{
return ownClassPath;
}

public void setOwnClassPath(String ownClassPath)
{
this.ownClassPath = ownClassPath;
}

public int getExecMode()
{
return execMode;
}

public void setExecMode(int md)
{
this.execMode = md;
}

public long getExecuteTimes()
{
return executeTimes;
}

public void setExecuteTimes(long executeTimes)
{
this.executeTimes = executeTimes;
}

public String getCommand()
{
return command;
}

public void setCommand(String command)
{
this.command = command;
}

public ExecuteFile getExecuter()
{
return executer;
}

public void setExecuter(ExecuteFile executer)
{
this.executer = executer;
}

public long getSleepSeconds()
{
return sleepSeconds/1000;
}

public void setSleepSeconds(long sleepSeconds)
{
this.sleepSeconds = sleepSeconds*1000;
}

public void run()
{
if(this.execMode==COMMAND_MODE)
{
executer.execute(this.command);
System.out.println(executer.getReturnString());
}
else if(execMode==FILE_MODE)
{
executeJavaFile(this.command);
}
else if(execMode==CLASS_MODE)
{//Execute class
this.executeClass(this.command);
}
else
{
System.out.println("No mode is setted!");
System.exit(0);
}
}

public boolean execute()
{
if(this.command==null)
{
System.out.println("No command to execute!!");
return false;
}
if(this.executer==null)
{
System.out.println("Executer is not valid!");
return false;
}
AutoExec ae=new AutoExec();//ae is a new object so it must be initialized before use it.
ae.setJavaPackage(this.javaPackage);
ae.setOwnClassPath(this.ownClassPath);
ae.setCommand(this.command);
ae.setExecMode(this.getExecMode());
Thread thd=new Thread(ae);
long i=0;
try
{
if(this.getExecuteTimes()>0)
{
while(i++<this.executeTimes)
{
System.out.println("[cmd/file]"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
else
{
while(true)
{
System.out.println("[cmd/file]:"+this.getCommand());
thd.start();
if(this.getSleepSeconds()>0)
{
System.out.println("Sleep for "+sleepSeconds/1000+" seconds!");
thd.sleep(this.sleepSeconds);
}
try
{
if(!thd.isAlive())
{
thd.stop();
System.out.println("Stop the thread successful!");
}
else
{
thd.join(10000);
}
}catch(Exception ex){}
thd=null;
thd=new Thread(ae);
}
}
}catch(Exception ex){System.out.println("Error when execute thread"+i);return false;}
return true;
}

/**
* Execute a java file.
* @param fileName
* @return
*/
public boolean executeJavaFile(String fileName)
{
if(fileName==null||fileName.toLowerCase().indexOf(".java")!=fileName.length()-5)
{
System.out.println("Only java files can be executed!");
return false;
}
com.sun.tools.javac.Main javac=new com.sun.tools.javac.Main();
String[] args=new String[]{"-d",ownClassPath,fileName};
String className=fileName.substring(fileName.lastIndexOf("\\")+1,fileName.length()-5);
//System.out.println("Begin to execute file: "+fileName+" whose class Name is:"+className);
try
{
int status=javac.compile(args);
if(status!=0)
{
System.out.println("Some error occurs in the java file: "+fileName);
return false;
}
return executeClass(this.javaPackage+"."+className);

}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("Fail to execute java file named \""+fileName+"\"!");return false;
}
}

/**
* Execute a java class file ,be sure that the class is executable.
* @param className The name of the class to be executed,including the package and class name.
* @return
*/
public boolean executeClass(String className)
{
try
{
Class cls=Class.forName(className);
if(cls!=null)
{
Method main = cls.getMethod("main", new Class[] { String[].class });
main.invoke(null,new Object[]{ new String[0]});
}
else
{
System.out.println("The main method is not found!");
return false;
}
return true;
}catch(Exception ex){ex.printStackTrace();System.out.println("Fail to execute class named \""+className+"\"!");return false;}
}
}




/**
* @author Einstein
* Email: zhuangEinstein@tom.com
* Create date: 2005-10-29
*/
package myJava;

public class Test
{
public static void main(String[] argv)
{
/**
* 自动执行测试
*/
AutoExec ae=new AutoExec();
ae.setCommand("myJava.ExecuteJava");
ae.setExecMode(2);
ae.setSleepSeconds(300);
ae.setExecuteTimes(0);
ae.execute();
/**
* 发送数据测试

PostData pd=new PostData("www.sohu.com",80);
pd.myNC("f:\\nc.txt");
System.out.println(pd.getReceive());
pd.close();
/**
* 文件操作测试
*/
/*
String content="";
MyFile mf=new MyFile("f:\\nc.txt");
int i=0;
while(!(content=mf.readLine()).equals("<$文件末尾$>"))
{
System.out.println(content);
}
System.out.println(content+mf.getFilePointer());
*/
/**
* 执行外部命令测试

ExecuteFile exec=new ExecuteFile("shutdown -a");
if(exec.execute(exec.getCmd()))
{
System.out.println("执行成功!");
}
else
{
System.out.println("执行失败,请确定该文件存在!");
}
System.out.println(exec.getReturnString());
*/
}
}
分享到:
评论

相关推荐

    定时监视exe程序运行状态,可对监视exe程序进行关闭重启,定时重启exe程序

    6. **安全性**:虽然这里未提及,但一个好的exe监控工具还需要考虑安全因素,如防止恶意程序利用监控机制,以及确保操作权限的合理控制。 在实际应用中,这样的工具可以广泛应用于服务器管理、无人值守的自动工作流...

    一个OPC客户端监视程序

    "一个OPC客户端监视程序"是一个专门设计用于监测OPC服务器的数据接口,以及查看相关组和项信息的应用程序。 在OPC架构中,客户端是连接到OPC服务器并请求数据或服务的程序。这个监视程序作为一个OPC客户端,它的...

    服务器状态监视工具

    通常,这样的程序会有一个直观的用户界面,展示服务器的关键指标,并可能支持定制警报阈值,当服务器状态超出预设范围时,自动发送通知。 "监视.ini"文件很可能是配置文件,用于存储用户的设置和监控参数。用户可以...

    程序监视器

    总的来说,"程序监视器"是一个强大的工具,它通过智能监控和自动化处理,解决了服务类软件因故障导致的中断问题,极大地提高了系统的可用性和可靠性。在日常IT运维中,合理使用这类工具能有效降低故障率,提升服务...

    本地服务器监视器

    "本地服务器监视器"和"loadrunner"虽然用途不同,但都服务于同一个目标:确保服务器健康、高效地运行。Monitorix适用于日常监控,提供实时数据,而LoadRunner则用于压力测试,预测系统在高负载下的行为。结合两者,...

    服务器监视器 Ver2.0[ServerMonitor2.rar]-精品源代码

    【服务器监视器 Ver2.0】是一个用于实时监控服务器运行状态的应用程序,它包含了多个关键模块,以确保全面且高效地收集和分析服务器的各种性能数据。这个【源代码】提供了宝贵的资源,对于开发者来说,可以深入理解...

    ServerLoadChecker服务器负载监视器

    在IT行业中,服务器负载监视是维护系统健康的关键环节,它可以帮助管理员及时发现并解决可能导致服务中断的问题。下面将详细介绍ServerLoadChecker的相关知识点。 一、服务器负载监控的重要性 1. 预防过载:通过...

    Node.js-uptimey是一个开源的服务器正常运行时间监视器

    `uptimey` 是一个基于 `Node.js` 的开源服务器正常运行时间监视器,专为跟踪和确保服务的高可用性而设计。它允许开发者轻松地监控他们的服务器和应用程序,确保在出现故障时能够及时收到警报,从而提高系统的稳定性...

    soft_服务器监视 MyIIS.Monitor(附瞬时流量显示).zip.zip

    【描述解析】:描述部分与标题相同,"soft_服务器监视 MyIIS.Monitor(附瞬时流量显示).zip.zip",没有提供额外的信息,但我们可以推断该软件可能是一个用于IIS(Internet Information Services)服务器的性能监控...

    NetMeter流量监视器(服务器专用版)

    NetMeter流量监视器是一款专为服务器设计的网络监控工具,其主要功能是实时监测和分析网络数据流量。在服务器管理中,对网络流量的监控至关重要,因为它可以帮助管理员了解服务器的网络使用情况,预防网络拥塞,及时...

    目录监视器源码(vs2005 win程序)

    FileSystemWatcher类提供了一个方便的方式来监视文件系统更改,如文件或目录的创建、修改、删除等事件。通过创建FileSystemWatcher对象,并设置其属性,如需要监视的目录路径、过滤特定类型的文件,我们可以实现定制...

    MySQL监视器监视数据库动态

    MySQL监视器是数据库管理系统中一个至关重要的工具,它允许管理员实时跟踪和分析MySQL数据库的运行状态,以便优化性能、诊断问题以及确保数据的安全性。在本文中,我们将深入探讨MySQL监视器的功能、重要性以及如何...

    解决SQL数据库程序挂起问题

    标题中的“解决SQL数据库程序挂起问题”是一个典型的IT故障排查和修复场景,涉及到SQL数据库的运行状态和系统性能优化。挂起通常意味着程序或进程处于非响应状态,可能由于资源耗尽、死锁、错误的查询执行计划、内存...

    开源智慧农场数据实时监视程序(实时控制)1

    SIoT平台提供了一个完整的iot解决方案,包括数据采集、处理、存储、分析和可视化等功能。SIoT平台支持多种协议,包括MQTT、CoAP、HTTP等。 知识点3:Python编程 该程序使用Python语言进行开发。Python是一种高级...

    文件监视程序源码FileMonitorSource.zip

    总结来说,这个“文件监视程序源码FileMonitorSource”是一个基于Windows COM接口的文件监控解决方案,它利用了COM的特性实现了跨进程通信,并通过系统API监听文件系统的变更。通过深入学习和理解这些源码,开发者...

    JavaScript_监视nodejs应用程序中的任何更改,并自动重新启动服务器,非常适合开发.zip

    在Node.js应用的开发过程中,"JavaScript_监视nodejs应用程序中的任何更改,并自动重新启动服务器,非常适合开发.zip"这个主题恰好解决了开发者在持续开发过程中的一个痛点。 在传统的开发环境中,每当修改了Node....

    进程监视进程守护

    在操作系统中,进程是程序执行时的一个实例,每个进程都有自己的内存空间和系统资源。进程间相互独立,可以并发执行,是操作系统实现多任务的基础。 "监视进程"是指对系统中运行的进程进行实时监测,包括进程的状态...

    刀片服务器HS21问题确定与维护指南

    IBM刀片服务器HS21是一...总之,IBM刀片服务器HS21问题确定与维护指南为维护人员提供了一套完整的参考工具,通过这个指南,维护人员可以有效地识别和解决刀片服务器可能出现的各种问题,确保服务器能够高效稳定地运行。

    网络游戏-用于加强跟踪和或监视通信网络的方法、装置、程序和计算机程序产品.zip

    在现代信息技术领域,网络游戏已经成为一个不可或缺的组成部分,它不仅提供了娱乐和社交的平台,还涉及到大量的数据传输和处理。本文将深入探讨标题“网络游戏-用于加强跟踪和或监视通信网络的方法、装置、程序和...

    1600W监视软件

    总的来说,“1600W监视软件”可能是一个全面的IT运维工具,旨在提升系统的稳定性和效率。要更深入地了解这款软件,我们需要更多的详细信息,如其具体功能、使用场景、操作界面和用户评价等。不过,上述内容已经涵盖...

Global site tag (gtag.js) - Google Analytics