需求:
有时候物理机意外断电或者节假日关机省电,重新开机后虚拟机的电源老是需要手动去命令行启动,机器多了觉得很麻烦。
首先要获取想要启动的虚拟机的uuid,然后再启动它。
于是就想把机器上的虚拟机列表保存到excel里面,需要启动哪台,改下标志位,批量启动就好了,于是就有了下面的代码:
# coding='utf-8'
import paramiko
import xlwt
import xlrd
import threadpool
import os
def save_excel(hostname, password, wbk):
'''
查询指定主机所有虚拟机,保存到excel文件中
'''
sheet = wbk.add_sheet(hostname)
sheet.write(0, 0, '名称') # 写入表头
sheet.write(0, 1, '状态')
sheet.write(0, 2, 'uuid')
sheet.write(0, 3, '是否启动')
result = ssh_connt(hostname, password, 'xe vm-list')
result_list = result.split('
')
data = int((len(result_list)-1)/5)
for i in range(data):
print(result_list[5*i][23:], result_list[5*i+1][23:], result_list[5*i+2][23:])
sheet.write(i+1, 0, result_list[5*i+1][23:]) # 第i+1行第1列写入名称
sheet.write(i+1, 1, result_list[5*i+2][23:]) # 第i+1行第2列写入状态
sheet.write(i+1, 2, result_list[5*i][23:]) # 第i+1行第3列写入uuid
sheet.write(i+1, 3, '否') # 第i+1行第4列写入是否需要启动,默认为否,需要手动调整为是
def ssh_connt(hostname, password, cmd):
'''
ssh连接后执行执行命令,返回执行结果
'''
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, port=22, username='root', password=password)
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read() or stderr.read()
ssh.close()
print(hostname, ' : ', result.decode('utf-8'))
return result.decode('utf-8')
def read_excel(sheetname, password):
'''
读取excel,将其中未开机且标记需要启动的虚拟机进行启动
'''
wbk = xlrd.open_workbook('服务器2.xls')
sheet = wbk.sheet_by_name(sheetname)
nrows = sheet.nrows # 行数
listf = []
for i in range(1, nrows):
vmname, statu, uuid, is_start = sheet.row_values(i)
if statu == 'halted' and is_start == '是':
lista = []
print(sheet.row_values(i))
cmd = f'xe vm-start uuid={uuid}'
lista.extend((sheetname, password, cmd))
listf.append((lista, None))
# ssh_connt(sheetname, password, cmd)
runners(ssh_connt, listf)
def runners(func, args):
'''
用于多线程运行
'''
pool = threadpool.ThreadPool(4)
requests = threadpool.makeRequests(func, args)
[pool.putRequest(req) for req in requests]
pool.wait()
if __name__ == "__main__":
host_list = {'192.168.206.76':'winserver123',
'192.168.206.25':'winserver123!@#',
'192.168.212.207':'root123'}
if os.path.exists('服务器.xls'): # 文件存在则读取,否则生成文件
listf = []
for host, pwd in host_list.items():
lista = []
lista.extend((host, pwd))
listf.append((lista, None))
# save_excel(host, pwd, wbk)
runners(read_excel, listf)
else:
wbk = xlwt.Workbook()
listf = []
for host, pwd in host_list.items():
lista = []
lista.extend((host, pwd, wbk))
listf.append((lista, None))
# save_excel(host, pwd, wbk)
runners(save_excel, listf)
wbk.save('服务器.xls')
具体效果如下:
生成的excel文件:
运行效果: