python运维脚本代码
1、生成批量加用户sql语句
游戏测试时,经常会收到运营部门的加账户需求,用以下代码可以批量生成插入账户的sql语句:
for i in range(1, 500):
sql = ("insert into account(name,passwd) values('qatest_%d','7c4a8d09ca3762af61e59520943dc26494f8941b');"%(i));
print ("qatest_%d, 7c4a8d09ca3762af61e59520943dc26494f8941b"%(i))
2、python操作mysql(需要安装mysql-python模块)
# coding=utf-8
#!/usr/bin/env python
import
MySQLdb
try:
conn=MySQLdb.connect(host='127.0.0.1',user='username',passwd='password123',port=3306,charset='utf8')
cur=conn.cursor()
conn.select_db('database1')
sql = "SELECT now(),COUNT(*) FROM user_info WHERE heartbeat >=DATE_ADD(NOW(), INTERVAL -5 MINUTE);"
result = cur.execute(sql)
for item in cur.fetchall():
print "Time:%s, online numbers:%s"%(item[0], item[1])
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
3、利用paramiko远程执行指令
一个项目的自动化运维工具部分功能就是用paramiko模块写的,paramoko的详细安装,请参考:
http://www.cnblogs.com/gannan/archive/2012/02/06/2339883.html,
一个简单的执行命令示例:
#!/usr/bin/python
import sys
import paramiko
def pycmd(server, port, username, password,
shellcmd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()
ssh.connect(server, port, username, password)
stdin, stdout, stderr = ssh.exec_command(shellcmd)
print stdout.readlines()
ssh.close()
if __name__ == "__main__":
pycmd("xxx.xxx.xxx.xxx", 22, "root", "password", sys.argv[1])