修改Windows和linux系統時間

1、修改本機Windows的系統時間,Java代碼實現:

複製代碼
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ChangeWindowsDate {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) {
        try {
            Runtime.getRuntime().exec("cmd /c date 2013-11-08") ;
            Runtime.getRuntime().exec("cmd /c time 18:10:00") ;
        } catch (IOException e) {
            e.printStackTrace() ;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        Date date = new Date() ;
        System.out.println(sdf.format(date));
        
    }

}
複製代碼

2、修改遠程Linux Server的系統時間,Java代碼實現:

複製代碼
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;



public class ChangeLinuxDate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String host_ip1 = "192.168.1.118" ;
        int port = 22 ;
        String username = "root" ;
        String password = "123456" ;        
        
        String cmd = "date -s '2013-08-04 23:00:00'" ;
        
        Connection conn1 = new Connection(host_ip1, port) ;
        Session session1 = null ;
        
        try {
            conn1.connect() ;
            boolean isconn = conn1.authenticateWithPassword(username, password) ;
            if(!isconn){
                System.out.println("用戶名稱或者是密碼不正確");
            }else{
                System.out.println(host_ip1 + ":" + "已經連接OK");
                session1 = conn1.openSession() ;
                session1.execCommand(cmd) ;

                InputStream is = new StreamGobbler(session1.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is));
                while(true){  
                    String line = brs.readLine();  
                    if(line==null){  
                        break;  
                    }  
                    System.out.println(line);  
                }
                is.close() ;
                brs.close() ;
                session1.close() ;
                conn1.close() ;
            }
            
        } catch (IOException e) {
            e.printStackTrace() ;
        }
        
    }

}
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章