java远程开关机

JAVA学习网 2018-12-21 11:38:02

最近,很多客户向我们反馈终端启动后异常的问题,因此,我自己做了一个远程开关的小工具,该工具的目的在于通过批量的方式来控制终端启动。其设计逻辑是通过服务端发送cmd指令 ,客户端接受并执行指令,把结果返回给服务端。

1.客户端

package testSocket;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

//客户端
public class Kehu {
    private static String ServiceIp;
    private static Integer ServicePort;
    private static String imageFormat = "jpg"; //图像文件的格式
    private static Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    private static SimpleDateFormat sdfymdhm = new SimpleDateFormat("yyyyMMddHHmm");
    private static Socket socket;
    private static DataInputStream in;
    private static DataOutputStream out;
    
    @SuppressWarnings("static-access")
    public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
        JFrame a = new JFrame();
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭,当关闭窗口时,程序即结束
        a.setBounds(100, 100, 300, 200);//设置窗口坐标和大小
        a.setLocationRelativeTo(null);//窗口居中
        a.setVisible(true);
        a.setTitle("客户端");
        a.setResizable(false);
        
        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("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()));
            }
        }        
        while(true){
            socket = new Socket(ServiceIp,ServicePort);
            in = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
            String s = "";
            try {
                s = in.readUTF();
            } catch (Exception e) {
                while(true){
                    try {
                        socket = new Socket(ServiceIp,ServicePort);
                        in = new DataInputStream(socket.getInputStream());
                        out = new DataOutputStream(socket.getOutputStream());
                    } catch (Exception e2) {
                        e.printStackTrace();
                        Thread.currentThread().sleep(1000*60*5);
                    } finally{                        
                        if(socket!=null){
                            break;
                        }
                    }    
                }    
            }            
            snapShot(curAddr,out);
            out.close();
            in.close();            
            socket.close();
            callCmd(s);            
        }
    }
    
    public  static String[] getFile(String realpath) {
       Scanner scanner = null;
       String[] text = new String[4];
       int i = 0;
       try {    
           File file= new File(realpath);
           scanner = new Scanner(file);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       if(scanner!=null){
       while(scanner.hasNextLine()){
           text[i]= scanner.nextLine();
           i++;
       }
           scanner.close();
       }
       return text;
   }
    
   public static void snapShot(String addr,DataOutputStream outs) {
        try {
            //拷贝屏幕到一个BufferedImage对象screenshot
            BufferedImage screenshot = (new Robot()).createScreenCapture(new Rectangle(0, 0,(int) d.getWidth(), (int) d.getHeight()));
            //根据文件前缀变量和文件格式变量,自动生成文件名
            String name = addr+"\\"+sdfymdhm.format(new Date())+".jpg";
            File f = new File(name);
            ImageIO.write(screenshot, imageFormat, f);
            FileInputStream fin = new FileInputStream(f);
            byte[] sendByte = new byte[1024];
            outs.writeUTF(f.getName());
            int length = 0;
            while((length = fin.read(sendByte, 0, sendByte.length))>0){
                outs.write(sendByte,0,length);
                outs.flush();
            }
            fin.close();
            f.delete();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
   
   //执行CMD命令
   public static void callCmd(String cmd) throws IOException{
       Runtime.getRuntime().exec(cmd);
   }

}

2.服务端

package testFrame;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Timer;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

//服务器
public class testMain extends JFrame{
    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 static DataOutputStream out;
    private static DataInputStream in;
    private static Socket CurSocket;
    private static String ServiceIp;
    private static Integer ServicePort;
    private static Map<String,Socket> socketList = new HashMap<String,Socket>(); //客户端集合信息
    private static FileOutputStream fout = null;
    private static byte[] inputByte = null;
    private static Timer timer;
    public static void main(String[] args) throws IOException {
        Date d = new Date();
        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(new File(curLogAddr));
        FileWriter fw = new FileWriter(curLogAddr,true);
        PrintWriter pw = new PrintWriter(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 = new testMain();
            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() throws IOException{        
        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 = new JPanel();
        
        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 =new JScrollPane(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(new ActionListener() {
            @Override
            public void actionPerformed(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(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e){              
               FileWriter fw = null;
               try {
                    fw = new FileWriter(curLogAddr,true);
               } catch (IOException e1) {
                    e1.printStackTrace();
               }
                  PrintWriter pw = new PrintWriter(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) throws IOException{        
       final int timecount = Integer.parseInt(timeSize);
       if(timer!=null){
           timer.cancel();
       }
       timer = new Timer();       
       timer.schedule(
       new java.util.TimerTask() { 
           public void run() {
               timeFunctionContion(iptext,labec);
           } 
       }, 0, timecount*60*1000);       
   }
   
   public  static String[] getFile(String realpath) {
       Scanner scanner = null;
       String[] text = new String[4];
       int i = 0;
       try {    
           File file= new File(realpath);
           scanner = new Scanner(file);
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       }
       if(scanner!=null){
       while(scanner.hasNextLine()){
           text[i]= scanner.nextLine();
           i++;
       }
           scanner.close();
       }
       return text;
   }
   
   //校验IP
   public static boolean ipCheck(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 void judeDirExists(File file) {
        if (!file.exists()) {
            file.mkdir();
        }
    }
    
    //判断文件是否存在
    public static void judeFileExists(File file) {
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    //通过IP地址获取MAC地址      
    public static String getMACAddress(String ip) throws Exception {     
        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();    
        }      
        return macAddress;      
    } 
    
    //获取MAC地址
    public static String callCmdMAC(String cmd) throws IOException{
        Process p = Runtime.getRuntime().exec(cmd); 
        InputStreamReader isr = new InputStreamReader(p.getInputStream(),"GB2312");      
        BufferedReader br = new BufferedReader(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();
        return line;
    }
    
    //创建服务器端
    public static String callCmd(String cmd) throws IOException{
        Process p = Runtime.getRuntime().exec(cmd);      
        InputStreamReader isr = new InputStreamReader(p.getInputStream());      
        BufferedReader br = new BufferedReader(isr);
        String line="";
        String ret="";
        while ((line = br.readLine()) != null) {      
            if (line != null) {      
                ret =line;    
            }      
        }      
        br.close();
        return ret;
    }
    
    //创建服务器端
    public static void newService() throws IOException{
        ServerSocket serverSocket=new ServerSocket(ServicePort);
        while(true){
            Socket sk = serverSocket.accept();  //当有客户端连接时,产生阻塞
            socketList.put(sk.getInetAddress().toString(), sk);
            FileWriter fw = new FileWriter(curLogAddr,true);
            PrintWriter pw = new PrintWriter(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 void timeFunctionContion(String iptext,JLabel labec){
        FileWriter fw = null;
           try {
               fw = new FileWriter(curLogAddr,true);
           } catch (IOException e) {
               e.printStackTrace();
           }
           PrintWriter pw = new PrintWriter(fw);               
           Date d = new Date();               
           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 = new DataInputStream(CurSocket.getInputStream());
                         String curIPImgAddFol = logImageAddr+"\\"+ip;
                         judeDirExists(new File(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();
           }
    }
}

如有问题联系我QQ:316349645

阅读(8447) 评论(0)