qemu guest agent修改密码(python)
2015-07-06 16:03
260 查看
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 re if 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" % cmd stream=os.popen(cmd).read() return None if not stream else json.loads(stream) def guestFileRead(path): file_handle=-1 try: file_handle=EXE(FILE_OPEN_READ % path)["return"] file_content=EXE(FILE_READ % (file_handle,1024000))["return"]["buf-b64"] except Exception,ex: print Exception,":",ex return None finally: EXE(FILE_CLOSE % file_handle) return file_content def guestFileWrite(path,content): file_handle=-1 try: file_handle=EXE(FILE_OPEN_WRITE % path)["return"] write_count=EXE(FILE_WRITE % (file_handle,content))["return"]["count"] except Exception,ex: print Exception,":",ex return -1 finally: EXE(FILE_CLOSE % file_handle) return write_count def 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" % content user_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] break content=base64.standard_b64encode("\n".join(user_array)) write_count=guestFileWrite(path,content) print write_count>0 resetPwd("/etc/shadow",pwd_)若virsh qemu-agent-command执行返回没有结果,则使用/var/lib/libvirt/qemu/下的socket文件进行通信,请参考python实例浅谈下的文章。
相关文章推荐
- 浅谈 Python 的 with 语句
- 用PyInstaller把Python代码打包成单个独立的exe可执行文件
- 理解Python的With语句
- Python 学习 --- 基础知识
- 判断Python输入是否为数字
- Python实现图像几何变换
- Python统计日志中每个IP出现次数的方法
- python BinaryTree
- python统计日志ip访问数的方法
- python检查指定文件是否存在的方法
- vim的python代码检测工具
- windows上安装numpy和scipy
- 安装python至windows
- Python单例模式的4种实现方法
- Python - 属性访问
- python代码运行显示PC参数
- Python正则表达式
- XGBoost:在Python中使用XGBoost
- Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
- python转换字符串为摩尔斯电码的方法