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)