1. 程式人生 > >python第七章:常用模塊--小白博客

python第七章:常用模塊--小白博客

eve cep rt thread pre 動作 oot sso current 博客

yagmail模塊

python標準庫中發送電子郵件的模塊比較復雜,因此,有許多開原的庫提供了更加易用的接口來發送電子郵件,其中yagmail是一個使用比較廣泛的開原項目,yagmail底層依然使用了smtplib和email模塊,但是yagmail提供了更好的接口,並具有更好的易讀性

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

pip install yagmai

用法:

技術分享圖片
#連接郵箱服務器
yag = yagmail.SMTP(user=[email protected], password=xxxx, host=smtp.163.com)
#發送郵件
yag.send(to
=[email protected], cc=[email protected],subject=這是測試郵件, contents=這是測試郵件的內容) #斷開連接 yag.close()
View Code

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

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(rC:\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, rC:\Users\fengzi\Desktop\test3.yml)
sftp.close()
View Code

pyinotify模塊

pip 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()
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
ip="127.0.0.1"
name="root"
pwd="root"
#發送命令執行交互  
child=pexpect.spawn(ssh  %s@%s % ("root",ip)  )
child.expect (password:)
child.sendline(pwd)
child.expect($)
child.sendline(df -h)
#發送命令  
child.sendline("exit")
child.interact()
#關閉pexpect  
child.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))
View Code

全雙工

技術分享圖片
#全雙工電話
#服務器端
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()
View Code

socket監控服務端口

技術分享圖片
#監控服務端口,不通就發郵件報警
def sendmail(message, ip):
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
    sender = [email protected]
    receiver = [email protected]
    subject = %s報警 % ip
    username = [email protected]
    password = xxxx
    msg = MIMEText(message, plain, utf-8)
    msg[Subject] = Header(subject, utf-8)
    msg[From] = Tim<[email protected]>
    msg[To] = "[email protected]"
    smtp = smtplib.SMTP()
    smtp.connect(smtp.163.com)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
import re
import socket
socket.setdefaulttimeout(1)
server = socket.socket()
host_list = [192.168.4.145:5555]
for info in host_list:
    ip = re.compile((.*?):(.*)).search(info).group(1)
    port = re.compile((.*?):(.*)).search(info).group(2)
    print(ip, port)
res = server.connect_ex((ip, int(port)))
if res != 0:
    sendmail(%s不通 % port, ip)
View Code

socket數據粘包

#nagle算法:會把數據量較小並且時間間隔較短的數據打包成一個發送給服務器

技術分享圖片
服務端:
import socket
import subprocess
server = socket.socket()
server.bind((127.0.0.1, 8888))
server.listen(5)
print(等待電話.....)
conn, addr = server.accept()
print(電話來了......)
while True:
    data = conn.recv(1024)
    cmd = subprocess.Popen(data.decode(utf-8),
                           shell=True,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    stdout = cmd.stdout.read()
    stderr = cmd.stdout.read()
    total_size = len(stdout + stderr)
    conn.send(str(total_size).encode(utf-8))
    conn.send(stdout + stderr)



客戶端:
import socket
client = socket.socket()
client.connect((127.0.0.1, 8888))
while True:
    info = input(===>:)
    if not info:continue
    client.send(info.encode(utf-8))
    total_size = client.recv(1024)
    recv_size = 0
    recv_data = b‘‘
    while recv_size < int(total_size.decode(utf-8)):
        data = client.recv(1024)
        recv_size += len(data)
        recv_data += data
    print(recv_data.decode(gbk))
    print(總大小:%s\n接收大小:%s % (total_size.decode(utf-8), recv_size))
View Code

re模塊:調用正則(.*?與.*很重要,熟記熟練)

技術分享圖片
import re
import socket
socket.setdefaulttimeout(1)
server = socket.socket()
host_list = [192.168.4.145:5555,127.0.0.1:8888,2.2.2.2:80,3.3.3.3:3333]
for info in host_list:
    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不通 % port, ip)
View Code

\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個分組的子表達式,如果它經匹配。否則指的是八進制字符碼的表達式。

python第七章:常用模塊--小白博客