求助:AWS EC2 Linux实例重启后无法自动运行Python脚本
配置问题分析与修正方案
现有配置的核心问题
脚本路径未指定绝对路径
EC2启动时用户数据脚本的默认工作目录是/,而你的script.py、script2.py存放在Cloud9的环境目录(通常为/home/ec2-user/environment/),直接写文件名会导致系统找不到脚本。Python解释器版本不匹配
多数AWS Linux镜像中python指向Python2,若你的脚本基于Python3开发,会直接运行失败,需明确使用python3调用。无日志记录,无法排查问题
脚本运行的输出和错误未被捕获,出现问题后无法定位原因。未处理环境依赖
如果脚本依赖Cloud9中配置的虚拟环境,现有脚本未激活虚拟环境,会导致依赖包找不到。
修正后的用户数据配置
Content-Type: multipart/mixed; boundary="//" MIME-Version: 1.0 --// Content-Type: text/cloud-config; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="cloud-config.txt" #cloud-config cloud_final_modules: - [scripts-user, always] --// Content-Type: text/x-shellscript; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="userdata.txt" #!/bin/bash # 替换为你的脚本实际所在绝对路径 SCRIPT_DIR="/home/ec2-user/environment" # 日志输出路径,方便排查问题 LOG_FILE="/var/log/startup_scripts.log" # 先确认脚本目录存在 if [ -d "$SCRIPT_DIR" ]; then cd "$SCRIPT_DIR" # 如果使用虚拟环境,取消下面注释并替换为你的虚拟环境路径 # source venv/bin/activate # 运行脚本并记录所有输出和错误 python3 script.py >> "$LOG_FILE" 2>&1 python3 script2.py >> "$LOG_FILE" 2>&1 else echo "错误:脚本目录不存在 -> $SCRIPT_DIR" >> "$LOG_FILE" 2>&1 fi --//--
验证步骤
- 重启EC2实例后,查看日志排查问题:
cat /var/log/startup_scripts.log - 确认脚本路径正确性:
ls /home/ec2-user/environment/script.py - 确保脚本有可读权限:
chmod +r /home/ec2-user/environment/*.py
内容的提问来源于stack exchange,提问作者Drejz
相关产品推荐
相关产品推荐

