Java修改机器系统时间实战

有些自动化测试过程中需要修改系统时间,代码如下 

package ***.aw;

import com.autotestframe.core.basic.ActionWord;
import com.autotestkit.model.utils.ssh.SshCfg;
import com.autotestkit.utils.ssh.SshUtil;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AWChangeTime extends ActionWord {
    private int minueTimes;
    private String pastOrFuture;
    private String host ;
    private int port = 22;
    private String user ;
    private String passwd;
    @Override
    public boolean compareExpectAndActual()  {
        long nowTime=System.currentTimeMillis();
        long setTime=0;

        switch (pastOrFuture) {
            case "Past":
                setTime =nowTime - minueTimes*60*1000;
                break;
            case "Future":
                setTime =nowTime + minueTimes*60*1000;
                break;
            default:
                logger.info("请选择设置时间为过去还是未来,当前选择错误:{}。",pastOrFuture);
                break;
        }
        String dateTime=stampToDate(setTime);
        if(0==setTime){
            logger.info("修改时间有误setTime:{}.",setTime);
        }else if(host!=null && user!=null && passwd!=null && !host.equals("")&& !user.equals("")&& !passwd.equals(""))
        {     //host不为null则设置host机器的系统时间
            SshCfg cfg = new SshCfg();
            cfg.setHost(host);
            cfg.setUser(user);
            cfg.setPasswd(passwd);
            cfg.setSshPort(port);

            //ssh连接配置文件
            SshUtil util = new SshUtil(cfg);
            if (util == null) {
                return false;
            } else {
                setTimes(util,dateTime);
            }
            logger.info("当前时间是戳{},修改后的时间戳为setTime:{}.修改后的时间是{}",nowTime,setTime,dateTime);
        }else{         //设置当前机器的时间
            setTimes(dateTime);
            setTime=System.currentTimeMillis();
            logger.info("当前时间是戳{},修改后的时间戳为setTime:{}.修改后的时间是{}",nowTime,setTime,dateTime);
        }
        return true;
    }

    @Override
    public void assignContext() {
        setContext(pastOrFuture, "Past");
    }

    private String stampToDate(long time) {
        String res="";
        try{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            res = simpleDateFormat.format(new Date(time));

        }catch(Exception e){
            logger.error("serialize status failed", e);
        }
        return res;

    }

    private void setTimes(String time) {
        //Operating system name
        String osName = System.getProperty("os.name");
        String cmd = "";
        try {
            String timeOfWindow=time.substring(11,19);
            String dataOfWindow=time.substring(0,10);
            String dataOflinux=dataOfWindow.replace("-","");
            if (osName.matches("^(?i)Windows.*$")) {// Window 系统
                //设置当前机器
                // 格式 HH:mm:ss
                cmd = "  cmd /c time "+timeOfWindow;
                Runtime.getRuntime().exec(cmd);

                // 格式:yyyy-MM-dd
                cmd = " cmd /c date "+dataOfWindow;
                Runtime.getRuntime().exec(cmd);
                logger.info("Windoes 设置时间成功,当前系统时间应为{}",dataOfWindow+timeOfWindow);
            } else {// Linux 系统
                // 格式:yyyyMMdd
                cmd = "  date -s "+dataOflinux;
                Runtime.getRuntime().exec(cmd);
                // 格式 HH:mm:ss
                cmd = "  date -s "+timeOfWindow;
                Runtime.getRuntime().exec(cmd);
                logger.info("Linux 设置时间成功,当前系统时间应为{}",dataOflinux+" "+timeOfWindow);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void setTimes(SshUtil util,String time) {
        //设置目标机器的时间
        //Operating system name
        String osName = System.getProperty("os.name");
        String cmd = "";
        try {
            String timeOfWindow=time.substring(11,19);
            String dataOfWindow=time.substring(0,10);
            String dataOflinux=dataOfWindow.replace("-","");
            if (osName.matches("^(?i)Windows.*$")) {// Window 系统
                util.excuteCommand(" cmd /c date "+dataOfWindow);
                util.excuteCommand("  cmd /c time "+timeOfWindow);
            } else {// Linux 系统

                util.excuteCommand("echo ares | sudo date -s "+dataOflinux);
                util.excuteCommand("echo ares | sudo date -s "+timeOfWindow);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public int getMinueTimes() {
        return minueTimes;
    }

    public void setMinueTimes(int minueTimes) {
        this.minueTimes = minueTimes;
    }

    public String getPastOrFuture() {
        return pastOrFuture;
    }

    public void setPastOrFuture(String pastOrFuture) {
        this.pastOrFuture = pastOrFuture;
    }

    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 getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
}

你可能感兴趣的:(机器时间)