`
lovehibernate
  • 浏览: 4539 次
  • 性别: 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());
*/
}
}
分享到:
评论

相关推荐

    MCStatus:Android应用程序,用于监视Minecraft服务器的状态

    Android应用程序,用于监视Minecraft服务器的状态 如果要将MinecraftServer类包含在其他内容中以用于查询服务器,则可以将其单独使用。 尽管不是直接端口,但是大部分过程都来自 。 我之所以写这篇文章是因为,尽管...

    X服务器虚拟化整合解决方案.pptx

    X86服务器虚拟化整合的效果 35%-75% TCO 节省 通过将整合多个物理服务器到一个物理服务器降低40%软件硬件成本 每个服务器的平均利用率从7%提高到60%-80% 降低70-80%运营成本, 包括数据中心空间、机柜、网线,...

    远程服务器剪贴板修复工具

    远程服务器用远程桌面连接进去,经常复制文本,不能在本地计算机桌面粘贴出来,是服务器里的的剪贴板rdpclip.exe程序出现了问题,这个小工具,直接双击,可以对rdpclip.exe进行重启,解决你的烦恼。

    基于 SIMATIC NET OPC 报警和事件服务器的独立信息发送系统

    国际通用的 OPC Alarm & Events 标准支持在一个 Windows 应用程序中方便地访问过程消息并监视和处理来自不同制造商系统的消息。将演示如何基于 SIMATIC OPC Alarm & Events 并结合 SIMATIC S7 站实现一个简单、单独...

    VSIP服务器虚拟化解决方案.pptx

    VSIP服务器虚拟化技术 VSIP系统提供基于Linux内核的KVM(Kernel-based Virtual Machine)虚拟机,通过软硬件模拟具有完整硬件系统功能的、运行在一个完全隔离环境中的完整计算机系统,把一台X86物理服务器虚拟成...

    stagemonitor:Java服务器应用程序的应用程序性能监视的开源解决方案

    Stagemonitor是一个Java监视代理,它与时间序列数据库(例如Elasticsearch,Graphite和InfluxDB)紧密集成,以分析图形化指标,而用于分析请求和调用堆栈。 它包括可以自定义的预配置Grafana和Kibana仪表板。 更多...

    Mancy:Mancy是一个文件监视程序,支持通过sshsftp将更改自动上传到远程服务器

    Mancy是文件监视程序,并且支持通过ssh / sftp将更改自动上传到远程服务器。 我开始了这个学习golang的项目,并解决了我们开发环境中的一些问题。 用法 去获取github.com/rootrl/Mancy 去建造 运行“ Mancy”或“ ...

    Java-Web服务器(应用服务器).doc

    它包含了编写、运行和监视全天候的工业强度的随需应变 Web 应用程序和跨平台、跨产品解决方案所需要的整个中间件基础设施,如服务器、服务和 工具。WebSphere 提供了可靠、灵活和健壮的集成软件。 JBOSS、 JBoss是一...

    WFetch 1.4是免费实用程序上提供一个作为是基础 " - "。 Microsoft 不支持工具, 但您可以使用它来提供客户端和服务器之间通信详细信息。

    WFetch 是免费实用程序上提供一个作为是基础 " - "。 Microsoft 不支持工具, 但您可以使用它来提供客户端和服务器之间通信详细信息。 警告 此工具提供高级功能可允许用户公开服务器以潜在安全风险。 由于这个原因,...

    opc服务器.doc

    2、楼控解决方案用户 3、工控解决方案厂商 4、楼控解决方案厂商 5、工控解决方案集成商 6、楼控解决方案集成商 7、 All Automation Fields OPC是为了连接数据源(OPC服务器)和数据的使用者(OPC应用程序)之间的软件...

    企业内部的DNS服务器构建.docx

    四、调试过程中出现的问题及相应解决办法 出现的问题 尽管DNS允许在不改变友好名称的情况下更改IP地址,但是DNS服务器总难免有难以获取更新的时候,或仅仅是更新晚了。另外,可能你本地系统使用的是一个被缓存的...

    Vuls漏洞扫描器扫描程序

    对于系统管理员来说,每天必须执行安全漏洞分析和软件更新都是一个负担。为避免生产环境宕机,系统管理员通常选择不使用软件包管理器提供的自动更新选项,而是手动执行更新。这会导致以下问题: 1、系统管理员必须...

    Jprofile简介

    在这篇文章中,我使用比较通用的工具( JProfiler 和 JBuilder )和设备创建了一个性能监控分析环境,跟踪本地和远程的服务器程序,专注于三个性能问题:内存、垃圾回收和多线程运行状况,从而很好的监视 JVM 运行...

    IIS6.0 IIS,互联网信息服务

    一个IP地址对应多个Web站点 当按上步的方法建立好所有的Web站点后,对于做虚拟主机,可以通过给各Web站点设不同的端口号来实现,比如给一个Web站点设为80,一个设为81,一个设为82……,则对于端口号是80的Web站点,...

    Sentry:跨平台应用程序监视和错误跟踪软件-开源

    Sentry是一个跨平台,自托管的错误监视解决方案,可帮助软件团队实时发现,监视和修复错误。 线索最多的是用户和日志,而Sentry提供了答案。 Sentry通过载满信息的堆栈跟踪提供了增强的应用程序性能监视。 通过在一...

    node-site-monitor:Node.JS应用程序,用于监视网站并在网站关闭时发出警报

    一个简单的节点服务器,它将检查任何数量的网站的状态并以不同的方式警告任何数量的用户。 为什么这样做? 好吧,我们想要一个免费的分布式系统来监视我们的网站。 我们可以使用各种免费的节点托管解决方案轻松地...

    Minetrack:Minetrack可让您轻松监视自己喜欢的Minecraft服务器

    拉取请求将被审核和合并(如果被接受),但是在社区成员提供的修复程序之外,问题可能不会得到解决。 请分享您所做的任何改进或修正,以便所有人都可以从中受益。 产品特点 :rocket: 具有可自定义的更新速度的实时...

    ApexSQL_BI_Monitor_Pro_Edition_v2018.07.0382.rar

    ApexSQL BI Monitor Professional Edition是一个令人印象深刻的应用程序,它允许用户监控和跟踪工具设计和开发的SQL Server DBA。它包含了广泛的工具和功能,使这个应用程序成为开发人员和后端用户的简单和完整的...

    mariadb10.0.15

    MONyog能够帮助你监视和管理MySQL服务器,发现并修复MySQL数据库应用程序,在出现问题或中断前找到并解决问题!可以帮助你对MySQL的dbas管理更多MySQL服务器,调整其目前的MySQL服务器,在有严重的问题或中断之前...

    DBMailPro-邮件服务器.zip

    遥志软件改变传统邮件服务器软件基于文件结构的存储方式,采用易检索、高速度、数据备份、安全性和灵活性上更具效率的数据库做为存储目标,开发出一套完全基于数据库存储的邮件服务器软件,以适应日新月异的数字存储...

Global site tag (gtag.js) - Google Analytics