【python自动化运维】python基础语法总结

一、输出语句

print("内容")

1.1、引号的使用

print("hello world!!!!")
print("python自动化运维")

# 引号的使用, 单引号,双引号,三引号
print('shell运维')
print("python运维")
print("""Linux
Windows
Unix
Macos""")
print("我的姓名是'Martin'")

1.2、输出变量的值

# 输出变量的值
user = "Martin"
password = "redhat"
print(user)
# 你好, Martin
print("你好", user)
print("用户名:", user, "密码:", password)

1.3、占位符的使用

'''
占位符
%s      字符串占位
%d      整数
%f      浮点数
%%      %本身
'''

user = "Martin"
password = "redhat"

print("姓名: '%s'" % user)
print("姓名: '%s', 密码: '%s'" % (user, password))

print("数字: %d" % 100)
print("数字: %d" % 3.56)

print("小数: %f" % 3.14)
print("小数: %f" % 20)
print("小数: %.3f" % 3.1415926)


# 50%
number = 50
print("百分比: %d%%" % number)

二、变量的定义、调用

2.1、变量的定义、调用

变量的定义

变量名称 = 值

变量名称规范:

  • 只能包含字母、数字、下划线
  • 只能以下划线、字母开头
  • 不能与python关键字冲突
  • 见名知义
user = "Martin"
print(user)
hostname, ip_address = "node01.linux.com", "10.1.1.1"
print("主机名: %s, 服务器地址: %s" % (hostname, ip_address))

2.2、交互式定义变量

变量名称 = input("提示信息")
username = input("用户名: ")
print("用户名: %s" % username)

三、数字管理操作

3.1、数据类型

数字、字符串、列表、元组、字典、集合、Bytes

3.2、数字的定义

整数、浮点数、复数 10+20i

data_01 = 10
data_02 = 3.17
data_03 = 10 + 20j

print(type(data_01), type(data_02), type(data_03))

3.3、数字操作符

3.3.1) 数学运算符

+, -, *, /, %, //(地板除), **(次幂)

print(10 + 4)
print(10 - 4)
print(10 * 4)
print(10 / 4)
print(10 // 4)
print(10 % 4)
print(2 ** 3)
data_01 = 10
data_01 = data_01 + 1
print(data_01)

data_01 += 1
print(data_01)

3.3.2) 比较运算符

, <, ==, !=, >=, <=

>>> 10 > 8
True
>>> 10 < 8
False
>>> 10 == 10
True
>>> 10 != 20
True

3.3.3) 逻辑运算符

and, or, not

>>> 10 > 8 and 9 > 7
True

>>> 10 < 20 or 8 > 34
True

>>> 10 < 20
True

>>> not 10 < 20
False

四、字符串管理操作

4.1、定义

  • 被定义在一对引号中的数据
  • 不可变数据类型
data_01 = "192.168.1.1"
data_02 = 'node01.linux.com'
data_03 = "/etc/fstab"
data_04 = ""

print(type(data_01), type(data_02), type(data_03), type(data_04))

原始字符串

  • 避免特殊字符被转义
  • 应用于正则表达式、windows文件路径
file_name = r"D:\testdir\new_logo.jpg"
print(file_name)

4.2、字符串常规操作

  • 获取字符串的长度
data_01 = "/etc/fstab"
print(len(data_01))
  • 拼接操作
print("Python" + "Shell" + "Golang")
  • 重复
print("Python" * 4)
  • 判断成员关系
>>> "h" in "python"
True
>>> "tho" in "python"
True

>>> "to" in "python"
False
>>>
>>> "h" not in "python"
False
  • 索引

从左向右,下标从0开始
从右向左, 下标从-1开始

>>> data_01 = "/etc/fstab"
>>>
>>> data_01[2]
't'
>>> data_01[0]
'/'
>>> data_01[-4]
's'
>>> data_01[-2] = "K"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
  • 切片
  • 字符串[起始下标:终止下标]
  • 从起始下标开始,到终止下标的前一个字符结束
>>> data_01 = "/etc/fstab"

>>> data_01[1:5]
'etc/'
>>> data_01[0:3]
'/et'
>>> data_01[5:]
'fstab'
>>> data_01[-3:]
'tab'
>>> data_01[0:6:2]
'/t/'
>>> data_01[::-1]
'batsf/cte/'
>>> data_01 = "python"
>>>
>>> data_01 = data_01[0:2] + "K" + data_01[-3:]
>>>
>>> data_01
'pyKhon'

4.3、字符串对象操作方法

4.3.1、查看对象的操作方法

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

4.3.2、转换大小写

data_01 = "pYtHon"

print(data_01.capitalize())
print(data_01.upper())
print(data_01.lower())

4.3.3、判断字符串开头、结尾

