Python 更新linux服務器日期時間


 

由於使用的f-string,請使用Python3.6及以上的版本,或者把cmd變量修改了。
以下代碼是獲取用戶所在的系統時間去進行同步,用於局域網的條件。

 1 import paramiko
 2 import time
 3 
 4 def set_time(hostname):
 5     ssh = paramiko.SSHClient()
 6     # 把要連接的機器添加到known_hosts文件中
 7     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 8     # 連接服務器
 9     ssh.connect(hostname=hostname, port=22, username='root', password='winserver')
10     real_time = time.strftime("%m/%d/%Y %H:%M:%S", time.localtime()) # 獲取當前時間
11     cmd = f'date -s "{real_time}";hwclock -w'  # 設置時間並寫入bios
12     stdin, stdout, stderr = ssh.exec_command(cmd)
13     result = stdout.read() or stderr.read()
14     ssh.close()
15     print(hostname, " : ", result.decode())
16 
17 if __name__ == "__main__":
18     host_list = ['192.168.205.10', '192.168.205.20', '192.168.205.30', '192.168.205.50']
19     for host in host_list:
20         set_time(host)

 

如果是可以訪問互聯網的話,建議從網絡獲取時間比較准確,代碼如下:

 1 import paramiko
 2 import time
 3 import requests
 4 
 5 
 6 def get_time():
 7     re = requests.get('https://www.baidu.com')
 8     get_time = re.headers['date']                                   # 從百度返回的文件頭獲取時間
 9     real_time = time.strptime(get_time[5:25], "%d %b %Y %H:%M:%S")  # 獲取當前時間
10     local_time = time.localtime(time.mktime(real_time) + 8*3600)    # 轉北京時間
11     real_time = time.strftime("%m/%d/%Y %H:%M:%S", local_time)      # 轉換時間格式
12     return real_time
13 
14 def set_time(hostname, ssh):
15     ssh.connect(hostname=hostname, port=22, username='root', password='winserver')
16     real_time = get_time()                      # 從網絡獲取獲取當前時間
17     cmd = f'date -s "{real_time}";hwclock -w'   # 設置時間並寫入bios
18     stdin, stdout, stderr = ssh.exec_command(cmd)
19     result = stdout.read() or stderr.read()
20     ssh.close()
21     print(hostname, " : ", result.decode())
22 
23 if __name__ == "__main__":
24     ssh = paramiko.SSHClient()
25     # 把要連接的機器添加到known_hosts文件中
26     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
27     # 連接服務器
28     host_list = ['192.168.205.50']
29     for host in host_list:
30         set_time(host, ssh)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM