python之經常使用模塊4

pyinotify模塊

pip3 install pyinotify

pyinotify提供的事件:python

事件標誌 事件含義
IN_ACCESS 被監控項目或者被監控目錄中的文件被訪問,好比一個文件被讀取
IN_MODIFY 被監控項目或者被監控目錄中的文件被修改
IN_ATTRIB 被監控項目或者被監控目錄中的文件的元數據被修改
IN_CLOSE_WRITE 一個打開切等待寫入的文件或者目錄被關閉
IN_CLOSE_NOWRITE 一個以只讀方式打開的文件或者目錄被關閉
IN_OPEN 文件或者目錄被打開
IN_MOVED_FROM 被監控項目或者目錄中的文件被移除監控區域
IN_MOVED_TO 文件或目錄被移入監控區域
IN_CREATE 在所監控的目錄中建立子目錄或文件
IN_DELETE 在所監控的目錄中刪除目錄或文件
IN_CLOSE* 文件被關閉,等同於IN_CLOSE_WRITE*
IN_MOVE 文件被移動,等同於IN_CLOSE_NOWRITE

在具體實現時,時間僅僅是一個標誌位,所以,咱們可使用「與」操做來合併多個時間,下面來看一個實例mysql

import pyinotify
#建立一個監控實例
wm = pyinotify.WatchManager()
#定義要監控的內容   
mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE   #這裏pyinotify.ALL_EVENTS表示監控全部事件
#在實例中添加動做
wm.add_watch('/tmp', mask)
#加載監控實例對象
notifier = pyinotify.Notifier(wm)
#循環處理時間
notifier.loop()

yagmail模塊

python標準庫中發送電子郵件的模塊比較複雜,所以,有許多開原的庫提供了更加易用的接口來發送電子郵件,其中yagmail是一個使用比較普遍的開原項目,yagmail底層依然使用了smtplib和email模塊,可是yagmail提供了更好的接口,並具備更好的易讀性linux

yagmail是開原項目,所以,在使用前須要安裝sql

pip install yagmail

 

#鏈接郵箱服務器
yag = yagmail.SMTP(user='xxx@163.com', password='xxxx', host='smtp.163.com')
#發送郵件
yag.send(to='xxx@126.com', cc='xxx@163.com',subject='這是測試郵件', contents='這是測試郵件的內容')
#斷開鏈接
yag.close()

 

 

pymysql模塊

#pymysql操做數據庫
import pymysql
# 打開數據庫鏈接
db = pymysql.connect(host="192.168.254.24", user="root",
                     password="root", db="mysql", port=3306)

# 使用cursor()方法獲取操做遊標
cur = db.cursor()

# 1.查詢操做
# 編寫sql 查詢語句  user 對應個人表名
sql = "select host,user,password from user"
try:
    cur.execute(sql)  # 執行sql語句
    results = cur.fetchall()  # 獲取查詢的全部記錄
    for i in results:#遍歷結果
        print(i)
except Exception as e:
    raise e
finally:
    db.close()  # 關閉鏈接
View Code

configparse模塊

1、ConfigParser簡介
ConfigParser 是用來讀取配置文件的包。配置文件的格式以下:中括號「[ ]」內包含的爲section。section 下面爲相似於key-value 的配置內容。