print("abc".startswith("a"))
print("abc".endswith("bc"))

dir_name = input("目录名称: ")

if dir_name.endswith("/"):
    print(dir_name)
else:
    dir_name = dir_name + "/"
    print(dir_name)

4.3.4.、去除字符串左、右两侧指定的字符

>>> data_01 = "    node01.linux.com     "
>>>
>>> data_01.strip()
'node01.linux.com'
>>>
>>> data_01.lstrip()
'node01.linux.com     '
>>>
>>> data_01.rstrip()
'    node01.linux.com'

>>> data_02 = "AALinuxAA"
>>> data_02.strip("AA")
'Linux'

choice = input("确认/取消(y/n)? ").strip().lower()

if choice == "y":
    print("执行操作")
else:
    print("取消操作")

4.3.5、分割字符串

>>> data_01 = "linux      unix macos  windows"
>>>
>>> data_01.split()
['linux', 'unix', 'macos', 'windows']
>>>
>>> data_01.split()[-2]
'macos'

>>> ip_address = "192.168.1.1"
>>>
>>> ip_address.split(".")
['192', '168', '1', '1']
>>>
>>> ip_address.split(".")[1]
'168'
>>>
>>> type(ip_address.split(".")[1])
<class 'str'>

4.3.6、字符串替换

>>> data_01 = "hello python"
>>>
>>> data_01.replace("o", "K")
'hellK pythKn'
>>>
>>> data_01.replace("o", "K", 1)
'hellK python'

4.3.7、判断字符串组成结构

>>> "68768".isdigit()
True
>>> "abc".islower()
True
>>> "Abc".isupper()
False
>>> "abc234ds".isalnum()
True

4.4、遍历字符串

data_01 = "Linux"

for i in data_01:
    print("---> %s" % i)

五、列表管理操作

5.1、列表定义

被定义一对方括号[ ]中的数据, 不同的数据使用逗号隔开
[ 数据1, 数据2, 数据3 ]
可变数据

data_01 = []
data_02 = [ "nginx", "haproxy", "lvs" ]
print(type(data_01), type(data_02))

data_03 = [ 10, 20, 100, 2352, 2534 ]
print(type(data_03))

data_04 = [ ["MySQL", "Oracle"], ["redis", "mongoDB"], ["memcache", "etcd"] ]
print(type(data_04))

5.1.1、列表解析

data_05 = [ i for i in range(1, 11) ]
print(data_05)

data_06 = [ i ** 2 for i in range(1,11) ]
print(data_06)

data_07 = [ i ** 2 for i in range(1, 11) if i % 2 ]
print(data_07)

data_08 = [ "172.16.10.%s" % i for i in range(1,11) ]
print(data_08)

5.2、列表常规操作符

5.2.1、判断成员关系 in, not in

>>> data_01 = [ "nginx", "httpd", "tomcat" ]
>>> "httpd" in data_01
True
>>> "httpd" not in data_01
False

>>> data_02 = [ ["MySQL", "Oracle"], ["Redis", "etcd"] ]
>>>
>>> "Redis" in data_02
False
>>>
>>> ["MySQL", "Oracle"] in data_02
True

5.2.2、获取列表中元素的个数

>>> len(data_01)
3
>>> len(data_02)
2

5.2.3、索引操作

>>> data_01 = [ "nginx", "httpd", "tomcat" ]
>>> data_01[-1]
'tomcat'
>>> data_01[0]
'nginx'

>>> data_02 = [ ["MySQL", "Oracle"], ["Redis", "etcd"] ]
>>> data_02[1]
['Redis', 'etcd']
>>> data_02[1][0]
'Redis'

>>> data_01[1] = "IIS"
>>> data_01
['nginx', 'IIS', 'tomcat']

>>> data_02[0][-1] = "PostgreSQL"
>>> data_02
[['MySQL', 'PostgreSQL'], ['Redis', 'etcd']]
>>>

5.3、列表对象操作方法

5.3.1、追加数据

>>> data_01 = [ "nginx", "tomcat" ]
>>> data_01.append("IIS")
>>>
>>> data_01
['nginx', 'tomcat', 'IIS']
>>>
>>> data_01.append("httpd")

>>> data_01
['nginx', 'tomcat', 'IIS', 'httpd']

5.3.2、插入数据

data_01 = [ "nginx", "tomcat" ]
data_01.insert(1, "IIS")
print(data_01)

5.3.3、删除数据 pop( )

删除最后一个数据
返回删除的数据

data_01 = [ "nginx", "tomcat", "IIS", "httpd" ]
AA = data_01.pop()
print(data_01)
print("删除数据: %s" % AA)

BB = data_01.pop()
print(data_01)
print("删除数据: %s" % BB)

