影刀RPA 自动化运维:服务重启与日志清理 title: “影刀RPA 自动化运维服务重启与日志清理”date: 2026-07-01author: 林焱影刀RPA 自动化运维服务重启与日志清理服务器上某个服务偶尔会挂要人工SSH上去重启日志文件越积越大定期清理要手动处理……这类有固定操作步骤的运维任务用影刀自动化减少人肉运维。什么情况用什么适合自动化的运维场景服务异常进程挂了、端口不通后自动重启定期清理日志文件防止磁盘空间耗尽定时重启服务某些服务运行久了会内存泄漏定期重启规避批量处理多台服务器的相同操作不适合的场景拼多多店群自动化上架方案服务异常原因未知需要人工排查后再决定是否重启高危操作删除数据、修改生产数据库配置必须人工确认怎么做方法1监控服务并自动重启Windows服务【影刀操作】新建流程「服务健康监控」添加【Python】指令importsubprocessimportwin32serviceutilimportwin32serviceimporttimeimportrequestsdefcheck_service_status(service_name):检查Windows服务状态try:statuswin32serviceutil.QueryServiceStatus(service_name)# 1Stopped, 4Runningreturnstatus[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,timeout5):检查HTTP接口是否正常try:resprequests.get(url,timeouttimeout)returnresp.status_code200except: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_nameservice[service_name]# 检查服务状态is_runningcheck_service_status(service_name)ifis_runningisNone:print(f服务不存在{service_name})continueifnotis_running:print(f⚠️ 服务已停止{service_name})ifservice[auto_restart]:print(f正在尝试重启...)successrestart_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日志文件自动清理【影刀操作】添加【Python】指令importosimportglobimporttimefromdatetimeimportdatetime,timedeltadefclean_old_logs(log_dirs,keep_days7,max_total_gb5): 清理旧日志文件 log_dirs: 日志目录列表 keep_days: 保留最近N天的日志 max_total_gb: 如果总大小超过这个值清理更多 total_deleted_bytes0deleted_count0cutoff_timetime.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),recursiveTrue))# 按修改时间排序最旧的在前log_files.sort(keylambdaf:os.path.getmtime(f))forlog_fileinlog_files:mtimeos.path.getmtime(log_file)ifmtimecutoff_time:file_sizeos.path.getsize(log_file)try:os.remove(log_file)total_deleted_bytesfile_size deleted_count1print(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_usageshutil.disk_usage(rC:\\)free_gbdisk_usage.free/1024**3total_gbdisk_usage.total/1024**3usage_pct(disk_usage.used/disk_usage.total)*100print(f磁盘使用{usage_pct:.1f}%剩余{free_gb:.1f}GB)ifusage_pct80:print(⚠️ 磁盘使用率超过80%开始清理日志...)# 配置要清理的日志目录和规则log_dirs[rC:\Logs\Application,rC:\Logs\IIS,rD:\ServiceLogs]deleted_count,freed_bytesclean_old_logs(log_dirs,keep_days7)yda.set_variable(deleted_count,deleted_count)yda.set_variable(freed_mb,round(freed_bytes/1024/1024,1))方法3通过SSH操作远程Linux服务器【影刀操作】添加【Python】指令importparamikoimporttimedefssh_run(client,command,timeout30):执行SSH命令并返回输出stdin,stdout,stderrclient.exec_command(command,timeouttimeout)outstdout.read().decode(utf-8,errorsreplace).strip()errstderr.read().decode(utf-8,errorsreplace).strip()exit_codestdout.channel.recv_exit_status()returnout,err,exit_code# SSH连接sshparamiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(192.168.1.100,usernameubuntu,key_filenamerC:\SSH\my_key.pem)# 检查进程是否运行out,_,_ssh_run(ssh,pgrep -f myapp.jar)ifout:pidout.strip()print(f服务运行中PID{pid})# 检查内存使用![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/0341b1ce823c4d9f8920fa0c155e4f9b.png#pic_center)mem_out,_,_ssh_run(ssh,fps -p{pid}-o %mem --no-header)mem_pctfloat(mem_out.strip())ifmem_pct80:print(f内存占用过高{mem_pct:.1f}%准备重启)ssh_run(ssh,fkill -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 21 )# 清理旧日志out,_,codessh_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店群如何管理运营坑2SSH密钥权限问题paramiko连接时提示密钥文件权限过宽Windows上文件权限问题。解决方法直接用密码认证password参数或者确保密钥文件只有当前用户可读。坑3服务重启期间有请求进来重启过程中约5-10秒服务不可用请求报错。解决方法在业务低峰期凌晨执行自动重启或者先把流量切走再重启蓝绿部署。坑4删除了正在写入的日志日志文件还在被服务使用强制删除后文件句柄还在实际磁盘空间没释放Linux常见问题。解决方法Linux上重启后才能释放或者用logrotate配合copytruncate选项安全轮转。总结自动化运维的核心原则能自动恢复的让它自动不确定的告警让人决策。日志清理是最安全的自动化任务服务自动重启要谨慎限制次数、记录日志。做好这两件事能减少50%以上的人肉运维时间。