base_class文件
import sys
import libvirt
import socket
import paramiko
class SSH:
def __init__(self,):
self.ID = 1
def Connect(self,ip,username,pd,port=22):
try:
self.trans = paramiko.Transport((ip,port)) # 创建一个transport对象
self.trans.connect(username=username,password=pd) # 建立连接
self.SSh = paramiko.SSHClient() # 创建SSH客服端对象,用来执行命令行
self.SSh._transport = self.trans # 使用之前的连接
self.Sftp = paramiko.SFTPClient.from_transport(self.trans) # 创建sftp对象,用来传输文件
except:
print("连接失败,请检查!")
def Command(self,com=""):
# 命令执行,stdout为返回的结果, stderr为返回的错误信息
stdin, stdout, stderr =self.SSh.exec_command(command=com)
if stdout: # 读取成功,解码输出
print(stdout.read().decode())
return True
else:
print(stderr.read().decode()) # 输出错误信息
return False
def Put(self,local_path,remote_path): # 文件传输
self.Sftp.put(local_path,remote_path)
def Get(self,remote_path,local_path): # 文件传输
self.Sftp.get(remote_path,local_path)
def Close(self): # 关闭连接
self.trans.close()
class KVM_Control:
def __init__(self):
self.conn=None
self.hostname = "本机"
# 创建连接
def createConnect(self,user_name="",the_ip=""):
if user_name=="":
self.conn = libvirt.open("qemu:///system") # 连接自己的kvm
self.hostname = "本机"
else:
self.conn = libvirt.open("qemu+ssh://{0}@{1}/system".format(user_name,the_ip)) # 远程连接
self.hostname = user_name+"@"+the_ip
if self.conn==None:
print("Connect failed!")
return False
else:
print("Connect success!")
return True
# 主机信息
def Host_info(self):
property_ = self.conn.getInfo()
return {'hostname': self.hostname, 'cpu_type': property_[0], 'memory': property_[1]/1024,
'cpu_nums': property_[2],'kvm_type': self.conn.getType()}
# 虚拟机概况
def VirMachine_info(self):
offline_Dom = self.conn.listDefinedDomains() # 未运行的虚拟机
online_Dom = self.conn.listDomainsID() # 正在运行的虚拟机
ret_msg = []
print("正常运行的虚拟机有:")
print("编号 ID 域名称 状态")
for index,i in zip(range(len(online_Dom)),online_Dom):
dom = self.conn.lookupByID(i)
print("{0} {1} {2} Running".format(index+1,dom.ID(),dom.name()))
ret_msg.append(dict({"hostname":self.hostname,"dom_name":dom.name(),"status":"running"},**self.vir_info(name=dom.name(),Get_IP=True)))
print("未运行的虚拟机有:")
print("编号 域名称 状态")
for index, i in zip(range(len(offline_Dom)), offline_Dom):
dom = self.conn.lookupByName(i)
print("{0} {1} Stoped".format(index + 1, dom.name()))
ret_msg.append(dict({"hostname":self.hostname,"dom_name":dom.name(),"status":"stopped"},**self.vir_info(name=dom.name())))
return ret_msg
# 虚拟机详情
def vir_info(self,name="",Get_IP=False):
dom = self.conn.lookupByName(name)
Info = dom.info()
IP="-"
if Get_IP:
ifaces = dom.interfaceAddresses(libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT, 0) # 查看网络配置文件
IP = ifaces['ens3']['addrs'][0]['addr']
return {"memory": int(Info[1]/1048576),"CPUs":Info[3],"IP":IP}
def create_new_machine(self,name,cpus,memory,):
pass
# 定义虚拟机域
def define(self, name):
try:
# f = open('/etc/libvirt/qemu/{}.xml'.format(name)) # xml文件需要事先准备好
# xml = f.read()
# f.close()
dom = self.conn.defineXML(xml_info)
print("定义域成功")
return True
except:
return False
# 取消定义
def undefine(self,name):
try:
dom = self.conn.lookupByName(name)
dom.undefine()
return True
except:
return False
# 强制关机
def destroy(self,name):
try:
dom = self.conn.lookupByName(name)
dom.destroy()
return True
except:
return False
# 启动虚拟机
def start(self,name):
try:
dom = self.conn.lookupByName(name)
dom.create()
return True
except:
return False
# 关闭虚拟机
def shutdown(self,name):
try:
dom = self.conn.lookupByName(name)
dom.shutdown()
return True
except:
return False
views文件
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from database.models import customer
from cloud1.base_function import user_login,user_sign,func_add_1,func_add_2,func_add_3,func_add_4,func_add_5,func_add_6,func_add_7
# Create your views here.
def Login_page(request):
if request.method == "GET":
return render(request=request,template_name="Login.html") # context={'name': name}
if request.method == "POST":
if request.POST.get('type') == "sign": # 无关返回
return JsonResponse({'ret':0,'msg':"log"})
else:
print(request.POST.get('username'))
print(request.POST.get('password'))
if user_login(request.POST.get('username'),request.POST.get('password')):
return JsonResponse({'ret':0,'msg':"success"}) # 验证成功
else:
return JsonResponse({'ret':1,'msg':"user error"}) # 失败
# 注册处理
def Signin(request):
if request.method == "GET":
return render(request=request,template_name="Signin.html") # context={'name': name}
if request.method == "POST":
if request.POST.get('type') == "login": # 无关返回
return JsonResponse({'ret':0,'msg':"log"})
else:
# 从 HTTP POST 请求中获取用户名、密码参数
userName = request.POST.get('username')
passWord1 = request.POST.get('password1')
passWord2 = request.POST.get('password2')
if passWord1 != passWord2: # 注册时前后的密码不一样,注册错误
return JsonResponse({'ret': 1, 'msg': '前后密码不一样'})
if user_sign(userName,passWord1):
return JsonResponse({'ret': 0, 'msg': '注册成功'})
else:
return JsonResponse({'ret': 1, 'msg': '用户名已存在'})
def Ctr(request):
if request.method == "GET":
return render(request=request,template_name="Control.html") # context={'name': name}
if request.method == "POST":
if request.POST.get('type') == "add_1": # 获取主机信息
return JsonResponse({'ret': 0, 'data': func_add_1()})
elif request.POST.get('type') == "add_2_add": # 创建虚拟机
hostname = request.POST.get('hostname_2')
name = request.POST.get('name_2')
run_memory = request.POST.get('run_memory_2')
disk_memory = request.POST.get('disk_memory_2')
return JsonResponse({'ret': 0, 'data': func_add_2(hostname,name,run_memory,disk_memory)})
elif request.POST.get('type') == "add_3_add": # 删除虚拟机
hostname = request.POST.get('hostname_3')
name = request.POST.get('name_3')
(ret,data) = func_add_3(hostname, name) # 删除信息
return JsonResponse({'ret': ret, 'data':data})
elif request.POST.get('type') == "add_4": # 查询虚拟机状态
return JsonResponse({'ret': 0, 'data': func_add_4()})
elif request.POST.get('type') == "add_5_add": # 启动虚拟机
hostname = request.POST.get('hostname_5')
name = request.POST.get('name_5')
(ret,data) = func_add_5(hostname, name)
return JsonResponse({'ret': ret, 'data':data})
elif request.POST.get('type') == "add_6_add": # 关闭虚拟机
hostname = request.POST.get('hostname_6')
name = request.POST.get('name_6')
(ret,data) = func_add_6(hostname, name) # 删除信息
return JsonResponse({'ret': ret, 'data':data})
elif request.POST.get('type') == "add_7_add": # 运行并行程序
data = func_add_7()
if data:
return JsonResponse({'ret': 0, 'data': data})
return JsonResponse({'ret': 1, 'data':"删除错误"})
base_function文件
from django.http import JsonResponse
# from database.models import customer
import json
from cloud1.base_class import KVM_Control,SSH
import socket
# xml = "<domain type="kvm">
# <name>ubuntu3</name> <!--虚拟机名称-->
# <memory unit="MiB">3096</memory> <!--最大内存,单位k-->
# <currentMemory unit="MiB">3096</currentMemory> <!--可用内存,单位k-->
# <vcpu>3</vcpu> <!--//虚拟cpu个数-->
# <os>
# <type arch="x86_64" machine="pc">hvm</type>
# <boot dev="hd" /> <!-- 硬盘启动 -->
# <boot dev="cdrom" /> <!--//光盘启动-->
# <bootmenu enable='yes'/>
# </os>
# <features>
# <acpi />
# <apic />
# <pae />
# </features>
# <clock offset="localtime" />
# <on_poweroff>destroy</on_poweroff>
# <on_reboot>restart</on_reboot>
# <on_crash>destroy</on_crash>
# <devices>
# <emulator>/usr/bin/kvm</emulator>
# <disk type="file" device="disk">
# <driver name="qemu" type="qcow2" />
# <source file="/home/user/ubuntu3.qcow2" /> <!--目的镜像路径-->
# <target dev="hda" bus="ide" />
# </disk>
# <disk type="file" device="cdrom">
# <source file="/home/user/ubuntu-18.04.5-desktop-amd64.iso" /> <!--光盘镜像路径 -->
# <target dev="hdb" bus="ide" />
# </disk>
# <interface type="bridge"> <!--虚拟机网络连接方式-->
# <source bridge="br0" /> <!--当前主机网桥的名称-->
# </interface>
# <channel type='unix'>
# <source mode="bind"/>
# <target type='virtio' name='org.qemu.guest_agent.0'/>
# </channel>
# <input type="mouse" bus="ps2" />
# <!--vnc方式登录,端口号自动分配,自动加1,可以通过virsh vncdisplay来查询
# -->
# <graphics type="vnc" port="-1" autoport="yes" listen="0.0.0.0" keymap="en-us" />
# </devices>
# </domain>"
# 读取数据为字典
def read_data(name): # 读取文件,json形式读取为字典
try:
with open(name,mode="r",encoding="utf-8") as fp:
js = fp.read()
dic = json.loads(js)
return dic
except:
return None
# 将数据写入txt文件
def write_data(name,data): # 写入文件,写入json格式,为字典
with open(name,mode="w",encoding="utf-8") as fp:
fp.write(json.dumps(data))
def get_host_ip():
try:
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.connect(('8.8.8.8',80))
ip = s.getsockname()[0]
except:
s.close()
return ip
def user_login(user_name,user_pd): # 登录,先读取密码文件,然后查看用户名和密码是否匹配
all_user = read_data("./user.txt")
if user_name in all_user.keys():
if all_user[user_name] == user_pd:
return True
return False
def user_sign(user_name,user_pd): # 用户注册,先读取密码文件,查看用户名是否重复,然后写入
try:
all_user = read_data("./user.txt")
if user_name in all_user.keys():
return False
all_user[user_name] = user_pd
write_data("./user.txt", all_user)
return True
except:
return False
# write_data("./remote_host.txt",{'user':'192.168.146.43'})
def func_add_1():
all_host = read_data("./remote_host.txt") # 读取远程用户名和ip对应关系的文件
ret_msg = [] # 返回的信息
kvm_ctr = KVM_Control() # 创建kvm控制对象
if kvm_ctr.createConnect(): # 默认连接本机
ret_msg.append(kvm_ctr.Host_info()) # 加入本机信息
for user_ip,user_name in all_host.items(): # 依次获取远程主机的信息,并加入
if user_ip == get_host_ip():
continue
if kvm_ctr.createConnect(user_name,user_ip):
ret_msg.append(kvm_ctr.Host_info())
return ret_msg
def func_add_2(hostname,name,run_memory,disk_memory):
print(hostname,name,run_memory,disk_memory)
def func_add_3(hostname,dom_name):
all_host = read_data("./remote_host.txt")
if hostname not in all_host.keys():
return (1,"该主机不在管理范围内")
kvm_ctr = KVM_Control() # 创建kvm控制对象
ip = get_host_ip()
if ip == hostname:
kvm_ctr.createConnect() # 连接本机
if kvm_ctr.start(dom_name):
return (0,"success")
if kvm_ctr.createConnect(all_host[hostname], hostname):
if kvm_ctr.start(dom_name):
return (0,"success")
return (1,"fail") # 失败
def func_add_4():
all_host = read_data("./remote_host.txt") # 读取远程用户名和ip对应关系的文件
ret_msg = [] # 返回的信息
kvm_ctr = KVM_Control() # 创建kvm控制对象
if kvm_ctr.createConnect(): # 默认连接本机
ret_msg+=kvm_ctr.VirMachine_info()
for user_ip,user_name in all_host.items(): # 依次获取远程主机的信息,并加入
if user_ip == get_host_ip():
continue
if kvm_ctr.createConnect(user_name, user_ip):
ret_msg+=kvm_ctr.VirMachine_info()
return ret_msg
def func_add_5(hostname,dom_name): # 启动虚拟机
all_host = read_data("./remote_host.txt") # 读取远程用户名和ip对应关系的文件
if hostname not in all_host.keys():
return (1,"该主机不在管理范围内")
kvm_ctr = KVM_Control() # 创建kvm控制对象
ip = get_host_ip()
if ip==hostname:
kvm_ctr.createConnect() # 连接本机
if kvm_ctr.start(dom_name):
return (0,"success")
if kvm_ctr.createConnect(all_host[hostname], hostname):
if kvm_ctr.start(dom_name):
return (0,"success")
return (1,"fail") # 失败
def func_add_6(hostname,dom_name): # 关闭虚拟机
all_host = read_data("./remote_host.txt")
if hostname not in all_host.keys():
return (1,"该主机不在管理范围内")
kvm_ctr = KVM_Control() # 创建kvm控制对象
ip = get_host_ip()
if ip == hostname:
kvm_ctr.createConnect() # 连接本机
if kvm_ctr.shutdown(dom_name):
return (0,"success")
if kvm_ctr.createConnect(all_host[hostname], hostname):
if kvm_ctr.shutdown(dom_name): # 连接远程主机
return (0,"success")
return (1,"fail") # 失败
def func_add_7():
all_host = read_data("./remote_host.txt")
all_kvm_machine = func_add_4()
print(all_kvm_machine)
alive_dom = {}
for dom in all_kvm_machine:
if dom['status']=="running":
alive_dom[dom['IP']]="user"
write_data("./alive_dom.txt",alive_dom)
with open("./mpi_config.txt","w") as fp:
for IP,username in alive_dom.items():
write_str = "{0}:{1}\n".format(IP,2)
fp.write(write_str)
ssh = SSH()
for IP, username in alive_dom.items():
print(IP)
ssh.Connect(IP,username,"123456")
ssh.Put("./mpi_config.txt","/home/user/mpich-3.2/examples/mpi_config.txt")
# ssh.Put("./mpi_sort_last", "/home/user/mpich-3.2/examples/mpi_sort_last")
# ssh.Put("./datacatch.txt", "/home/user/mpich-3.2/examples/datacatch.txt")
ssh.Close()
IP = list(alive_dom.keys())[0]
print(IP)
username = alive_dom[IP]
ssh.Connect(IP, username, "123456")
print("run")
# ssh.Command("ifconfig")
# ssh.Command("mpiexec -n 10 -f /home/user/mpich-3.2/examples/mpi_config.txt /home/user/mpich-3.2/examples/mpi_sort_last\n")
# ssh.Command("ifconfig")
# print("over")
# ssh.Get("/home/user/mpich-3.2/examples/result.txt", "./result.txt")
ssh.Close()
return True