本站以分享各种运维经验和运维所需要的技能为主
《python》:python零基础入门学习
《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战
《k8》暂未更新
《docker学习》暂未更新
《ceph学习》ceph日常问题解决分享
《日志收集》ELK+各种中间件
《运维日常》持续更新中
用于执行一些shell操作
- import shutil
- import os
- f1 = open('/etc/hosts', 'rb')
- f2 = open('/tmp/zj.txt', 'wb')
- shutil.copyfileobj(f1 , f2)
- f1.close()
- f2.close()
-
- #拷贝文件,cp /etc/hosts /tmp/zhuji
- shutil.copy('/etc/hosts','/tmp/yff')
- shutil.copy('/etc/hosts','/tmp/yff.txt')
-
- #cp -p /etc/hosts /tmp/zhuji
- shutil.copy2('/etc/hosts','/tmp/yff2')
-
- #cp -r /etc/security /tmp/anquan
- shutil.copytree('/etc/security','/tmp/anquan')
-
- #mv /tmp/anquan /var/tmp/
- shutil.move('/tmp/anquan','/var/tmp')
-
- #chown bob.bob /tmp/yyf
- shutil.chown('/tmp/yff.txt',user='yyf',group='yyf')
- shutil.chown('/tmp/yff',user='yyf',group='yyf')
- shutil.chown('/tmp/yff2',user='yyf',group='yyf')
-
- #rm -rf /var/tmp/anquan ---只能删除目录
- shutil.rmtree('/var/tmp/anquan')
- #rm -rf /tmp/yyf ----删除文件
- os.remove('/tmp/yff2')
-
用于调用系统命令
- >>> import subprocess
- >>> result = subprocess.run('id root', shell=True)
- uid=0(root) gid=0(root) 组=0(root)
-
- >>> result = subprocess.run('id root ; id yyf', shell=True)
- uid=0(root) gid=0(root) 组=0(root)
- uid=1003(yyf) gid=1003(yyf) 组=1003(yyf)
-
- >>> result = subprocess.run('id root ; id ddd', shell=True)
- uid=0(root) gid=0(root) 组=0(root)
- id: ddd: no such user
-
- >>> result.args
- 'id root ; id ddd'
-
- >>> result.returncode -----相当于 shell 的$?
- 1
-
- #如果不希望把命令的执行结果打印在屏幕上,可以使用以下方式:
- >>> import subprocess
- >>> result = subprocess.run('id root; id sss', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- >>> result.stderr
- b'id: sss: no such user\n'
- >>> result.stdout
- b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
- >>> result.stdout.decode()
- 'uid=0(root) gid=0(root) 组=0(root)\n'
- >>>
- py:
- import subprocess
- result = subprocess.run('id root ; id fff ', shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- print(result.stderr)
- print(result.stdout)
- print(result.stdout.decode())
-
- 测试结果:
- b'id: fff: no such user\n'
- b'uid=0(root) gid=0(root) \xe7\xbb\x84=0(root)\n'
- uid=0(root) gid=0(root) 组=0(root)
- import sys
- import subprocess
-
- def ping(host):
- result = subprocess.run(
- 'ping -c2 %s &> /dev/null' % host , shell=True
- )
- if result.returncode == 0 :
- print('%s:up' % host)
- else:
- print('%s:down' % host)
-
- if __name__ == '__main__':
- ping(sys.argv[1])
- >>> a=b=[10,20]
- >>> b.append(40)
- >>> a
- [10, 20, 40]
- >>> b
- [10, 20, 40]
- >>> a,b = 10 ,20
- >>> a
- 10
- >>> b
- 20
- >>> c, d = (10,20)
- >>> c
- 10
- >>> d
- 20
- >>> e, f = [10, 20 ]
- >>> e
- 10
- >>> b
- 20
- >>> a = [100]
- >>> a
- [100]
- >>> g, f = 'ab'
- >>> g
- 'a'
- >>> f
- 'b'
-
- 两个变量互换
-
- >>> t = a
- >>> a = b
- >>> b = t
- >>> a
- 20
- >>> b
- [100]
- >>> a , b = b ,a
- >>> a
- [100]
- >>> b
- 20
-
- >>> import keyword
- >>> keyword.kwlist
- ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
- >>> 'pass' in keyword.kwlist
- True
- >>> keyword.iskeyword('is')
- True
-
內建不是关键字,可以被覆盖,除非你不用它
len = 100
len('abc') -----无法使用原来的功能
- ```python
- #!/usr/local/bin/python3 # 解释器
- """模块文件名
- 模块文件的说明文字,即文档字符串,用于help帮助
- """
- import sys # 模块导入
- from random import randint, choice
-
-
- hi = 'Hello World' # 全局变量
- debug = True
-
-
- class MyClass: # 类的定义
- pass
-
-
- def func1(): # 函数定义
- pass
-
-
- if __name__ == '__main__': # 主程序代码
- func1()
- ```
- #!/usr/local/bin/python3 ---解释器
- """演示模块
- 辣鸡
- """
- hi = 'hello shabichao' # 全局变量之后才可以调用
-
-
- def pstar(n=30):
- "用于打印n个星号"
- print('*' * n)
-
-
- if __name__ == '__main__':
- print(hi)
- pstar()
- pstar(50)
-
-
- >>> import star
- >>> help(star)
- Help on module star:
- NAME
- star - 演示模块
- DESCRIPTION
- 辣鸡
- FUNCTIONS
- pstar(n=30)
- 用于打印n个星号
- DATA
- hi = 'hello shabichao'
- FILE
- /root/nsd1907/py01/day03/star.py
- >>> import os
- >>> os.path.ex
- os.path.exists( os.path.expanduser( os.path.expandvars( os.path.extsep
- >>> os.path.ex
- os.path.exists( os.path.expanduser( os.path.expandvars( os.path.extsep
- >>> os.path.exists('/tmp/yff')
- True
- >>> os.path.exists('/tmp/yffdd')
- False
- 1. 发呆。思考程序的动作方式(交互?非交互?)
- ```shell
- 文件名: /
- 文件已存在,请重试。
- 文件名: /etc/hosts
- 文件已存在,请重试。
- 文件名: /tmp/abc.txt
- 请输入文件内容,在单独的一行输入end结束。
- (end to quit)> hello world!
- (end to quit)> how are you?
- (end to quit)> the end
- (end to quit)> end
- # cat /tmp/abc.txt
- hello world!
- how are you?
- the end
- ```
- 2. 分析程序有哪些功能,把这些功能编写成函数
- ```python
- def get_fname():
- '用于获取文件名'
- def get_content():
- '用于获取内容'
- def wfile(fname, content):
- '用于将内容content,写入文件fname'
- ```
- 3. 编写程序的主体,按一定的准则调用函数
- ```python
- def get_fname():
- '用于获取文件名'
- def get_content():
- '用于获取内容'
- def wfile(fname, content):
- '用于将内容content,写入文件fname'
- if __name__ == '__main__':
- fname = get_fname()
- content = get_content()
- wfile(fname, content)
- ```
- 4. 完成每一个具体的函数
- """创建文件
- 这是一个用于创建文件的脚本,用到的有三个函数
- """
- import os
-
-
- def get_fname():
- '用于获取文件名'
- while 1 :
- fname = input('文件名: ')
- if not os.path.exists(fname):
- break
- print('文件已存在,请重新输入: ')
- return fname
-
-
- def get_content():
- '用于获取内容'
- content = []
-
- print('请输入文件内容,在单独的一行输入end结束')
- while 1:
- line = input('(end to quit)> ')
- if line == 'end':
- break
- #content.append(line + '\n')
- content.append(line)
- return content
-
- # print('请输入文件内容,在单独的一行输入end结束')
- # f = open(fname,'w')
- # while if q != end :
- # content = f.writelines([q = input('(end to quit)>: ')])
-
- def wfile(fname,content):
- '用于将内容content,写入文件fname'
- with open(fname, 'w') as fobj:
- fobj.writelines(content)
- # fobj = open(fname,'w')
- # fobj.writelines(content)
- # fobj.close()
-
- if __name__ == '__main__':
- fname = get_fname()
- content = get_content()
- print(content)
- content = ['%s\n' % line for line in content]
- wfile(fname, content)
包括字符串 列表 元组
- #list用于将某些数据转成列表
- >>> list(range(10))
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- >>> list('abc')
- ['a', 'b', 'c']
- #tuple用于将某些数据转成元组
- >>> tuple('abc')
- ('a', 'b', 'c')
- >>> tuple(range(10))
- (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
-
- >>> len('asdasd')
- 6
-
- #reversed 用于翻转
- >>> alist = [ 10 , 8 , 25 , 1, 100]
- >>> list(reversed(alist))
- [100, 1, 25, 8, 10]
- >>> for i in reversed(alist):
- ... print(i)
-
- #sorted用于排序,默认升序
- >>> sorted(alist)
- [1, 8, 10, 25, 100]
-
- #enumerate 用于获取下标和值
- >>> user = ['tom','yyf','chao']
- >>> list(enumerate(user))
- [(0, 'tom'), (1, 'yyf'), (2, 'chao')]
- >>> for i in enumerate(user):
- ... print(i)
- ...
- (0, 'tom')
- (1, 'yyf')
- (2, 'chao')
- >>> for i, name in enumerate(user):
- ... print(i,name)
- ...
- 0 tom
- 1 yyf
- 2 chao
- >>> print(i) ------一次次的赋值给变量i
- 2
- 格式化操作符:
- >>> '%s is %s years old' % ('tom',20)
- 'tom is 20 years old'
- >>> '%s is %d years old' % ('tom',20)
- 'tom is 20 years old'
- >>> '%s is %f years old' % ('tom',20.5)
- 'tom is 20.500000 years old'
- >>> '%s is %d years old' % ('tom',20.5)
- 'tom is 20 years old'
- >>> '%d is %d years old' % ('tom',20) -----tom转不成数字
- Traceback (most recent call last):
- File "
" , line 1, in <module> - TypeError: %d format: a number is required, not str
- >>> '%s is %.1f years old' % ('tom',20.5) ------%.1f 指保留1位小数
- 'tom is 20.5 years old'
-
- >>> '%10s%8s' % ('tom',20.5) -----正数向右对齐
- ' tom 20.5'
- >>> '%10s%8s' % ('tom','age')
- ' tom age'
- >>> '%-10s%-8s' % ('tom','age') ------负数向左对齐
- 'tom age '
- >>> '%-10s%-8s' % ('tom',20)
- 'tom 20
- #不常用 了解
- >>> '%c' % 97 ----将数字根据ascii码转成对应的字符
- 'a'
- >>> '%c' % 65
- 'A'
- >>> '%#o' % 10----8进制
- '0o12'
- >>> '%#x' % 10------16进制
- '0xa'
- >>> '%e' % 10000-----科学计算法----
- '1.000000e+04' ------e+04 10的4次方
- >>> '%8d' % 10
- ' 10'
- >>> '%08d' % 10 -----宽度8 不够的补0
- '00000010'
- format函数
- >>> '{} is {} years old'.format('tom',20)
- 'tom is 20 years old'
- >>> '{1} is {0} years old'.format('tom',20)
- '20 is tom years old'
- """创建用户
- 这是一个用于创建用户的脚本,用到有4个函数
- """
-
-
- import sys
- import randpass
- import subprocess
-
-
- def add_user(user, passwd, fname):
- #如果用户已存在,则返回,不要继续执行函数
- result = subprocess.run(
- 'id %s &> /dev/null' % user, shell=True
- )
- if result.returncode == 0 :
- print('用户已存在')
- #return默认返回None,类似于break,函数遇到return也会提前结束
- return
-
- # 创建用户, 设置密码
- subprocess.run(
- 'useradd %s' % user, shell=True
- )
- subprocess.run(
- 'echo %s | passwd --stdin %s' % (passwd,user),shell=True
- )
-
- #写入文件
- info = """用户信息:
- 用户名: %s
- 密码: %s
- """ % (user,passwd)
- with open(fname,'a') as fobj:
- fobj.write(info)
-
- if __name__ == '__main__':
- user = sys.argv[1]
- passwd = randpass.mk_pass2()
- fname = sys.argv[2]
- add_user(user,passwd,fname)
- >>> win_path = 'c:\temp'
- >>> print(win_path)
- c: emp
- >>> wpath = r'c:\temp'
- >>> print(wpath)
- c:\temp
- >>> win_path = 'c:\\temp'
- >>> print(win_path)
- c:\temp
- >>> a = r'c:\tem\tec'
- >>> print(a)
- c:\tem\tec
- >>> '+%s+' % ('*' * 50)
- '+**************************************************+'
- >>> 'hello world'.center(48)
- ' hello world '
- >>> '+hello world+'.center(50)
- ' +hello world+ '
- >>> '+%19s%-18s+' % ('hello','world')
- '+ helloworld +'
-
- >>> 'hello world'.center(48,'*')
- '******************hello world*******************'
- >>>
- >>> 'hello world'.ljust(48,'a')
- 'hello worldaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
- >>> 'hello world'.ljust(48,'#')
- 'hello world#####################################'
- >>> 'hello world'.rjust(48,'%')
- '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%hello world'
- >>>
- >>> '+' + 'hello world'.center(48,'*') + '+'
- '+******************hello world*******************+'
- >>> '+%s+' % 'hello'.center(50)
- '+ hello +'
-
- >>> 'hello'.upper() # 转大写
- 'HELLO'
- >>> 'HELLO'.lower() # 转小写
- 'hello'
- >>> 'hello'.startswith('h') # 字符串以h开头吗?
- True
- >>> 'hello'.startswith('he') # 字符串以he开头吗?
- True
- >>> 'hello'.endswith('ab') # 字符串以ab结尾吗?
- False
- >>> 'hao123'.islower() # 字母都是小写的吗?
- True
- >>> 'hao123'.isupper() # 字母都是大写的吗?
- False
- >>> '1234'.isdigit() # 所有的字符都是数字吗?
- True
-
- # 判断是不是所有的字符都是数字字符
- >>> s = '1234@11'
- >>> for ch in s:
- ... if ch not in '0123456789':
- ... print(False)
- ... break
- ... else:
- ... print(True)
- ...
- False
下一篇文将会教python的常用数据类型:列表,元组,字典,集合,想学习的同学一起学习。