5.3.4、删除数据 remove( )

data_01 = [ "nginx", "tomcat", "IIS", "httpd" ]

data_01.remove("tomcat")

print(data_01)

5.4、遍历列表

data_01 = [ "nginx", "httpd", "tomcat", "redis" ]

for i in data_01:
    print("yum install -y %s" % i)

data_02 = [ ["MySQL", "Oralce"], ["Redis", "Etcd"], ["docker", "podman"] ]

for i, j in data_02:
    print("第一个值: %s, 第二个值: %s" % (i, j))

六、元组管理操作

6.1、元组的定义

被定义在一对圆括号( )的数据, 不同的元素使用逗号隔开
不可变的数据

data_01 = ()
data_02 = ( "nginx", "httpd", "IIS" )
data_03 = ( ("MySQL", "Oracle"), ("redis", "etcd"), ("docker", "podman") )
data_04 = ( ["linux", "unix"], ["macos", "windows"] )

print(type(data_01), type(data_02), type(data_03), type(data_04))

6.1.1、定义单元素的元组

data_05 = ( "node01.linux.com", )
print(type(data_05))

6.2、元组的常规操作

len()、in、not in、索引

data_02 = ( "nginx", "httpd", "IIS" )
print(data_02[-1])
print(data_02[0])

data_04 = ( ["linux", "unix"], ["macos", "windows"] )
data_04[0][-1] = "AIX"
print(data_04)

6.3、遍历元组

data_01 = ( "nginx", "httpd", "tomcat", "IIS" )

for i in data_01:
    print("---> %s" % i)

data_02 = ( ("10.1.1.1", "node01"), ("10.1.1.2", "node02"), ("10.1.1.3", "node03") )

for i, j in data_02:
    print("IP地址: %s, 主机名: %s" % (i, j))

data_02 = ( ["10.1.1.1", "node01"], ["10.1.1.2", "node02"], ["10.1.1.3", "node03"] )

for i, j in data_02:
    print("IP地址: %s, 主机名: %s" % (i, j))

七、字典管理操作

7.1、字典的定义

被定义在一对大括号{ }中的数据
以key-value对进行存储,不同的键值对使用逗号隔开
键要唯一,值可以为任意类型的数据
可变的数据

data_01 = {}
data_02 = { "martin":"redhat", "robin":"123" }
print(type(data_01), type(data_02))

data_03 = {
    "10.1.1.1": [ "sshd", "httpd", "php"],
    "10.1.1.2": [ "sshd", "nginx", "php-fpm"]
}
print(type(data_03))

data_04 = {
    "10.1.1.1": {
        "ssh_user": "root",
        "ssh_pwd": "redhat",
        "ssh_port": "22"
    },
    "10.1.1.2": {
        "ssh_user": "admin",
        "ssh_pwd": "123",
        "ssh_port": "44444"
    }
}
print(type(data_04))

7.2、字典数据的管理操作

7.2.1、获取数据

>>> data_01 = { "martin":"redhat", "robin":"123", "lz":"777" }
>>>
>>> data_01["robin"]
'123'
>>> data_01["martin"]
'redhat'

>>> data_01.get("martin")
'redhat'
>>> data_01.get("lz")
'777'

