zoukankan      html  css  js  c++  java
  • python自动化运维记录

    解释器

    #!/usr/bin/env python
    # coding: utf-8
    # -*- coding: utf-8 -*-
    

    基础学习脚本

    +加号拼接

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import getpass
    
    name = input("Please input your name")
    pwd = getpass.getpass("please input your passwd")
    print("My name is" + name, "and passwd is" + pwd)
    

    输出

    # chmod +x study1.py
    # pytohon study1.py
    Please input your namehuang
    please input your passwd
    My name ishuang and passwd is123
    

    逗号 空格分割:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import getpass
    
    name = input("Please input your name")
    pwd = getpass.getpass("please input your passwd")
    print("My name is", name, "and passwd is", pwd)
    

    输出:

    # python study1.py 
    Please input your namehuang
    please input your passwd
    My name is huang and passwd is 123
    

    格式化输出:

    #!/usr/bin/env python
    # coding: utf-8
    
    name = input("please input your name: ")
    age = input("please input your age: ")
    job = input("please input your job: ")
    
    msg = '''
    # 默认字符串形式输出%s
    Information of %s 
    -----------------
    Name: %s
    Age: %s
    Job: %s
    ''' %(name,name,age,job)
    
    print(msg)
    

    输出:

    # python study2.py 
    please input your name: huang
    please input your age: 12
    please input your job: engineer
    
    Information of huang
    -----------------
    Name: huang
    Age: 12
    Job: engineer
    

    python3中格式化输出默认接收的都是字符串,如果是数字则需要另外强制转化为init()转化为数字类型

    #!/usr/bin/env python
    # coding: utf-8
    
    name = input("please input your name: ")
    age = input("please input your age: ")
    job = input("please input your job: ")
    
    msg = '''
    Information of %s
    -----------------
    Name: %s
    Age: %d
    Job: %s
    ''' %(name,name,age,job)
    
    print(msg)
    

    运行:

    please input your name: 1
    please input your age: 12
    please input your job: 12
    Traceback (most recent call last):
      File "study2.py", line 14, in <module>
        ''' %(name,name,age,job)
    TypeError: %d format: a number is required, not str
    

    报错原因: age没有转化格式为数字,导致执行代码时报错,init()转化了则不会报错

    #!/usr/bin/env python
    # coding: utf-8
    
    name = input("please input your name: ")
    age = input("please input your age: ")
    age = int(age)
    job = input("please input your job: ")
    
    msg = '''
    Information of %s
    -----------------
    Name: %s
    Age: %d
    Job: %s
    ''' %(name,name,age,job)
    
    print(msg)
    

    运行:

    # python study2.py 
    please input your name: huang
    please input your age: 12
    please input your job: student
    
    Information of huang
    -----------------
    Name: huang
    Age: 12
    Job: student
    

    模块

    sys

    sys.argv 从外部向程序内部传递参数

    #!/usr/bin/env python
    # coding: utf-8
    
    import sys
    
    print(sys.argv)
    print(sys.argv[0])
    print(sys.argv[2])
    

    运行:[获取执行脚本时带上的参数被获取到]

    # python module_test1.py  hello world
    ['module_test1.py', 'hello', 'world']
    module_test1.py
    world
    
    #!/usr/bin/env python
    
    import sys
    
    for i in range(len(sys.argv)):
      print('argv{0}: type is {1}, value is {2}'.format(i, type(sys.argv[i]), sys.argv[i]))
    
    # python sys_argv.py 1 2 s 
    
    argv0: type is <class 'str'>, value is sys_argv.py
    argv1: type is <class 'str'>, value is 1
    argv2: type is <class 'str'>, value is 2
    argv3: type is <class 'str'>, value is s
    

    循环

    while 循环

    eg1

    [1:] 意义:遍历,去掉列表中的第一个元素(下表为0),去后面的元素进行操作

    #!/usr/bin/env python
    # coding: utf-8
    url = "lannister.poizon.com"
    while url:
      print(url)
      url = url[1:]
    

    运行:

    lannister.poizon.com
    annister.poizon.com
    nnister.poizon.com
    nister.poizon.com
    ister.poizon.com
    ster.poizon.com
    ter.poizon.com
    er.poizon.com
    r.poizon.com
    .poizon.com
    poizon.com
    oizon.com
    izon.com
    zon.com
    on.com
    n.com
    .com
    com
    om
    m
    
    eg2
    #!/usr/bin/env python
    # coding: utf-8
    
    x = 0;y = 10
    while x < 10:
      print(x)
      x += 1
    
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    

    [:-1]:遍历,去掉列表中的最后一个元素,去前面一个的元素进行操作

    #!/usr/bin/env python
    # coding: utf-8
    url = 'lannister.poizon.com'
    while url:
      print(url)
      url = url[:-1]
    else:
      print('game over')
    

    运行:

    lannister.poizon.com
    lannister.poizon.co
    lannister.poizon.c
    lannister.poizon.
    lannister.poizon
    lannister.poizo
    lannister.poiz
    lannister.poi
    lannister.po
    lannister.p
    lannister.
    lannister
    lanniste
    lannist
    lannis
    lanni
    lann
    lan
    la
    l
    game over
    

    函数

    pop函数

    使用: 用于一处列表中的一个元素,默认最后一个元素,并且返回该元素值
    pop(0) 删除第一个元素

    #!/usr/bin/env python
    # coding: utf-8
    
    list = [1, 2, 3, 4, 5]
    count = 0
    while list:
      print(list[0])
      list.pop()
    
    list2 = [1, 2, 3, 4, 5]
    count = 0
    while list2:
      print(list[0])
      list.pop(0)
    

    运行:

    # part 1:
    1
    1
    1
    1
    1
    # part 2:
    1
    2
    3
    4
    5
    

    场景练习脚本:

    #!/usr/bin/env python
    # coding: utf-8
    
    import getpass
    
    name = 'sihye'
    pwd = '123456'
    count = 0
    
    while True:
      if count < 3:
        print('please enter your name and passwd ')
        username = input('username: ')
        passwd = getpass.getpass('passwd: ')
        if username == name and passwd == pwd:
          print('welcome come back')
          break;
        else:
          print('wrong')
      else:
        print('you have already failed 3 times...logging out...')
        break;
      count += 1 
    

    运行:

    # python user_login.py 
    please enter your name and passwd 
    username: sihye
    passwd: 
    wrong
    please enter your name and passwd 
    username: sihye
    passwd: 
    wrong
    please enter your name and passwd 
    username: sihye
    passwd: 
    welcome come back
    

    场景二:猜年龄游戏

    #!/usr/bin/env python
    # coding: utf-8
    
    age = 8
    count = 0
    for i in range(20):
      if count < 3:
        a = int(input("age: "))
        if a == age:
          print('success')
          break
        elif a < age:
          print('smaller~')
        else:
          print('bigger~')
      else:
        b = input('continue? ')
        if b == 'yes':
          count = 0
          continue
        else:
          print('see u next time')
          break
      count += 1
    

    运行:

    # python guess_age.py 
    age: 1
    smaller~
    age: 2
    smaller~
    age: 1
    smaller~
    continue? no
    see u next time
    # python guess_age.py 
    age: 8
    success
    

    运维场景脚本

    新创脚本时可自动生成python解释器
    # 在用户的家目录下创建'.vimrc'文件
    # root用户
    # ---------
    # vim ~/.vimrc
    function HeaderPython()
    
    call setline(1, "#!/usr/bin/env python")
    
    call append(1, "#-*- coding:utf8 -*-")
    
    normal G
    
    normal o
    
    normal o
    
    endf
    
    autocmd bufnewfile *.py call HeaderPython()
    

    保存退出即可,之后创建.py文件就会自动生成解释器

    输出某个目录下所有子目录下的文件,并输出绝对路径

    方法一:用OS库

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    import os
    for root,dirs,files in os.walk('/server/scripts'):
      for name in files:
        print(os.path.join(root,name))
    

    方法二:用pathlib

    path.rglob()相当于 os.walk,可添加筛选条件
    
    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server')
    for p in path.rglob("*.py"):
      print(str(p))
    

    pathlib库

    引用:

    from pathlib import Path
    p = Path()
    p.name 获取文件名,包含所有目录名和文件名
    p.parent 获取每个文件的目录名称,一直到最后一层目录都输出,有几个文件就会输出几次
    p.parents 会输出每一个子目录,返回一个iterable
    

    场景:

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server/scripts/python')
    for p in path.rglob("*"):
      p.parents
      for i in p.parents:
        print(i)
    运行:
    server/scripts/python
    /server/scripts
    /server
    /
    /server/scripts/python
    /server/scripts
    /server
    /
    /server/scripts/python/study_base_scripts
    /server/scripts/python
    /server/scripts
    /server
    /
    

    场景二:

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server/scripts/python')
    for p in path.rglob("*"):
      print(p.parent)
    运行:
    /server/scripts/python
    /server/scripts/python
    /server/scripts/python/study_base_scripts
    /server/scripts/python/study_base_scripts
    /server/scripts/python/study_base_scripts
    

    场景三:判断文件是否存在

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server')
    path = Path(path,'scripts') # 字符串拼接,也就是后面检验的是/server/scripts是否存在
    print(path.exists())  #判断文件是否存在
    print(path.is_file()) #判断是否是文件
    print(path.is_dir()) #判断是否是目录
    

    运行:

    # python find_file.py 
    True
    False
    True
    

    场景四:遍历文件夹

    path.iterdir(): 相当域os.listdir,
    path.glob('*'), 相当于os.listdir, 可添加条件
    path.rglob('*'),相当于 os.walk , 可添加筛选条件
    
    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server/scripts')
    for p in path.glob("*ell"):
      print(p)
    print('------------------')
    for n in path.iterdir():
      print(n)
    print('------------------')
    for i in path.rglob("*.py"):
      print(i)
    print('------------------')
    

    运行:

    # python find_file.py 
    /server/scripts/shell
    ------------------
    /server/scripts/python
    /server/scripts/shell
    ------------------
    /server/scripts/python/study_base_scripts/while_test2.py
    /server/scripts/python/study_base_scripts/guess_age.py
    /server/scripts/python/study_base_scripts/user_login.py
    /server/scripts/python/study_base_scripts/name_test2.py
    /server/scripts/python/study_base_scripts/sys_argv.py
    /server/scripts/python/study_base_scripts/while_test.py
    /server/scripts/python/study_base_scripts/sys_os.py
    /server/scripts/python/study_base_scripts/while_test3.py
    /server/scripts/python/study_base_scripts/name_test1.py
    /server/scripts/python/study_base_scripts/stdout.py
    /server/scripts/python/study_base_scripts/module_test1.py
    /server/scripts/python/ops_base_scripts/find_file.py
    /server/scripts/python/ops_base_scripts/dic_list.py
    ------------------
    

    场景五:创建文件夹

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    # 第一种方式:前提是tmp文件夹必须存在,否则会报错。
    path = Path(r'/server/tmp/python') 
    path.mkdir(exist_ok=True)
    # 第二种方式:若是tmp文件不存在会递归创建文件夹。
    path = Path(r'/server/tmp/python')
    path.mkdir(exist_ok=True, parents=True)
    

    场景五: 获取文件的详细信息

    #!/usr/bin/env python
    # coding:utf-8
    
    from pathlib import Path
    
    path = Path(r'/server/scripts/python')
    
    print(path.stat())
    print(path.stat().st_size)
    print(path.stat().st_ctime)
    

    运行:

    
    

    场景六: 查看某个目录下有几个匹配类型文件

    #!/usr/bin/env python
    #-*- coding:utf8 -*-
    
    from pathlib import Path
    
    path = Path(r'/server/scripts')
    for p in path.rglob('*.py'):
      print(p.parent)
    

    运行:

    # python review.py | sort -rn | uniq -c
         13 /server/scripts/python/study_base_scripts
          4 /server/scripts/python/ops_base_scripts
    

    方法

  • 相关阅读:
    [转发]深入理解git,从研究git目录开始
    iOS系统网络抓包方法
    charles抓包工具
    iOS多线程中performSelector: 和dispatch_time的不同
    IOS Core Animation Advanced Techniques的学习笔记(五)
    IOS Core Animation Advanced Techniques的学习笔记(四)
    IOS Core Animation Advanced Techniques的学习笔记(三)
    IOS Core Animation Advanced Techniques的学习笔记(二)
    IOS Core Animation Advanced Techniques的学习笔记(一)
    VirtualBox复制CentOS后提示Device eth0 does not seem to be present的解决方法
  • 原文地址:https://www.cnblogs.com/sihye/p/12619440.html
Copyright © 2011-2022 走看看