yagmail子產品
python标準庫中發送電子郵件的子產品比較複雜,是以,有許多開原的庫提供了更加易用的接口來發送電子郵件,其中yagmail是一個使用比較廣泛的開原項目,yagmail底層依然使用了smtplib和email子產品,但是yagmail提供了更好的接口,并具有更好的易讀性
yagmail是開原項目,是以,在使用前需要安裝
pip install yagmail
用法:
#連接配接郵箱伺服器
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(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
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() #等同于socket.socket(socket.AF_INET,socket.SOCK_STREAM) 代表TCP協定,預設值
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()
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個分組的子表達式,如果它經比對。否則指的是八進制字元碼的表達式。