packagetestFrame;importjava.awt.Color;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.HashMap;importjava.util.Map;importjava.util.Scanner;importjava.util.Timer;importjavax.swing.BorderFactory;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;//服务器
public class testMain extendsJFrame{private static final long serialVersionUID = 1L;private static String logAddr = "";private static String logImageAddr = "";private static SimpleDateFormat sdfymd = new SimpleDateFormat("yyyy-MM-dd");private static SimpleDateFormat sdfymdhm = new SimpleDateFormat("yyyy-MM-dd HH:mm");private static SimpleDateFormat sdfymdhms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");private static String curLogAddr = "";final String LOOPBACK_ADDRESS = "127.0.0.1";private staticDataOutputStream out;private staticDataInputStream in;private staticSocket CurSocket;private staticString ServiceIp;private staticInteger ServicePort;private static Map socketList = new HashMap(); //客户端集合信息
private static FileOutputStream fout = null;private static byte[] inputByte = null;private staticTimer timer;public static void main(String[] args) throwsIOException {
Date d= newDate();
String logDateFile=sdfymd.format(d);
String curAddr= System.getProperty("user.dir");//String configAddr = curAddr+"\\mainConfig.txt";//exe执行时路径
String configAddr = curAddr+"\\src\\config\\mainConfig.txt"; //ide工具执行路径
String[] text=getFile(configAddr);for(String con : text) {if("logAddr".equals(con.substring(0, con.indexOf("=")))){
logAddr= con.substring(con.indexOf("=")+1, con.length());
judeDirExists(new File(con.substring(con.indexOf("=")+1, con.length())));
}else if("logImageAddr".equals(con.substring(0, con.indexOf("=")))){
logImageAddr= con.substring(con.indexOf("=")+1, con.length());
judeDirExists(new File(con.substring(con.indexOf("=")+1, con.length())));
}else if("ServiceIp".equals(con.substring(0, con.indexOf("=")))){
ServiceIp= con.substring(con.indexOf("=")+1, con.length());
}else if("ServicePort".equals(con.substring(0, con.indexOf("=")))){
ServicePort= Integer.parseInt(con.substring(con.indexOf("=")+1, con.length()));
}
}
curLogAddr= logAddr+"\\unitTest_"+logDateFile+".log";
judeFileExists(newFile(curLogAddr));
FileWriter fw= new FileWriter(curLogAddr,true);
PrintWriter pw= newPrintWriter(fw);if(!"".equals(logAddr)||!"".equals(logImageAddr)||!"".equals(ServiceIp)||!"".equals(ServicePort)){
pw.write(sdfymdhms.format(new Date())+": 启动成功!\r\n");
pw.flush();
fw.flush();
pw.close();
fw.close();
testMain myFrame= newtestMain();
myFrame.setVisible(true);
myFrame.setTitle("自动开关机工具");
myFrame.setResizable(false);
newService();
}else{
pw.write(sdfymdhms.format(new Date())+": 启动失败,mainConfig.txt配置文件异常!\r\n");
pw.flush();
fw.flush();
pw.close();
fw.close();
}
}public testMain() throwsIOException{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭,当关闭窗口时,程序即结束
setBounds(100, 100, 600, 360);//设置窗口坐标和大小
setLocationRelativeTo(null);//窗口居中
Font fontStyle = new Font(Font.DIALOG,Font.BOLD, 18);
Font fontConton= new Font(Font.DIALOG,Font.LAYOUT_NO_LIMIT_CONTEXT, 18);
JPanel panel= newJPanel();
JLabel label= new JLabel("IP地址:");
label.setFont(fontStyle);
panel.add(label);final JTextArea IpArea = new JTextArea(10, 35);
IpArea.setLineWrap(true);
IpArea.setFont(fontConton);
JScrollPane IpPane=newJScrollPane(IpArea);
IpPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.add(IpPane);
JLabel labela= new JLabel("重启效率:");
labela.setFont(fontStyle);
panel.add(labela);final JTextArea DateArea = new JTextArea(1, 3);
DateArea.setLineWrap(false);
DateArea.setBorder(BorderFactory.createLineBorder(Color.black,1));
DateArea.setFont(fontConton);
panel.add(DateArea);
JLabel labeb= new JLabel("(分钟/每次) ");
labeb.setFont(fontStyle);
panel.add(labeb);final JLabel labec = new JLabel("");
JButton btn= new JButton("发送");
btn.setFont(fontStyle);
btn.addActionListener(newActionListener() {
@Overridepublic voidactionPerformed(ActionEvent e) {if(DateArea.getText().isEmpty()||IpArea.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "请输入IP地址和重启效率");
}else{try{
timerFunction(DateArea.getText(),IpArea.getText(),labec);
}catch(IOException e1) {
e1.printStackTrace();
}
}
}
});
panel.add(btn);
labec.setFont(fontStyle);
labec.setForeground(Color.red);
panel.add(labec);this.setContentPane(panel);this.addWindowListener(newWindowAdapter() {
@Overridepublic voidwindowClosing(WindowEvent e){
FileWriter fw= null;try{
fw= new FileWriter(curLogAddr,true);
}catch(IOException e1) {
e1.printStackTrace();
}
PrintWriter pw= newPrintWriter(fw);
pw.write(sdfymdhms.format(new Date())+": 关闭成功!\r\n");try{
pw.flush();
fw.flush();
pw.close();
fw.close();
}catch(IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
}public static void timerFunction(final String timeSize,final String iptext,final JLabel labec) throwsIOException{final int timecount =Integer.parseInt(timeSize);if(timer!=null){
timer.cancel();
}
timer= newTimer();
timer.schedule(newjava.util.TimerTask() {public voidrun() {
timeFunctionContion(iptext,labec);
}
},0, timecount*60*1000);
}public staticString[] getFile(String realpath) {
Scanner scanner= null;
String[] text= new String[4];int i = 0;try{
File file= newFile(realpath);
scanner= newScanner(file);
}catch(FileNotFoundException e) {
e.printStackTrace();
}if(scanner!=null){while(scanner.hasNextLine()){
text[i]=scanner.nextLine();
i++;
}
scanner.close();
}returntext;
}//校验IP
public static booleanipCheck(String text) {if (text != null && !text.isEmpty()) {//定义正则表达式
String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";//判断ip地址是否与正则表达式匹配
if(text.matches(regex)) {return true;
}else{return false;
}
}return false;
}//判断文件夹是否存在
public static voidjudeDirExists(File file) {if (!file.exists()) {
file.mkdir();
}
}//判断文件是否存在
public static voidjudeFileExists(File file) {if (!file.exists()) {try{
file.createNewFile();
}catch(Exception e) {
e.printStackTrace();
}
}
}//通过IP地址获取MAC地址
public static String getMACAddress(String ip) throwsException {
String macAddress= "";try{
String cmd= "ping " +ip;
String ret=callCmd(cmd);if(ret!=null &&!"".equals(ret)){//判断IP地址是否存在
cmd = "nbtstat -a " +ip;
macAddress=callCmdMAC(cmd);
}
}catch(IOException e) {
e.printStackTrace();
}returnmacAddress;
}//获取MAC地址
public static String callCmdMAC(String cmd) throwsIOException{
Process p=Runtime.getRuntime().exec(cmd);
InputStreamReader isr= new InputStreamReader(p.getInputStream(),"GB2312");
BufferedReader br= newBufferedReader(isr);
String line="";int startIndex = 0;while ((line = br.readLine()) != null) {
startIndex= line.indexOf("MAC 地址");if(startIndex>0){
line= line.substring(startIndex+8, line.length()).trim().toUpperCase();break;
}
}
br.close();returnline;
}//创建服务器端
public static String callCmd(String cmd) throwsIOException{
Process p=Runtime.getRuntime().exec(cmd);
InputStreamReader isr= newInputStreamReader(p.getInputStream());
BufferedReader br= newBufferedReader(isr);
String line="";
String ret="";while ((line = br.readLine()) != null) {if (line != null) {
ret=line;
}
}
br.close();returnret;
}//创建服务器端
public static void newService() throwsIOException{
ServerSocket serverSocket=newServerSocket(ServicePort);while(true){
Socket sk= serverSocket.accept(); //当有客户端连接时,产生阻塞
socketList.put(sk.getInetAddress().toString(), sk);
FileWriter fw= new FileWriter(curLogAddr,true);
PrintWriter pw= newPrintWriter(fw);
pw.write(sdfymdhms.format(new Date())+": 新的客户端连接!"+sk.getInetAddress()+":"+sk.getPort()+"\r\n");
System.out.println("新的客户端连接"+sk.getInetAddress()+":"+sk.getPort());
pw.flush();
fw.flush();
pw.close();
fw.close();
}
}public static voidtimeFunctionContion(String iptext,JLabel labec){
FileWriter fw= null;try{
fw= new FileWriter(curLogAddr,true);
}catch(IOException e) {
e.printStackTrace();
}
PrintWriter pw= newPrintWriter(fw);
Date d= newDate();
String dateNowStr=sdfymdhm.format(d);
labec.setText("发送成功,上次发送时间"+dateNowStr);
String[] iplist= iptext.split(",");for(String ip : iplist) {if(ipCheck(ip)){try{
CurSocket= socketList.get("/"+ip);
out=new DataOutputStream(CurSocket.getOutputStream()); //信息接发流
out.writeUTF("shutdown -r -t 20");
in= newDataInputStream(CurSocket.getInputStream());
String curIPImgAddFol= logImageAddr+"\\"+ip;
judeDirExists(newFile(curIPImgAddFol));
fout= new FileOutputStream(new File(curIPImgAddFol+"\\"+in.readUTF()));
inputByte= new byte[1024];int length = 0;while (true) {if (in != null) {
length= in.read(inputByte, 0, inputByte.length);
}if (length == -1) {break;
}
fout.write(inputByte,0, length);
fout.flush();
}
pw.write(sdfymdhms.format(new Date())+": "+ip+"重启成功\r\n");
fout.close();
}catch(Exception e) {
e.printStackTrace();
}
}else{
pw.write(sdfymdhms.format(new Date())+": "+ip+" 地址不合法!\r\n");
}
}try{
fw.flush();
pw.close();
fw.close();
pw.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
}