Month: July 2014

  • ansible-fetch获取服务器上的文件

    目标是获取两台服务器下root,www用户的crontab文件,并保存在本地的fetched目录。

    main.yml文件如下

    – hosts: all
    tasks:
    – fetch: src=/var/spool/cron/www dest=fetched/cron-www-{{ ansible_hostname }} flat=yes

    – fetch: src=/var/spool/cron/root dest=fetched/cron-root-{{ ansible_hostname }} flat=yes

    执行完之后的目录结构如下

    [[email protected] fetch-crontab]# tree
    .
    ├── fetched
    │   ├── cron-root-2.jpuyy.com
    │   └── cron-www-1.jpuyy.com
    ├── hosts
    └── main.yml

  • ansible使用笔记-改主机名

    针对所有主机修改主机名

    - hosts: all
     hostname: name={{ hostname }}
  • 通过python netsnmp读取cisco交换机信息

    首先使用snmpwalk跑一遍看一下有没有问题

    snmpwalk -v 2c -c public 10.103.33.1

    这里测试用交换机是 WS-C2960G-24TC-L,以下脚本用于读取管理ip,序列号,型号,主机名。思科的交换机snmp oid信息都可通过如下网址查询http://tools.cisco.com/Support/SNMP/do/BrowseOID.do

    首先安装python的snmp依赖包

    yum install net-snmp-python

    获取信息的脚本

    #!/usr/bin/env python
    # by yangyang89
    # using snmp get switch serial, model, manage ip ..
    import netsnmp
    import sys
    import urllib
    import urllib2
    
    # reference python for linux and unix administration page 209
    class Snmp(object):
        """A basic SNMP session"""
        def __init__(self,oid="sysDescr", Version=2):
            self.oid = oid
            self.version = Version
            self.destHost = sys.argv[1]
            self.community = sys.argv[2]
    
        def query(self):
            """Creates SNMP query session"""
            try:
                result = netsnmp.snmpwalk(self.oid, Version = self.version, DestHost = self.destHost, Community = self.community)
            except Exception, err:
                print err
                result = None
            return result
    
    print sys.argv[1] + sys.argv[2]
    if sys.argv[1] and sys.argv[2]:
        s = Snmp()
        #print s.query()
        #s.oid = "2.47.1.1.1.1.11.1001"
        #http://tools.cisco.com/Support/SNMP/do/BrowseOID.do
        s.oid = ".1.3.6.1.2.1.4.20.1.1" # manage ip ipAdEntAddr
        ip = s.query()
        telnet = ip[0]
        print "ip: " + telnet
        
        s.oid = ".1.3.6.1.4.1.9.3.6.3" # serial numbers chassisId
        serial = s.query()
        serial = serial[0]
        print "serial: " + serial
        
        s.oid = ".1.3.6.1.2.1.47.1.1.1.1" # product_model entPhysicalEntry
        product_model = s.query()
        product_model = product_model[1].split(' ')[0]
        print "product_model: " + product_model
        #print s.query()
        
        s.oid = ".1.3.6.1.4.1.9.2.1.3" # hostname hostName
        hostname = s.query()
        hostname = hostname[0]
        print "hostname: " + hostname
    
    
  • macOS terminal.app 设置

    基本上都用terminal.app, 使用多标签页,快捷键如下

    打开新的窗口

    command + n

    打开新的标签页

    command + t

    关闭当前标签页

    command + w

    tab互相切换

    command + shift + { 上一个tab
    command + shift + } 下一个tab

    shell 配置页
    when the shell exits: close if the shell exited cleanly

    terminal 设置

    Grass Courier 16 pt.
    使用标准键盘的小键盘 偏好设置 – 高级 – uncheck 允许VT100应用程序 小键盘模式

  • tee命令

    The tee utility copies standard input to standard output, making a copy in zero or more files. The output is unbuffered.

    将date执行的命令保存到文件里

     date > today.txt

    将date的输出传到today.txt,且打印到屏幕上

     date | tee today.txt

    结合管道命令,实现更多功能,比如cron文件如下

    */10 * * * * /usr/sbin/ntpdate 192.168.1.22
     15 5 * * * touch /tmp/nginx/fcgi

    现在需要将cron备份,并将ip更换为192.168.1.88,使用tee可实现备份并修改

    crontab -l | tee cron.backup | sed 's/192.168.1.22/192.168.1.88/g' | crontab -

    tee后面跟文件,会默认将输出覆盖到文件中,如果使用追加模式,加-a

    date | tee -a today.txt

    如果追加到多个文件

    date | tee today1.txt today2.txt today3.txt

    在vim中当用户没有权限保存文件时,使用root来tee输出到此文件(%在vim中表示当前文件),这时会提示文件有变动,就会保存成功。

    :w !sudo tee % > /dev/null

  • 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"
    
    }