python3 定时重启服务

本文介绍了一个使用Python编写的定时任务脚本,该脚本能每天在特定时间(12:24)自动重启Windows打印服务(spooler)。通过调用系统命令实现服务的停止与启动,利用时间模块获取当前时间并进行比较判断,确保服务按计划重启。
import os
import time
import time
import datetime
import codecs


def get_min():
    return int(  time.strftime('%M', time.localtime(time.time())) )
    
def get_hour():
    return int(  time.strftime('%H', time.localtime(time.time())) )
    
def get_current_time():
    return ( str(datetime.datetime.now().year) + '-' + str(datetime.datetime.now().month) + '-' + str(datetime.datetime.now().day) + " " + time.strftime('%H:%M:%S',time.localtime(time.time())) )

def writelog(content):
    print(content)
    f = codecs.open('reboot.log','a','utf-8')
    f.write(content)
    f.writelines('\r\n')
    f.flush()

def rebootservice():
    os.system('net stop spooler')
    time.sleep(1)
    os.system('net start spooler')
    
while True:
    print(get_current_time())
    if (  get_min() == 24  and get_hour() == 12 ):
        writelog("重启服务时间:" + get_current_time())
        rebootservice()
        time.sleep(60)
    time.sleep(10)
你可以使用Python的paramiko和time库来编一个定时重启H3C交换机的脚本。以下是一个示例代码: ```python import paramiko import time # 设置H3C交换机IP地址、用户名和密码 ip = '192.168.0.1' username = 'admin' password = 'password' # 创建SSH客户端连接 ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password) # 发送命令并获取输出 def send_command(command): ssh_shell = ssh.invoke_shell() time.sleep(1) ssh_shell.send(command + '\n') time.sleep(2) output = ssh_shell.recv(10000) return output.decode('utf-8') # 重启交换机 def restart_switch(): send_command('system-view') send_command('reboot') # 定时重启交换机 while True: current_time = time.strftime('%H:%M:%S', time.localtime()) if current_time == '03:00:00': print('Restarting switch...') restart_switch() break time.sleep(1) # 关闭SSH连接 ssh.close() ``` 在上面的代码中,首先使用paramiko库建立SSH连接。然后定义了send_command函数,它可以发送命令并获取输出。接着定义了restart_switch函数,它将进入系统视图并重启交换机。最后,使用while循环和time库来设置定时执行重启操作的时间,当时间到达指定时间时,就会执行重启操作。 请注意,定时重启交换机可能会影响网络正常运行,因此请谨慎使用。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值