>>> data_01["king"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'king'

>>> data_01.get("king")

7.2.2、添加数据

>>> data_01 = { "martin":"redhat", "robin":"123", "lz":"777" }
>>>
>>> data_01["king"] = "WWW.1.com"
>>>
>>> data_01
{'martin': 'redhat', 'robin': '123', 'lz': '777', 'king': 'WWW.1.com'}

7.2.3、修改数据

>>> data_01
{'martin': 'redhat', 'robin': '123', 'lz': '777', 'king': 'WWW.1.com'}

>>> data_01["lz"] = "9999"
>>>
>>> data_01
{'martin': 'redhat', 'robin': '123', 'lz': '9999', 'king': 'WWW.1.com'}

7.3、字典对象的操作方法

7.3.1、以列表的形式返回字典中所有的键

>>> data_01
{'robin': '123', 'lz': '9999', 'king': 'WWW.1.com'}
>>>
>>> data_01.keys()
dict_keys(['robin', 'lz', 'king'])

7.3.2、以列表的形式返回字典中所有的值

>>> data_01.values()
dict_values(['123', '9999', 'WWW.1.com'])

7.3.3、以列表的形式返回包含键值对的多个元组

>>> data_01
{'robin': '123', 'lz': '9999', 'king': 'WWW.1.com'}
>>>
>>> data_01.items()
dict_items([('robin', '123'), ('lz', '9999'), ('king', 'WWW.1.com')])

7.4、遍历字典

data_02 = { "martin":"redhat", "robin":"123", "lz":"9999" }

for i in data_02:                           
    print("----> %s" % i)

data_02 = { "martin":"redhat", "robin":"123", "lz":"9999" }

for i in data_02:
    print("用户名: %s, 密码: %s" % (i, data_02.get(i)))

data_02 = { "martin":"redhat", "robin":"123", "lz":"9999" }

for k, v in data_02.items():
    print("用户名: %s, 密码: %s" % (k, v))

八、集合管理操作

8.1、作用

去重
可变集合
set( )
不可变集合
fronzenset( )

8.1.1、集合定义

data_01 = "hello"
set_A = set(data_01)
print(type(set_A))
print(set_A)

data_02 = [ "nginx", "IIS", "Tomcat","IIS", "Tomcat","IIS", "Tomcat" ]
set_B = frozenset(data_02)
print(type(set_B))
print(set_B)

8.1.2、遍历集合

for i in set_A:
    print("---> %s" % i)

九、Bytes管理操作

9.1、定义Bytes格式的数据

data_01 = b"abc"
print(type(data_01))

data_02 = b"789"
print(type(data_02))

9.2、字符串 -----> Bytes

9.2.1、encode( ) 编码

data_01 = "python自动化运维"

new_data_01 = data_01.encode(encoding="utf-8")
print(type(new_data_01))
print(new_data_01)

9.2.2、bytes( )

data_02 = "python django框架"

new_data_02 = bytes(data_02, encoding="utf-8")
print(type(new_data_02))
print(new_data_02)

9.3、Bytes -------> 字符串

9.3.1、decode( ) 解码

data_03 = b"\xe6\xa1\x86\xe6\x9e\xb6"
print(type(data_03))

new_data_03 = data_03.decode(encoding="utf-8")
print(type(new_data_03))
print(new_data_03)

9.3.2、str( )

data_04 = b"\xe6\xa1\x86\xe6\x9e\xb6"
print(type(data_04))

new_data_04 = str(data_04, encoding="utf-8")
print(type(new_data_04))
print(new_data_04)

十、逻辑控制语句

10.1、逻辑控制语句

条件判断
if
循环
for、while

10.2、条件判断 if

1、语法
if 条件:
条件为真的操作
条件为真的操作
else:
条件为假的操作
条件为假的操作

10.3、for循环

10.3.1、语法

for 变量 in 取值列表:
执行的操作
执行的操作

10.4、while循环

10.4.1、常规语法

while 条件:
执行的操作
执行的操作

10.4.、语法2

while True:
执行的操作
执行的操作

10.5、终止循环的语句

10.5.1、break

终止整个循环

for i in range(1,6):
    if i == 3:
        break
    else:
        print("ping -c 1 172.16.%s.1" % i)

10.5.2、continue

终止本次循环

for i in range(1,6):
    if i == 3:
        continue
    else:
        print("ping -c 1 172.16.%s.1" % i)

十一、函数语法应用

def 函数名称(参数):
    代码体

if __name__ == "__main__":
    函数名称()

十二、面向对象语法

12.1、创建类

class 类名():
属性

方法

类名规范:
只能包含数字、字母、下划线
以下划线、字母开头
见名知义
不能与python关键字冲突
所有单词首字母大写

12.2、创建对象

变量名称 = 类名()

创建类

class Test1():
    name = "martin"
    age = 37

    def f1(self):
        print("这是类Test1中的f1方法")


if __name__ == '__main__':
    # 基于Test1类创建对象
    p1 = Test1()
    print(p1.name, p1.age)
    p1.f1()

    p2 = Test1()
    print(p2.name, p2.age)
    p2.f1()

12.3、类中调用数据 self

类中相互调用数据

class Test1():
    name = "martin"

    def f1(self):
        print("f1方法")

    def f2(self):
        print("用户名: ", self.name)
        self.f1()

if __name__ == '__main__':
    p1 = Test1()
    p1.f2()

12.4、构造方法

名称是固定
init
创建对象时,自动执行构造方法中的操作

适用场景
为类中的属性动态赋值

class Test1():

    def __init__(self, ip, username):
        self.ip = ip
        self.username = username

    def sshTest(self):
        print("ssh %s@%s" % (self.username, self.ip))

if __name__ == '__main__':
    p1 = Test1(ip="192.168.1.1", username="martin")
    p1.sshTest()
    
    p2 = Test1(ip="10.1.1.1", username="root")
    p2.sshTest()

12.5、类的继承

子类会自动继承父类中所有的数据

class Test1():
    name = "martin"
    age = 37

    def f1(self):
        print("这是Test1中的f1方法")


class Test2(Test1):
    pass

if __name__ == '__main__':
    p1 = Test2()
    print(p1.name, p1.age)
    p1.f1()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值