zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    JAVAWEB使用保存cookie、删除cookie、获取cookie工具类
    JAVA比较指定的两个日期
    编写一个C程序运行时输出 Hello World!
    正确理解以下名词及其含义:1源程序,目标程序,可执行程序2程序编辑,程序编译,程序连接3程序,程序模块,程序文件4函数,主函数,被调用函数,库函数5程序调试,程序测试
    为什么需要计算机语言?高级语言有哪些特点?
    什么是程序?什么是程序设计?
    题解 卡农
    题解 GT考试
    题解 SP6779 【GSS7
    题解 Crash 的文明世界
  • 原文地址:https://www.cnblogs.com/haiya2019/p/10627742.html
Copyright © 2011-2022 走看看