远程监控虚拟机上limux的硬盘和内存使用情况(每三秒刷新一次)并控制服务器的开关机,先用python连接到Linux,然后根据Linux的命令,去查询对应的进程、磁盘和内存,因为要显示到页面上,所以用django封装起来,把方法封装成接口,前端页面用elementui和vue画,通过axios调用封装好的接口,把服务器情况显示到页面上的代码。
时间: 2023-06-14 17:08:18 浏览: 64
首先,需要编写一个 Python 脚本来连接到远程的 Linux 服务器,并查询硬盘和内存的使用情况。可以使用 paramiko 库来实现 SSH 连接。以下是一个示例代码:
```python
import paramiko
import time
# SSH 连接信息
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote_host', username='username', password='password')
# 查询硬盘使用情况
stdin, stdout, stderr = ssh.exec_command('df -h')
disk_usage = stdout.read().decode('utf-8')
# 查询内存使用情况
stdin, stdout, stderr = ssh.exec_command('free -m')
memory_usage = stdout.read().decode('utf-8')
# 打印使用情况
print('Disk usage:')
print(disk_usage)
print('Memory usage:')
print(memory_usage)
# 关闭 SSH 连接
ssh.close()
```
接下来,需要使用 Django 框架来封装这个脚本,并把查询硬盘和内存使用情况的方法封装成接口。以下是一个示例代码:
```python
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import paramiko
# SSH 连接信息
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote_host', username='username', password='password')
@csrf_exempt
def get_disk_usage(request):
# 查询硬盘使用情况
stdin, stdout, stderr = ssh.exec_command('df -h')
disk_usage = stdout.read().decode('utf-8')
return JsonResponse({'disk_usage': disk_usage})
@csrf_exempt
def get_memory_usage(request):
# 查询内存使用情况
stdin, stdout, stderr = ssh.exec_command('free -m')
memory_usage = stdout.read().decode('utf-8')
return JsonResponse({'memory_usage': memory_usage})
```
最后,需要编写一个前端页面,使用 ElementUI 和 Vue.js 来实现。以下是一个示例代码:
```html
<template>
<div>
<el-button type="primary" @click="refresh">Refresh</el-button>
<el-card v-for="(item, index) in items" :key="index" class="box-card">
<div slot="header" class="clearfix">
<span>{{ item.title }}</span>
</div>
<div v-html="item.content"></div>
</el-card>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
items: [
{ title: 'Disk Usage', content: '' },
{ title: 'Memory Usage', content: '' }
]
}
},
methods: {
refresh () {
axios.get('/api/disk-usage/')
.then(response => {
this.items[0].content = response.data.disk_usage
})
axios.get('/api/memory-usage/')
.then(response => {
this.items[1].content = response.data.memory_usage
})
}
}
}
</script>
```
最后,在 Django 的 urls.py 文件中添加以下代码:
```python
from django.urls import path
from . import views
urlpatterns = [
path('api/disk-usage/', views.get_disk_usage),
path('api/memory-usage/', views.get_memory_usage),
]
```
这样就完成了一个远程监控 Linux 服务器硬盘和内存使用情况,并控制服务器开关机的应用。