本文主要是介绍qemu guest agent修改密码(python),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Python代码:
"""openstack中 虚拟机nova_db.instances.id 需转换为16进制 后补8位http://wiki.qemu.org/Features/QAPI/GuestAgent
"""
import os
import sys
import json
import base64
import crypt
import string
import random
import reif len(sys.argv)<3:print('Pls input argument instance password.')sys.exit(1)instance=sys.argv[1]
pwd_=sys.argv[2]FILE_OPEN_READ="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"r"}}"""FILE_OPEN_WRITE="""{"execute":"guest-file-open", "arguments":{"path":"%s","mode":"w+"}}"""FILE_READ="""{"execute":"guest-file-read", "arguments":{"handle":%s,"count":%d}}"""FILE_WRITE="""{"execute":"guest-file-write", "arguments":{"handle":%s,"buf-b64":"%s"}}"""FILE_CLOSE="""{"execute":"guest-file-close", "arguments":{"handle":%s}}"""def EXE(param):cmd="""virsh qemu-agent-command %s '%s' """ % (instance,param)#print "Exe command:%s" % cmdstream=os.popen(cmd).read()return None if not stream else json.loads(stream)def guestFileRead(path):file_handle=-1try:file_handle=EXE(FILE_OPEN_READ % path)["return"]file_content=EXE(FILE_READ % (file_handle,1024000))["return"]["buf-b64"]except Exception,ex:print Exception,":",exreturn Nonefinally:EXE(FILE_CLOSE % file_handle)return file_contentdef guestFileWrite(path,content):file_handle=-1try:file_handle=EXE(FILE_OPEN_WRITE % path)["return"]write_count=EXE(FILE_WRITE % (file_handle,content))["return"]["count"]except Exception,ex:print Exception,":",exreturn -1finally:EXE(FILE_CLOSE % file_handle)return write_countdef genPwd(pwd):salt=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))return crypt.crypt(pwd, "$6$%s" % salt)def resetPwd(path,pwd):content=base64.standard_b64decode(guestFileRead(path))#print "Read file content:%s" % contentuser_array=re.split("\n",content)for i,line in enumerate(user_array):info=line.split(":")if info[0]=="root":info[1]=genPwd(pwd)user_array[i]=":".join(info)#print "After change,user info:%s" % user_array[i]breakcontent=base64.standard_b64encode("\n".join(user_array)) write_count=guestFileWrite(path,content)print write_count>0resetPwd("/etc/shadow",pwd_)
若
virsh qemu-agent-command执行返回没有结果,则使用/var/lib/libvirt/qemu/下的socket文件进行通信,请参考python实例浅谈下的文章。
这篇关于qemu guest agent修改密码(python)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!