django开发自动跑脚本平台,分为手动出发和自动运行
时间: 2024-03-20 12:44:36 浏览: 94
自动执行脚本
实现一个自动跑脚本平台需要以下步骤:
1. 创建Django项目:
```python
django-admin startproject my_project
```
2. 创建应用程序:
```python
cd my_project
python manage.py startapp my_app
```
3. 安装依赖:
可以使用以下命令安装需要用到的依赖:
```python
pip install django-crontab
pip install paramiko
```
4. 配置数据库:
在Django项目的settings.py文件中配置数据库连接:
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'my_database',
'USER': 'my_user',
'PASSWORD': 'my_password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
```
5. 创建模型:
在应用程序my_app的models.py文件中创建模型:
```python
from django.db import models
class Script(models.Model):
name = models.CharField(max_length=50)
content = models.TextField()
interval = models.CharField(max_length=50)
is_auto = models.BooleanField(default=False)
last_run_time = models.DateTimeField(null=True, blank=True)
```
6. 创建视图:
在应用程序my_app的views.py文件中创建视图:
```python
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from crontab import CronTab
from paramiko import SSHClient
from paramiko.auth import AuthenticationException
from datetime import datetime
from .models import Script
def index(request):
scripts = Script.objects.all()
return render(request, 'index.html', {'scripts': scripts})
@csrf_exempt
def run_script(request):
script_id = request.POST.get('script_id')
script = Script.objects.get(id=script_id)
if script.is_auto:
return JsonResponse({'code': 1, 'msg': '自动脚本不能手动运行'})
try:
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('localhost', username='root', password='123456')
stdin, stdout, stderr = ssh.exec_command(script.content)
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
ssh.close()
if error:
return JsonResponse({'code': 1, 'msg': error})
script.last_run_time = datetime.now()
script.save()
return JsonResponse({'code': 0, 'msg': output})
except AuthenticationException:
return JsonResponse({'code': 1, 'msg': '登录失败'})
@csrf_exempt
def toggle_auto(request):
script_id = request.POST.get('script_id')
script = Script.objects.get(id=script_id)
script.is_auto = not script.is_auto
script.save()
if script.is_auto:
cron = CronTab(user='root')
job = cron.new(command='python manage.py runscript {0}'.format(script.name))
job.setall(script.interval)
cron.write()
else:
cron = CronTab(user='root')
cron.remove_all(command='python manage.py runscript {0}'.format(script.name))
cron.write()
return JsonResponse({'code': 0, 'msg': 'success'})
```
7. 创建模板:
在应用程序my_app的templates目录下创建index.html模板文件:
```html
{% extends "base.html" %}
{% block content %}
<table class="table">
<thead>
<tr>
<th>脚本名称</th>
<th>运行间隔</th>
<th>最近运行时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for script in scripts %}
<tr>
<td>{{ script.name }}</td>
<td>{{ script.interval }}</td>
<td>{% if script.last_run_time %}{{ script.last_run_time }}{% else %}未运行{% endif %}</td>
<td>
<button class="btn btn-primary btn-sm btn-run" data-id="{{ script.id }}">运行</button>
{% if script.is_auto %}
<button class="btn btn-warning btn-sm btn-toggle-auto" data-id="{{ script.id }}">关闭自动</button>
{% else %}
<button class="btn btn-success btn-sm btn-toggle-auto" data-id="{{ script.id }}">开启自动</button>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
{% block script %}
<script>
$(function() {
$('.btn-run').click(function() {
var script_id = $(this).data('id');
$.ajax({
url: '/run_script/',
method: 'POST',
data: {
'script_id': script_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(result) {
alert(result.msg);
}
});
});
$('.btn-toggle-auto').click(function() {
var script_id = $(this).data('id');
$.ajax({
url: '/toggle_auto/',
method: 'POST',
data: {
'script_id': script_id,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(result) {
alert(result.msg);
window.location.reload();
}
});
});
});
</script>
{% endblock %}
```
8. 创建脚本:
在Django项目根目录下创建scripts目录,并在该目录下创建脚本文件。例如,创建一个名为test.py的脚本:
```python
print('Hello, world!')
```
9. 配置定时任务:
在Django项目的settings.py文件中添加以下配置:
```python
CRONJOBS = [
('*/1 * * * *', 'my_app.scripts.test'),
]
```
10. 启动Django:
在Django项目根目录下运行以下命令启动Django:
```python
python manage.py runserver
```
现在你就可以访问http://localhost:8000/查看自动跑脚本平台了。在该平台中,你可以手动运行脚本,也可以开启自动运行模式。定时任务会根据配置的时间间隔自动运行脚本。
阅读全文