VPS挂机教程2026:24小时稳定运行方案
前言
想让软件24小时不间断运行?VPS是最佳选择!无论是挂机刷任务、运行自动化脚本,还是保持账号在线,VPS都能提供稳定的运行环境。本文将详细介绍2026年VPS挂机完整教程,从环境配置到稳定运行,让你轻松实现24小时无人值守。
VPS挂机适用场景
常见挂机需求
| 挂机类型 | 资源需求 | 推荐配置 | 适用软件 |
|---|---|---|---|
| 账号挂机 | 1核1GB | 轻量VPS | QQ/微信/Telegram |
| 刷任务挂机 | 1核2GB | 标准VPS | 各类刷单/签到软件 |
| 爬虫挂机 | 2核4GB | 优化VPS | Python爬虫/Scrapy |
| 游戏挂机 | 2核4GB | 游戏VPS | 模拟器/游戏脚本 |
| AI挂机 | 4核8GB+GPU | 计算VPS | AI绘图/聊天机器人 |
为什么选择VPS挂机?
优势:
- ✅ 24小时不间断运行
- ✅ 家庭断电/断网不影响
- ✅ 多账号同时挂机
- ✅ 资源隔离,互不干扰
- ✅ 成本低于实体服务器
注意事项:
- ⚠️ 遵守软件服务条款
- ⚠️ 不要用于违法活动
- ⚠️ 注意资源占用,避免被封
VPS系统环境配置
1. Linux系统基础配置
# 更新系统
sudo apt update && sudo apt upgrade -y
# 安装基础工具
sudo apt install -y wget curl unzip screen htop
# 配置时区(重要!)
sudo timedatectl set-timezone Asia/Shanghai
# 查看系统资源
htop
df -h
2. Windows系统配置(需要GUI挂机)
安装桌面环境:
# Ubuntu安装XFCE桌面
sudo apt install xfce4 xfce4-goodies -y
# 安装VNC服务器
sudo apt install tightvncserver -y
# 启动VNC
vncserver :1 -geometry 1920x1080 -depth 24
连接VNC:
1. 本地安装VNC Viewer
2. 连接地址:VPS_IP:5901
3. 输入VNC密码
4. 进入远程桌面
3. 创建专用用户
# 创建挂机用户
sudo adduser hanguser
sudo usermod -aG sudo hanguser
# 切换用户
su - hanguser
挂机软件安装与配置
方案1:使用Screen后台运行
Screen基础命令:
# 创建新会话
screen -S hang1
# 在会话中运行软件
python3 hang_script.py
# 按Ctrl+A然后按D detach(保持运行)
# 查看所有会话
screen -ls
# 重新连接会话
screen -r hang1
# 终止会话
screen -X -S hang1 quit
实战示例:Python脚本挂机
# 创建挂机脚本
nano hang_bot.py
import time
import logging
from datetime import datetime
# 配置日志
logging.basicConfig(
filename='hang_bot.log',
level=logging.INFO,
format='%(asctime)s - %(message)s'
)
def main_task():
"""主任务函数"""
while True:
try:
# 执行你的任务
logging.info("任务执行中...")
# 这里写你的挂机逻辑
# 每隔一段时间执行一次
time.sleep(3600) # 1小时
except Exception as e:
logging.error(f"错误: {e}")
time.sleep(300) # 出错后等待5分钟重试
if __name__ == "__main__":
logging.info("挂机脚本启动")
main_task()
# 在screen中运行
screen -S hang_bot
python3 hang_bot.py
# Ctrl+A, D detach
方案2:使用Systemd服务(推荐)
创建服务文件:
sudo nano /etc/systemd/system/hang-bot.service
服务配置:
[Unit]
Description=Hang Bot Service
After=network.target
[Service]
Type=simple
User=hanguser
WorkingDirectory=/home/hanguser
ExecStart=/usr/bin/python3 /home/hanguser/hang_bot.py
Restart=always
RestartSec=30
StandardOutput=append:/home/hanguser/hang-bot.log
StandardError=append:/home/hanguser/hang-bot.error.log
[Install]
WantedBy=multi-user.target
启动服务:
# 重新加载systemd
sudo systemctl daemon-reload
# 启动服务
sudo systemctl start hang-bot
# 设置开机自启
sudo systemctl enable hang-bot
# 查看状态
sudo systemctl status hang-bot
# 查看日志
sudo journalctl -u hang-bot -f
方案3:使用Docker容器
Dockerfile:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY hang_bot.py .
CMD ["python", "hang_bot.py"]
构建和运行:
# 构建镜像
docker build -t hang-bot .
# 运行容器(自动重启)
docker run -d \
--name hang-bot \
--restart always \
--log-driver=json-file \
--log-opt max-size=10m \
--log-opt max-file=3 \
hang-bot
# 查看日志
docker logs -f hang-bot
资源占用优化
1. 限制CPU和内存
使用Systemd限制资源:
# 在service文件中添加
[Service]
# 限制CPU使用率(50%)
CPUQuota=50%
# 限制内存
MemoryLimit=2G
# 限制进程数
LimitNPROC=1000
使用Docker限制资源:
docker run -d \
--name hang-bot \
--cpus=1.5 \
--memory=2g \
--memory-swap=3g \
--restart always \
hang-bot
2. 监控资源占用
# 安装监控工具
sudo apt install htop iotop nethogs -y
# 实时监控
htop
# 查看进程资源占用
ps aux --sort=-%mem | head -20
ps aux --sort=-%cpu | head -20
# 查看网络占用
nethogs
3. 自动清理日志
# 创建日志清理脚本
nano /home/hanguser/cleanup_logs.sh
#!/bin/bash
# 清理7天前的日志
find /home/hanguser/logs -name "*.log" -mtime +7 -delete
# 清理大于100MB的日志
find /home/hanguser/logs -name "*.log" -size +100M -delete
echo "$(date): 日志清理完成" >> /home/hanguser/cleanup.log
# 添加定时任务
crontab -e
# 每天凌晨2点清理
0 2 * * * /bin/bash /home/hanguser/cleanup_logs.sh
稳定性保障方案
1. 自动重启机制
使用Systemd自动重启:
[Service]
Restart=always # 总是重启
RestartSec=30 # 重启前等待30秒
StartLimitInterval=0 # 无限制重启
使用Supervisor(更强大):
# 安装supervisor
sudo apt install supervisor -y
# 配置程序
sudo nano /etc/supervisor/conf.d/hang-bot.conf
[program:hang-bot]
command=/usr/bin/python3 /home/hanguser/hang_bot.py
directory=/home/hanguser
user=hanguser
autostart=true
autorestart=true
startretries=999
redirect_stderr=true
stdout_logfile=/home/hanguser/hang-bot.log
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=10
# 启动管理
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl status hang-bot
2. 健康检查
创建健康检查脚本:
nano /home/hanguser/health_check.sh
#!/bin/bash
# 检查进程是否存在
if ! pgrep -f "hang_bot.py" > /dev/null; then
echo "$(date): 进程不存在,正在重启..." >> /home/hanguser/health.log
systemctl restart hang-bot
fi
# 检查CPU占用
CPU_USAGE=$(ps aux | grep "hang_bot.py" | grep -v grep | awk '{print $3}')
if (( $(echo "$CPU_USAGE > 90" | bc -l) )); then
echo "$(date): CPU占用过高($CPU_USAGE%),正在重启..." >> /home/hanguser/health.log
systemctl restart hang-bot
fi
# 添加到crontab(每5分钟检查一次)
*/5 * * * * /bin/bash /home/hanguser/health_check.sh
3. 故障告警
配置邮件告警:
# 安装mailutils
sudo apt install mailutils -y
# 创建告警脚本
nano /home/hanguser/alert.sh
#!/bin/bash
SUBJECT="VPS挂机告警"
EMAIL="your-email@example.com"
MESSAGE="挂机程序在 $(date) 停止运行,已自动重启。"
echo "$MESSAGE" | mail -s "$SUBJECT" "$EMAIL"
# 在systemd service中配置
[Service]
ExecStopPost=/bin/bash /home/hanguser/alert.sh
常见问题与解决方案
问题1:挂机程序频繁崩溃
原因:
- 内存不足
- 软件bug
- 依赖缺失
解决:
# 1. 检查内存
free -h
# 2. 增加虚拟内存
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# 3. 查看崩溃日志
journalctl -u hang-bot --no-pager | tail -50
问题2:VPS被封
原因:
- 滥用资源(CPU/带宽占满)
- 运行违法软件
- 被投诉
预防:
- 限制资源使用(CPU<80%, 内存<90%)
- 不使用VPS做违法事情
- 选择允许挂机的VPS商家
问题3:网络不稳定
优化方案:
# 1. 启用BBR加速
echo "net.core.default_qdisc=fq" | sudo tee -a /etc/sysctl.conf
echo "net.ipv4.tcp_congestion_control=bbr" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
# 2. 配置重试机制
# 在挂机脚本中添加
import time
MAX_RETRIES = 5
for attempt in range(MAX_RETRIES):
try:
# 你的网络请求
break
except Exception as e:
if attempt < MAX_RETRIES - 1:
time.sleep(2 ** attempt) # 指数退避
continue
总结
VPS挂机24小时稳定运行的关键:
环境配置:
- ✅ 选择Linux系统(资源占用少)
- ✅ 使用Systemd/Docker管理进程
- ✅ 配置自动重启机制
稳定性保障:
- ✅ 限制资源使用(CPU/GPU/内存)
- ✅ 配置健康检查和告警
- ✅ 定期清理日志和临时文件
推荐配置:
- 入门挂机:1核2GB,适合简单脚本
- 中级挂机:2核4GB,适合爬虫/多开
- 高级挂机:4核8GB,适合游戏/AI
相关文章推荐:
- VPS定时任务设置教程2026:crontab配置
- VPS监控资源使用教程2026:Zabbix监控
- VPS安全加固教程2026:防暴力破解
- VPS优化网络速度2026:BBR加速

评论(0)