Blog

  • python操作json

    首先操作一下python中的字典,首先是空字典eth,在其中添加数据eth0,eth1并对应两个ip

    >>> eth = {}
    >>> eth['eth0'] = '192.168.2.12'
    >>> print eth
    {'eth0': '192.168.2.12'}
    >>> eth['eth1'] = '223.5.5.5'
    >>> print eth
    {'eth1': '223.5.5.5', 'eth0': '192.168.2.12'}

    json与python中dict互相转换,把dict转换成json-使用json.dumps(),将json转换为dict-使用json.loads(),json.loads()返回的是一个dictionary.

    >>> import json
    >>> ethjson = json.dumps(eth)
    >>> type(ethjson)
    <type 'str'>
    >>> print ethjson
    {"eth1": "223.5.5.5", "eth0": "192.168.2.12"}
    >>> ethdict = json.loads(ethjson)
    >>> type(ethdict)
    <type 'dict'>
    >>> print ethdict
    {u'eth1': u'223.5.5.5', u'eth0': u'192.168.2.12'}
    >>> print ethdict['eth0'], ethdict['eth1']
    192.168.2.12 223.5.5.5
    

    判断json里是否有某个key

    if 'text' in post['caption'].keys():      #在keys中是否有text
    if 'text' in post['caption']:    # 在caption下是否有text
    if 'ipv4' in output['ansible_facts']['ansible_int']:  # 在ansible_facts下的ansible_int下是否有ipv4

    有时候需要临时生成一个格式化过的json,可以使用json.tool模块来格式化

    echo '{"json":"obj"}' | python -m json.tool
    
    {
    
        "json": "obj"
    
    }
    
  • python分割字符串split,filter

    现有字符串,需要取出用空格分隔的第一段,操作如下

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> product_model.split(' ')[0]
     'WS-C2960G-24TC-L'

    不带参数的split(),会把所有空格(空格符、制表符、换行符)当作分隔符,如果有这些“空格”,则可这样写

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> product_model.split()[0]
    截取 1 到 最后
    >>> product_model.split()[1:]

    使用filter更多的是过滤,根据

    >>> product_model = 'WS-C2960G-24TC-L - Fixed Module 0'
    >>> filter(None, product_model.split('-'))
     ['WS', 'C2960G', '24TC', 'L ', ' Fixed Module 0']
  • mongodb操作

    mongodb端口为27017

    http://127.0.0.1:27017

    It looks like you are trying to access MongoDB over HTTP on the native driver port.

    mongodb的结构为database, collection,

    创建database,

    > use blog
     switched to db blog

    查看已经存在的db 及其占用空间

    > show dbs
     admin (empty)
     blog 0.078GB
     example 0.078GB
     local 0.078GB

    接下来在collection里添加json格式的内容

    > db.posts.insert({'title':'learn mongo','tag':'db'})
     WriteResult({ "nInserted" : 1 })
     > db.posts.insert({'title':'learn mysql','tag':'db'})
     WriteResult({ "nInserted" : 1 })

    查看名为posts的collection的所有内容

    > db.posts.find()
     { "_id" : ObjectId("53d1b11aecbaca2dd97bc8d8"), "title" : "learn mongo", "tag" : "db" }
     { "_id" : ObjectId("53d1b124ecbaca2dd97bc8d9"), "title" : "learn mysql", "tag" : "db" }

    查看已经有的collections

    > show collections
     posts
     system.indexes

    清空collection

    > db.posts.remove()
     2014-07-25T09:30:33.139+0800 remove needs a query at src/mongo/shell/collection.js:299

    删除collection

    > db.posts.drop()
     true

    删除当前数据库

    > db.dropDatabase()

    五,更多命令
    db.AddUser(username,password) 添加用户

    db.auth(usrename,password) 设置数据库连接验证

    db.cloneDataBase(fromhost) 从目标服务器克隆一个数据库
    db.commandHelp(name) returns the help for the command
    db.copyDatabase(fromdb,todb,fromhost) 复制数据库fromdb—源数据库名称,todb—目标数据库名称,fromhost—源数据库服务器地址
    db.createCollection(name,{size:3333,capped:333,max:88888}) 创建一个数据集,相当于一个表
    db.currentOp() 取消当前库的当前操作
    db.dropDataBase() 删除当前数据库
    db.eval(func,args) run code server-side
    db.getCollection(cname) 取得一个数据集合,同用法:db[‘cname’] or
    db.getCollenctionNames() 取得所有数据集合的名称列表
    db.getLastError() 返回最后一个错误的提示消息
    db.getLastErrorObj() 返回最后一个错误的对象
    db.getMongo() 取得当前服务器的连接对象get the server
    db.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr of a replica pair
    db.getName() 返回当操作数据库的名称
    db.getPrevError() 返回上一个错误对象
    db.getProfilingLevel()
    db.getReplicationInfo() 获得重复的数据
    db.getSisterDB(name) get the db at the same server as this onew
    db.killOp() 停止(杀死)在当前库的当前操作
    db.printCollectionStats() 返回当前库的数据集状态
    db.printReplicationInfo()
    db.printSlaveReplicationInfo()
    db.printShardingStatus() 返回当前数据库是否为共享数据库
    db.removeUser(username) 删除用户
    db.repairDatabase() 修复当前数据库
    db.resetError()
    db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}
    db.setProfilingLevel(level) 0=off,1=slow,2=all
    db.shutdownServer() 关闭当前服务程序

    db.version() 返回当前MongoDB版本信息

    > db.version()
    2.6.0

    db.test.find({id:10}) 返回test数据集ID=10的数据集
    db.test.find({id:10}).count() 返回test数据集ID=10的数据总数
    db.test.find({id:10}).limit(2) 返回test数据集ID=10的数据集从第二条开始的数据集
    db.test.find({id:10}).skip(8) 返回test数据集ID=10的数据集从0到第八条的数据集
    db.test.find({id:10}).limit(2).skip(8) 返回test数据集ID=1=的数据集从第二条到第八条的数据
    db.test.find({id:10}).sort() 返回test数据集ID=10的排序数据集
    db.test.findOne([query]) 返回符合条件的一条数据
    db.test.getDB() 返回此数据集所属的数据库名称
    db.test.getIndexes() 返回些数据集的索引信息
    db.test.group({key:…,initial:…,reduce:…[,cond:…]})
    db.test.mapReduce(mayFunction,reduceFunction,)
    db.test.remove(query) 在数据集中删除一条数据
    db.test.renameCollection(newName) 重命名些数据集名称
    db.test.save(obj) 往数据集中插入一条数据
    db.test.stats() 返回此数据集的状态
    db.test.storageSize() 返回此数据集的存储大小
    db.test.totalIndexSize() 返回此数据集的索引文件大小
    db.test.totalSize() 返回些数据集的总大小
    db.test.update(query,object[,upsert_bool]) 在此数据集中更新一条数据
    db.test.validate() 验证此数据集
    db.test.getShardVersion() 返回数据集共享版本号

    六,MongoDB语法与现有关系型数据库SQL语法比较
    MongoDB语法 MySql语法
    db.test.find({‘name’:’foobar’}) <==> select * from test where name=’foobar’
    db.test.find() <==> select * from test
    db.test.find({‘ID’:10}).count() <==> select count(*) from test where ID=10
    db.test.find().skip(10).limit(20) <==> select * from test limit 10,20
    db.test.find({‘ID’:{$in:[25,35,45]}}) <==> select * from test where ID in (25,35,45)
    db.test.find().sort({‘ID’:-1}) <==> select * from test order by ID desc
    db.test.distinct(‘name’,{‘ID’:{$lt:20}}) <==> select distinct(name) from test where ID<20
    db.test.group({key:{‘name’:true},cond:{‘name’:’foo’},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}}) <==> select name,sum(marks) from test group by name
    db.test.find(‘this.ID<20’,{name:1}) <==> select name from test where ID<20
    db.test.insert({‘name’:’foobar’,’age’:25})<==>insert into test (‘name’,’age’) values(‘foobar’,25)
    db.test.remove({}) <==> delete * from test
    db.test.remove({‘age’:20}) <==> delete test where age=20
    db.test.remove({‘age’:{$lt:20}}) <==> elete test where age<20
    db.test.remove({‘age’:{$lte:20}}) <==> delete test where age<=20
    db.test.remove({‘age’:{$gt:20}}) <==> delete test where age>20
    db.test.remove({‘age’:{$gte:20}}) <==> delete test where age>=20
    db.test.remove({‘age’:{$ne:20}}) <==> delete test where age!=20
    db.test.update({‘name’:’foobar’},{$set:{‘age’:36}}) <==> update test set age=36 where name=’foobar’
    db.test.update({‘name’:’foobar’},{$inc:{‘age’:3}}) <==> update test set age=age+3 where name=’foobar’

    注意以上命令大小写敏感

  • rabbitmq添加用户

    现添加admin,密码admin,管理员权限

    add_user  
    rabbitmqctl add_user admin admin
    rabbitmqctl list_users
    rabbitmqctl set_user_tags admin administrator
    rabbitmqctl list_users
    

    添加成功后赋权限

    rabbitmqctl set_permissions -p / myuser ".*" ".*" ".*"

    测试用户名密码正确性

    curl -i -u 'admin':'123456'  rabbitmq.foobar.io:15672/api/whoami
    
  • virtualbox命令行启动

    VBoxManage startvm winxp -type vrdp
    Waiting for VM “winxp” to power on…
    VM “winxp” has been successfully started.

  • python管理dns

    使用dnspython模块

    pip install dnspython

    查询A记录

    import dns.resolver
    ip = dns.resolver.query("jpuyy.com", "A")
    for i in ip:
        print i

    写个函数查询多条记录

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    
    import dns.resolver
    
    hosts = ["jpuyy.com", "hupu.com", "hao123.com", "ifeng.com"]
    
    def query(host_list = hosts):
        collection = []
        for host in host_list:
            ip  =  dns.resolver.query(host,"A")
            for i in ip:
                collection.append(str(i))
        return collection
    
    if __name__ == "__main__":
        for arec in query():
            print arec
    

    来自python for unix and linux system Administration