[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69

[concurrent]
thread = 10
processor = 20
括號「[ ]」內包含的爲section。緊接着section 爲相似於key-value 的options 的配置內容。




2、ConfigParser 初始化對象
使用ConfigParser 首選須要初始化實例,並讀取配置文件:
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
3、ConfigParser 經常使用方法

1、獲取所用的section節點


# 獲取所用的section節點
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
print(config.sections())
#運行結果
# ['db', 'concurrent']

2、獲取指定section 的options。即將配置文件某個section 內key 讀取到列表中:


import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.options("db")
print(r)
#運行結果
# ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']

3、獲取指點section下指點option的值


import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.get("db", "db_host")
# r1 = config.getint("db", "k1") #將獲取到值轉換爲int型
# r2 = config.getboolean("db", "k2" ) #將獲取到值轉換爲bool型
# r3 = config.getfloat("db", "k3" ) #將獲取到值轉換爲浮點型
print(r)
#運行結果
# 127.0.0.1

4、獲取指點section的所用配置信息


import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
r = config.items("db")
print(r)
#運行結果
#[('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')]


5、修改某個option的值,若是不存在則會出建立


# 修改某個option的值,若是不存在該option 則會建立
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
config.set("db", "db_port", "69")  #修改db_port的值爲69
config.write(open("ini", "w"))


 運行結果
6、檢查section或option是否存在,bool值

import configparser
config = configparser.ConfigParser()
config.has_section("section") #是否存在該section
config.has_option("section", "option")  #是否存在該option
7、添加section 和 option


import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
if not config.has_section("default"):  # 檢查是否存在section
    config.add_section("default")
if not config.has_option("default", "db_host"):  # 檢查是否存在該option
    config.set("default", "db_host", "1.1.1.1")
config.write(open("ini", "w"))


 運行結果
8、刪除section 和 option

import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
config.remove_section("default") #整個section下的全部內容都將刪除
config.write(open("ini", "w"))
 運行結果
9、寫入文件

如下的幾行代碼只是將文件內容讀取到內存中,進過一系列操做以後必須寫回文件,才能生效。

import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
寫回文件的方式以下:(使用configparser的write方法)

config.write(open("ini", "w"))
View Code

 

pexpect模塊

import pexpect
host = '192.168.254.24'
password = 'root'
username = 'root'
child = pexpect.spawn('ssh root@192.168.254.24')
child.expect('password:')
child.sendline(password)
child.expect('#')
child.sendline('mysql -uroot -proot')
child.expect('none')
child.sendline('show variables like "%log%";')
child.sendline('exit')
child.sendline('exit')
child.interact()
child.close()
利用pexpect查看其餘機器的數據庫

 

import pexpect
ssh = pexpect.spawn('ssh 192.168.254.12',timeout=10)
i = ssh.expect(['password:','continue connecting'],timeout=10)
print(i)
if i == 0:
    ssh.sendline('root')
elif i == 1:
    ssh.sendline('yes\n')
    ssh.expect('password:')
    ssh.sendline('root\n')
index = ssh.expect(['#',pexpect.EOF,pexpect.TIMEOUT],timeout=15)
if index == 0:
    ssh.sendline('ip a')
    ssh.sendline('exit')
    ssh.interact()
    ssh.close()
elif index == 1:
    print('logging process exit')
elif index == 2:
    print('logging in time out')
ssh登陸主機

 

paramiko模塊

#經過paramiko模塊鏈接主機運行bash命令

import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname,port=port,username=username,password=password)
stdin, stdout, stderr = ssh.exec_command("ls -ltr")
print(stdout.read().decode('utf-8'))



#經過paramiko模塊鏈接主機上傳
import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(r'C:\Users\fengzi\Desktop\Linux.xmind', '/root/aaa.xmind')
sftp.close()



#經過paramiko模塊鏈接主機下載
import paramiko
hostname = '192.168.254.24'
port = 22
username = 'root'
password = 'root'
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get('/root/test3.yml', r'C:\Users\fengzi\Desktop\test3.yml')
sftp.close()
View Code

 

socket模塊

#linux服務器(半雙工)

