【快捷脚本】常用Python脚本集合(持续更新ing)

常用Python脚本集合(持续更新ing)

1. 时间同步

  1. 需求说明:想让两台服务器同步时间,但是不想安装什么ntp的软件,或者去一一配置啦,就想直接把另一台服务器时间直接给另一个台同步即可。
  2. 解决方案:使用Python获取当前服务器时间,去给另一台服务器更新时间
  3. 操作步骤
  • 复制脚本内容,粘贴到文件xxx.py,执行脚本的机器为主服务器
  • 修改目标机器的ip和ssh登录账号密码
  • 执行python3 xxx.py
# -*- coding: utf-8 -*-
#!/usr/bin/python
# desc 执行python版本为3.x
import paramiko
import time

def set_time(hostname):
    ssh = paramiko.SSHClient()
    # 把要连接的机器添加到known_hosts文件中
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 连接服务器
    ssh.connect(hostname=hostname, port=22, username='root', password='xxx')
    real_time = time.strftime("%m/%d/%Y %H:%M:%S", time.localtime()) # 获取当前时间
    cmd = f'date -s "{real_time}";hwclock -w'  # 设置时间并写入bios
    stdin, stdout, stderr = ssh.exec_command(cmd)
    result = stdout.read() or stderr.read()
    ssh.close()
    print(hostname, " : ", result.decode())

if __name__ == "__main__":
	# 要更新的服务器地址
    host_list = ['192.168.205.10']
    for host in host_list:
        set_time(host)

参考资料1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值