You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS CentOS 7实例中配置bash脚本实现开机自动运行

解决方案

1. 编写符合要求的上报脚本

预置脚本到镜像的/opt/aws_report/report.sh路径,设置仅root可读写执行,满足安全不被客户轻易查看的要求,脚本内容如下:

#!/bin/bash
# 替换为你的服务端实际IP
SERVER_IP="你的服务端IP"
# 等待EC2元数据服务和网络就绪,最多等30秒避免执行时机过早
for i in {1..30}; do
    curl -s --connect-timeout 1 http://169.254.169.254/latest/meta-data/instance-id > /dev/null && break
    sleep 1
done
# 从AWS EC2内置元数据接口获取实例ID、公网IP
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)
# 上报数据到服务端
curl -k "https://${SERVER_IP}/myphp.php?id=${INSTANCE_ID}&ip=${PUBLIC_IP}"

执行命令设置权限:
chmod 700 /opt/aws_report/report.sh
chown root:root /opt/aws_report/report.sh

2. 配置systemd开机自动执行(AWS环境最稳定方案)

你之前的systemd配置未生效是因为没有指定执行依赖,且脚本使用了相对路径,按以下配置即可:
新建服务文件/etc/systemd/system/aws-report.service,内容如下:

[Unit]
Description=Report EC2 instance info to internal server
# 等待网络、EC2云初始化完成后再执行,避免时机过早失败
After=network.target cloud-init.target

[Service]
Type=oneshot
RemainAfterExit=yes
# 填写脚本绝对路径
ExecStart=/opt/aws_report/report.sh
User=root

[Install]
WantedBy=multi-user.target

执行命令启用服务:
systemctl daemon-reload
systemctl enable aws-report.service

3. 你之前遇到的启动失败问题排查

  • /etc/profile.d下的脚本启动失败是因为你写错了shebang,末尾多了斜杠#!/bin/bash/,错误的解释器路径会导致用户登录环境初始化失败,直接造成SSH连接超时
  • crontab的@reboot方案失效是因为crond执行时EC2网络还未就绪,请求卡住会阻塞启动流程
  • 预置镜像时提前执行systemctl disable httpd即可避免httpd开机启动导致的实例异常

额外注意事项

  • 所有脚本、文件路径都要使用绝对路径,不要用./这类相对路径,systemd执行时的工作目录不是脚本存放目录
  • 每次重启实例后先刷新EC2控制台页面,确认公网IP更新后再发起SSH连接,避免控制台缓存旧IP导致连接失败

内容的提问来源于stack exchange,提问作者Phoenix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 18:09:02