python經常使用運維腳本

1.獲取外網ippython

#!/usr/bin/env python
-*- coding:utf-8 -*-
Time: 2019/12/20  10:05
import socket
import requests,re
#方法一
text=requests.get("http://txt.go.sohu.com/ip/soip").text
ip=re.findall(r'\d+.\d+.\d+.\d+',text)
#方法二
ipqwb = socket.getaddrinfo('www.baidu.com', 'http') #獲取指定域名的A記錄
nowIp = (ipqwb[0][4][0])    # 賦值
print("本機外網IP: " + ip[0])
print("qwb    IP: " + nowIp)

2.生成隨機密碼:git

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time: 2019/11/21  11:43
import random,string
def passwd():
    src = string.ascii_letters + string.digits
    count = input('請確認要生成幾條密碼: ')
    list_passwds = []
    for i in range(int(count)):
        #密碼位數爲N+3,例以下面就是5+3=8位密碼
        list_passwd_all = random.sample(src, 5) #從字母和數字中隨機取5位
        list_passwd_all.extend(random.sample(string.digits, 1))  #讓密碼中必定包含數字
        list_passwd_all.extend(random.sample(string.ascii_lowercase, 1)) #讓密碼中必定包含小寫字母
        list_passwd_all.extend(random.sample(string.ascii_uppercase, 1)) #讓密碼中必定包含大寫字母
        random.shuffle(list_passwd_all) #打亂列表順序
        str_passwd = ''.join(list_passwd_all) #將列表轉化爲字符串
        if str_passwd not in list_passwds: #判斷是否生成重複密碼
            list_passwds.append(str_passwd)
        print(list_passwds[i])
    #print(list_passwds)
passwd()

3.發送郵件:app

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time: 2019/11/15  17:18
import smtplib
from email.mime.text import MIMEText
from time import sleep
from email.header import Header
host = 'smtp.163.com'
port = 25
sender = 'xxxx@163.com'
pwd = 'xxxxx'
receiver = ['22222222@qq.com', 'xxxxxxxx@163.com']  # 能夠不用添加本身的郵箱,添加爲了防止系統認爲是垃圾郵箱發送失敗會報錯
body = '郵件內容'
title = '郵件標題'
def sentemail():
    msg = MIMEText(body, 'plain', 'utf-8')
    msg['subject'] = Header(title, 'utf-8').encode()
    msg['from'] = sender
    msg['to'] = ','.join(receiver)
    try:
        s = smtplib.SMTP(host, port)
        s.login(sender, pwd)
        s.sendmail(sender, receiver, msg.as_string())
        print ('Done.sent email success')
    except smtplib.SMTPException as e:
        print ('Error.sent email fail')
        print (e)
if __name__ == '__main__':
    sentemail()

4.基礎log日誌配置:dom

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time: 2019/11/27  13:04
import logging
def logger():
    logger=logging.getLogger()

    fh=logging.FileHandler("test.log")     #向文件中發送內容,有本身默認的日誌格式
    ch=logging.StreamHandler()             #向屏幕發送文件,有本身默認的日誌格式

    fm=logging.Formatter("%(asctime)s %(message)s")  #定義本身的日誌格式
    fh.setFormatter(fm)                    #添加自定義的日誌格式,若是不添加會用本身默認的日誌格式
    ch.setFormatter(fm)

    logger.addHandler(fh)          #顯示出fh,ch的日誌
    logger.addHandler(ch)
    logger.setLevel("DEBUG")       #定義日誌級別
    return logger                  # 返回函數對象

logger=logger()                     #調用函數

logger.debug("hello 1")            #打印日誌
logger.info("hello 2")
logger.warning("hello 3")
logger.error("hello 4")
logger.critical("hello 5")

5.查看本地端口是否開放:socket

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Time: 2019/11/21  11:05
import socket

port_number = [135,443,80,3306,22]

for index in port_number:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('127.0.0.1', index))
    if result == 0:
        print("Port %d is open" % index)
    else:
        print("Port %d is not open" % index)
    sock.close()
相關文章
相關標籤/搜索