import socket
import subprocess
import threading
server = socket.socket()
server.bind(('', 8888))
server.listen(5)
print('等待電話.....')
conn, addr = server.accept()
print('電話來了......')
while True:
    data = conn.recv(10240)
    cmd = subprocess.Popen(data.decode('utf-8'),
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    stdout = cmd.stdout.read()
    stderr = cmd.stdout.read()
    conn.send(stdout + stderr)

#客戶端
import socket
import threading
client = socket.socket()
client.connect(('192.168.254.24', 8888))
while True:
    info = input('===>:')
    if not info:continue
    client.send(info.encode('utf-8'))
    data = client.recv(10240)
    print(data.decode('utf-8'))
半雙工
#全雙工電話
#服務器端
import socket
import subprocess
import threading
server = socket.socket()
server.bind(('', 8888))
server.listen(5)
print('等待電話.....')
conn, addr = server.accept()
print('電話來了......')
def recv():
    while True:
        data = conn.recv(10240)
        print(data.decode('utf-8'))
def send():
    while True:
        data = input('===>:')
        conn.send(data.encode('utf-8'))
t1 = threading.Thread(target=recv)
t2 = threading.Thread(target=send)
t1.start()
t2.start()



#客戶端
import socket
import threading
client = socket.socket()
client.connect(('localhost', 8888))
def send():
    while True:
        info = input('===>:')
        client.send(info.encode('utf-8'))
def recv():
    while True:
        data = client.recv(1024)
        print(data.decode('utf-8'))

t1 = threading.Thread(target=send)
t2 = threading.Thread(target=recv)
t1.start()
t2.start()
全雙工
import socket
socket.setdefaulttimeout(1)

host_list = ['192.168.4.145:5555','192.168.4.146:555','192.168.4.147:5555','192.168.31.199:445']
for info in host_list:
    server = socket.socket()
    ip = re.compile('(.*?):(.*)').search(info).group(1)
    port = re.compile('(.*?):(.*)').search(info).group(2)
    res = server.connect_ex((ip, int(port)))
    if res == 0:
        print('%s--%s端口正常' % (ip, port))
    else:
        print('%s--%s端口異常' % (ip, port))
利用socket監控端口

 

 

re模塊

\w 匹配字母數字
\W 匹配非字母數字
\s 匹配任意空白字符,等價於 [\t\n\r\f].
\S 匹配任意非空字符
\d 匹配任意數字,等價於 [0-9].
\D 匹配任意非數字
\A 匹配字符串開始
\Z 匹配字符串結束,若是是存在換行,只匹配到換行前的結束字符串。c
\z 匹配字符串結束
\G 匹配最後匹配完成的位置。
\b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, 'er\b' 能夠匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\B 匹配非單詞邊界。'er\B' 能匹配 "verb" 中的 'er',但不能匹配 "never" 中的 'er'。
\n, \t, 等. 匹配一個換行符。匹配一個製表符。等
\1...\9 匹配第n個分組的子表達式。
\10 匹配第n個分組的子表達式,若是它經匹配。不然指的是八進制字符碼的表達式。

 

 

 

os模塊

一、getcwd()shell

獲取當前工做路徑數據庫

import os
print(os.getcwd())

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊

二、chdir()   改變當前工做路徑bash

import os
print(os.getcwd())
os.chdir("test1")
print(os.getcwd())

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊

D:\pyproject\day21模塊\test1

三、返回上級目錄用..服務器

import os
print(os.getcwd())
os.chdir("..")
print(os.getcwd())

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊

D:\pyproject

四、makedirs(能夠建遞歸的目錄)less

新建文件夾dom

import os
os.makedirs("gouguoqi/gouguoqi1")
os.chdir("gouguoqi/gouguoqi1")
print(os.getcwd())

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊\gouguoqi\gouguoqi

五、mkdir   新建目錄,只能建一層

import os
os.mkdir("gouguoqi")
os.chdir("gouguoqi")
print(os.getcwd())

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊\gouguoqi

六、rmdir 只能刪除單級目錄爲空的文件夾

import os
os.rmdir("gouguoqi")

OSError: [WinError 145] 目錄不是空的。: 'gouguoqi'

七、listdir    列出指定文件夾下面全部的文件夾和文件包括隱藏文件,以列表方式打印出來

import os
print(os.listdir("D:\pyproject\day21模塊"))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

['module-lesson.py', '文件修改功能.py', 'day21_lesson', 'time模塊.py', 'random隨機模塊.py', 'basedir.py', 'os模塊.py', 'test1', 'gouguoqi', '查詢功能.py', '三級菜單.py', 'test.py', 'sed.py', 'haproxy.cfg']

八、remove   刪除指定的一個文件

import os
os.remove("gouguoqi/test.py")

九、rename  修改文件夾名字或者是文件名字均可以

import os

os.rename("gouguoqi","gouguoqinew")

十、stat   查看一個文件的詳細信息

import os
print(os.stat("gouguoqinew/testnew"))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

os.stat_result(st_mode=33206, st_ino=15085150720, st_dev=75373296, st_nlink=1, st_uid=0, st_gid=0, st_size=28, st_atime=1528473600, st_mtime=1528552906, st_ctime=1528552713)

 

st_size=28    文件大小,單位是字節

st_atime=1528473600  用戶上一次的訪問時間

st_mtime=1528552906  用戶上一次修改的時間(經常使用)

st_ctime=1528552713   用戶的建立文件的時間

這個時間是時間戳,想要轉換成咱們能看懂的那種格式,還得轉換下,好比用戶建立文件時間是1528552713 轉換爲字符串時間

 

十一、system  運行shell命令,直接顯示結果

[root@localhost python]# cat os.system.py

#!/usr/bin/env  python

# _*_ coding:utf8 _*_

import os

os.system("cd /home && ls")

[root@localhost python]# python os.system.py

python                                src

十二、os.path.exists 判斷路徑是否存在,存在爲True,不存在爲False

import os
print(os.path.exists("D:\pyproject\day21模塊\gouguoqinew"))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

True

 

1三、os.path.isfile 判斷一個文件是否存在,存在爲True,不然爲False

import os
print(os.path.isfile(r"D:\pyproject\day21模塊\gouguoqinew\test.py"))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

True

1四、os.path.isdir  判斷一個目錄是否存在,存在爲True,不然爲False

import os
print(os.path.isdir(r"D:\pyproject\day21模塊\gouguoqinew"))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

True

1五、os.path.join  路徑拼接(重要經常使用)

import os
a="D:\pyproject"
b="day21模塊\gouguoqinew"
print(os.path.join(a,b))

C:\python35\python3.exe D:/pyproject/day21模塊/os模塊.py

D:\pyproject\day21模塊\gouguoqinew
相關文章
相關標籤/搜索