python之常用模塊4


pyinotify模塊

pip3 install pyinotify

pyinotify提供的事件:

事件標志 事件含義
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

在具體實現時,時間僅僅是一個標志位,因此,我們可以使用“與”操作來合並多個時間,下面來看一個實例

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提供了更好的接口,並具有更好的易讀性

yagmail是開原項目,因此,在使用前需要安裝

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模塊

一、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 的配置內容。




二、ConfigParser 初始化對象
使用ConfigParser 首選需要初始化實例,並讀取配置文件:
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
三、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模塊

1、getcwd()

獲取當前工作路徑

import os
print(os.getcwd())

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

D:\pyproject\day21模塊

2、chdir()   改變當前工作路徑

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

3、返回上級目錄用..

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

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

D:\pyproject\day21模塊

D:\pyproject

4、makedirs(可以建遞歸的目錄)

新建文件夾

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

5、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

6、rmdir 只能刪除單級目錄為空的文件夾

import os
os.rmdir("gouguoqi")

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

7、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']

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

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

9、rename  修改文件夾名字或者是文件名字都可以

import os

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

10、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 轉換為字符串時間

 

11、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

12、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

 

13、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

14、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

15、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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM