影刀RPA 自动化运维:服务重启与日志清理
2026/7/24 0:42:42 网站建设 项目流程

title: “影刀RPA 自动化运维:服务重启与日志清理”
date: 2026-07-01
author: 林焱

影刀RPA 自动化运维:服务重启与日志清理

服务器上某个服务偶尔会挂,要人工SSH上去重启;日志文件越积越大,定期清理要手动处理……这类有固定操作步骤的运维任务,用影刀自动化,减少人肉运维。

什么情况用什么

适合自动化的运维场景:

  • 服务异常(进程挂了、端口不通)后自动重启

  • 定期清理日志文件,防止磁盘空间耗尽

  • 定时重启服务(某些服务运行久了会内存泄漏,定期重启规避)

  • 批量处理多台服务器的相同操作

不适合的场景:

拼多多店群自动化上架方案

  • 服务异常原因未知,需要人工排查后再决定是否重启
  • 高危操作(删除数据、修改生产数据库配置),必须人工确认

怎么做

方法1:监控服务并自动重启(Windows服务)

【影刀操作】

  1. 新建流程「服务健康监控」
  2. 添加【Python】指令
    importsubprocessimportwin32serviceutilimportwin32serviceimporttimeimportrequestsdefcheck_service_status(service_name):"""检查Windows服务状态"""try:status=win32serviceutil.QueryServiceStatus(service_name)# 1=Stopped, 4=Runningreturnstatus[1]==4exceptExceptionase:print(f'服务{service_name}不存在或查询失败:{e}')returnNonedefrestart_service(service_name):"""重启服务"""try:win32serviceutil.StopService(service_name)time.sleep(5)win32serviceutil.StartService(service_name)time.sleep(3)returncheck_service_status(service_name)exceptExceptionase:print(f'重启失败:{e}')returnFalsedefcheck_http_endpoint(url,timeout=5):"""检查HTTP接口是否正常"""try:resp=requests.get(url,timeout=timeout)returnresp.status_code==200except:returnFalse# 监控配置services_to_monitor=[{'name':'我的业务服务','service_name':'MyBusinessService',# Windows服务名'check_url':'http://localhost:8080/health','auto_restart':True,'max_restart_times':3# 最多自动重启3次}]forserviceinservices_to_monitor:service_name=service['service_name']# 检查服务状态is_running=check_service_status(service_name)ifis_runningisNone:print(f'服务不存在:{service_name}')continueifnotis_running:print(f'⚠️ 服务已停止:{service_name}')ifservice['auto_restart']:print(f'正在尝试重启...')success=restart_service(service_name)ifsuccess:print(f'✅ 服务重启成功:{service_name}')yda.set_variable('restart_result',f'服务{service_name}已自动重启成功')else:print(f'❌ 重启失败:{service_name}')yda.set_variable('restart_result',f'服务{service_name}重启失败,需人工介入')else:# 服务进程在,但接口可能不通ifservice.get('check_url'):ifnotcheck_http_endpoint(service['check_url']):print(f'⚠️ 服务进程运行但接口异常:{service["check_url"]}')# 强制重启restart_service(service_name)else:print(f'✅ 服务正常:{service_name}')

方法2:日志文件自动清理

【影刀操作】

  1. 添加【Python】指令
    importosimportglobimporttimefromdatetimeimportdatetime,timedeltadefclean_old_logs(log_dirs,keep_days=7,max_total_gb=5):""" 清理旧日志文件 log_dirs: 日志目录列表 keep_days: 保留最近N天的日志 max_total_gb: 如果总大小超过这个值,清理更多 """total_deleted_bytes=0deleted_count=0cutoff_time=time.time()-keep_days*86400forlog_dirinlog_dirs:ifnotos.path.exists(log_dir):print(f'目录不存在:{log_dir},跳过')continue# 找到所有日志文件log_files=[]forextin['*.log','*.log.*','*.gz']:log_files.extend(glob.glob(os.path.join(log_dir,'**',ext),recursive=True))# 按修改时间排序(最旧的在前)log_files.sort(key=lambdaf:os.path.getmtime(f))forlog_fileinlog_files:mtime=os.path.getmtime(log_file)ifmtime<cutoff_time:file_size=os.path.getsize(log_file)try:os.remove(log_file)total_deleted_bytes+=file_size deleted_count+=1print(f'已删除:{log_file}({file_size/1024:.1f}KB)')exceptPermissionError:print(f'无法删除(正在使用):{log_file}')print(f'\n清理完成:删除{deleted_count}个文件,释放{total_deleted_bytes/1024/1024:.1f}MB')returndeleted_count,total_deleted_bytes# 检查磁盘空间importshutil disk_usage=shutil.disk_usage(r'C:\\')free_gb=disk_usage.free/1024**3total_gb=disk_usage.total/1024**3usage_pct=(disk_usage.used/disk_usage.total)*100print(f'磁盘使用:{usage_pct:.1f}%(剩余{free_gb:.1f}GB)')ifusage_pct>80:print('⚠️ 磁盘使用率超过80%,开始清理日志...')# 配置要清理的日志目录和规则log_dirs=[r'C:\Logs\Application',r'C:\Logs\IIS',r'D:\ServiceLogs']deleted_count,freed_bytes=clean_old_logs(log_dirs,keep_days=7)yda.set_variable('deleted_count',deleted_count)yda.set_variable('freed_mb',round(freed_bytes/1024/1024,1))

方法3:通过SSH操作远程Linux服务器

【影刀操作】

  1. 添加【Python】指令
    importparamikoimporttimedefssh_run(client,command,timeout=30):"""执行SSH命令并返回输出"""stdin,stdout,stderr=client.exec_command(command,timeout=timeout)out=stdout.read().decode('utf-8',errors='replace').strip()err=stderr.read().decode('utf-8',errors='replace').strip()exit_code=stdout.channel.recv_exit_status()returnout,err,exit_code# SSH连接ssh=paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect('192.168.1.100',username='ubuntu',key_filename=r'C:\SSH\my_key.pem')# 检查进程是否运行out,_,_=ssh_run(ssh,'pgrep -f "myapp.jar"')ifout:pid=out.strip()print(f'服务运行中,PID:{pid}')# 检查内存使用![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/0341b1ce823c4d9f8920fa0c155e4f9b.png#pic_center)mem_out,_,_=ssh_run(ssh,f'ps -p{pid}-o %mem --no-header')mem_pct=float(mem_out.strip())ifmem_pct>80:print(f'内存占用过高:{mem_pct:.1f}%,准备重启')ssh_run(ssh,f'kill -15{pid}')time.sleep(5)ssh_run(ssh,'cd /app && nohup java -jar myapp.jar &')print('服务已重启')else:print('服务未运行,启动服务')ssh_run(ssh,'cd /app && nohup java -jar myapp.jar > app.log 2>&1 &')# 清理旧日志out,_,code=ssh_run(ssh,'find /var/log/myapp -name "*.log" -mtime +7 -delete && echo "清理完成"')print(f'日志清理:{out}')# 检查磁盘空间out,_,_=ssh_run(ssh,'df -h / | tail -1')print(f'磁盘使用:{out}')ssh.close()

有什么坑

坑1:自动重启掩盖真正问题

服务频繁崩溃,自动重启让服务保持"正常",但根本问题(内存泄漏、死锁)没有被发现。

解决方法:记录重启次数,24小时内重启超过3次就停止自动重启,发告警让人工排查。

TEMU店群如何管理运营?


坑2:SSH密钥权限问题

paramiko连接时提示密钥文件权限过宽(Windows上文件权限问题)。

解决方法:直接用密码认证(password=参数),或者确保密钥文件只有当前用户可读。

坑3:服务重启期间有请求进来

重启过程中(约5-10秒),服务不可用,请求报错。

解决方法:在业务低峰期(凌晨)执行自动重启,或者先把流量切走再重启(蓝绿部署)。

坑4:删除了正在写入的日志

日志文件还在被服务使用,强制删除后,文件句柄还在,实际磁盘空间没释放(Linux常见问题)。

解决方法:Linux上重启后才能释放,或者用logrotate配合copytruncate选项安全轮转。

总结

自动化运维的核心原则:能自动恢复的让它自动,不确定的告警让人决策。日志清理是最安全的自动化任务,服务自动重启要谨慎(限制次数、记录日志)。做好这两件事,能减少50%以上的人肉运维时间。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询