当前位置:   article > 正文

python常用小脚本总结

小脚本

日常生活中常会遇到一些小任务,如果人工处理会很麻烦。

用python做些小脚本处理,能够提高不少效率。或者可以把python当工具使用,辅助提高一下办公效率。(比如我常拿python当计算器,计算和字符转换用)

以下总结下个人用到的一些python小脚本留作备忘。

打印16进制字符串

用途:通信报文中的hex数据不好看,可以打印为16进制的字符串显示出来。

  1. #coding=utf-8
  2. #name: myutil.py
  3. def print_hex1(s,prev='0x'):
  4. for c in s:
  5. print '%s%02x' %(prev,ord(c)),
  6. print
  7. def print_hex(s):
  8. for c in s:
  9. print '%02x' %(ord(c)),
  10. print
  11. print 'myutil'
  12. def print_hex3(s,prev='0x'):
  13. i = 0
  14. for c in s:
  15. print '%s%s,' %(prev,s[i:i+2]),
  16. i += 2
  17. print

文件合并

之前搞单片机时生成的hex应用程序文件不能直接刷到单片机里,还需要把iap程序合并成一个文件才能烧写到单片机。每次打包麻烦,做个脚本处理:

  1. #path='C:\\Users\\test\\IAP_CZ_v204w.hex'
  2. #file=open(path,'r')
  3. #for ll in file.readlines()
  4. # print ll
  5. #coding=gb18030
  6. import time
  7. import os
  8. def prr():
  9. print 'file combination begin..'
  10. path0=os.getcwd()
  11. print path0
  12. path=path0
  13. #path1=path0
  14. path2=path0
  15. path+='\\IAP_CZ_v204w.hex'
  16. #path1+='\\NC_armStaSystem.hex'
  17. path2+='\\'
  18. print path
  19. s=raw_input('enter file path:')
  20. path1=s
  21. #path1+='\\NC_armStaSystem.hex'
  22. print path1
  23. s=raw_input('enter file name:')
  24. path2+=s
  25. path2+=time.strftime('_%y%m%d%H%M%S')
  26. path2+='.hex'
  27. print path2
  28. prr()
  29. try:
  30. f1=open(path,'r')
  31. count=0
  32. for l in f1.readlines():
  33. # print l
  34. count+=1
  35. #print count
  36. f1.close()
  37. f1=open(path,'r')
  38. f2=open(path1,'r')
  39. f3=open(path2,'w')
  40. while(count>1):
  41. l=f1.readline()
  42. # print l
  43. f3.write(l)
  44. count-=1
  45. # print count
  46. f3.flush()
  47. for l in f2.readlines():
  48. f3.write(l)
  49. f3.flush()
  50. f3.close()
  51. print 'combination success!'
  52. except Exception,ex:
  53. print 'excettion occured!'
  54. print ex
  55. s=raw_input('press any key to continue...')
  56. finally:
  57. f1.close()
  58. f2.close()
  59. s=raw_input('press any key to continue...')

多线程下载图集

网上好看的动漫图集,如果手工下载太费时了。简单分析下网页地址规律,写个多线程脚本搞定。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # filename: paxel.py
  4. '''It is a multi-thread downloading tool
  5. It was developed follow axel.
  6. Author: volans
  7. E-mail: volansw [at] gmail.com
  8. '''
  9. import sys
  10. import os
  11. import time
  12. import urllib
  13. from threading import Thread
  14. local_proxies = {'http': 'http://131.139.58.200:8080'}
  15. class AxelPython(Thread, urllib.FancyURLopener):
  16. '''Multi-thread downloading class.
  17. run() is a vitural method of Thread.
  18. '''
  19. def __init__(self, threadname, url, filename, ranges=0, proxies={}):
  20. Thread.__init__(self, name=threadname)
  21. urllib.FancyURLopener.__init__(self, proxies)
  22. self.name = threadname
  23. self.url = url
  24. self.filename = filename
  25. self.ranges = ranges
  26. self.downloaded = 0
  27. def run(self):
  28. '''vertual function in Thread'''
  29. try:
  30. self.downloaded = os.path.getsize( self.filename )
  31. except OSError:
  32. #print 'never downloaded'
  33. self.downloaded = 0
  34. # rebuild start poind
  35. self.startpoint = self.ranges[0] + self.downloaded
  36. # This part is completed
  37. if self.startpoint >= self.ranges[1]:
  38. print 'Part %s has been downloaded over.' % self.filename
  39. return
  40. self.oneTimeSize = 16384 #16kByte/time
  41. print 'task %s will download from %d to %d' % (self.name, self.startpoint, self.ranges[1])
  42. self.addheader("Range", "bytes=%d-%d" % (self.startpoint, self.ranges[1]))
  43. self.urlhandle = self.open( self.url )
  44. data = self.urlhandle.read( self.oneTimeSize )
  45. while data:
  46. filehandle = open( self.filename, 'ab+' )
  47. filehandle.write( data )
  48. filehandle.close()
  49. self.downloaded += len( data )
  50. #print "%s" % (self.name)
  51. #progress = u'\r...'
  52. data = self.urlhandle.read( self.oneTimeSize )
  53. def GetUrlFileSize(url, proxies={}):
  54. urlHandler = urllib.urlopen( url, proxies=proxies )
  55. headers = urlHandler.info().headers
  56. length = 0
  57. for header in headers:
  58. if header.find('Length') != -1:
  59. length = header.split(':')[-1].strip()
  60. length = int(length)
  61. return length
  62. def SpliteBlocks(totalsize, blocknumber):
  63. blocksize = totalsize/blocknumber
  64. ranges = []
  65. for i in range(0, blocknumber-1):
  66. ranges.append((i*blocksize, i*blocksize +blocksize - 1))
  67. ranges.append(( blocksize*(blocknumber-1), totalsize -1 ))
  68. return ranges
  69. def islive(tasks):
  70. for task in tasks:
  71. if task.isAlive():
  72. return True
  73. return False
  74. def paxel(url, output, blocks=6, proxies=local_proxies):
  75. ''' paxel
  76. '''
  77. size = GetUrlFileSize( url, proxies )
  78. ranges = SpliteBlocks( size, blocks )
  79. threadname = [ "thread_%d" % i for i in range(0, blocks) ]
  80. filename = [ "tmpfile_%d" % i for i in range(0, blocks) ]
  81. tasks = []
  82. for i in range(0,blocks):
  83. task = AxelPython( threadname[i], url, filename[i], ranges[i] )
  84. task.setDaemon( True )
  85. task.start()
  86. tasks.append( task )
  87. time.sleep( 2 )
  88. while islive(tasks):
  89. downloaded = sum( [task.downloaded for task in tasks] )
  90. process = downloaded/float(size)*100
  91. show = u'\rFilesize:%d Downloaded:%d Completed:%.2f%%' % (size, downloaded, process)
  92. sys.stdout.write(show)
  93. sys.stdout.flush()
  94. time.sleep( 0.5 )
  95. filehandle = open( output, 'wb+' )
  96. for i in filename:
  97. f = open( i, 'rb' )
  98. filehandle.write( f.read() )
  99. f.close()
  100. try:
  101. os.remove(i)
  102. pass
  103. except:
  104. pass
  105. filehandle.close()
  106. if __name__ == '__main__':
  107. url = "http://xz1.mm667.com/xz84/images/001.jpg"
  108. output = '001.jpg'
  109. paxel( url, output, blocks=4, proxies={} )

多线程下载图片

多线程下载图片并存储到指定目录中,若目录不存在则自动创建。

  1. # -*- coding: UTF-8 -*-
  2. '''
  3. import re
  4. import urllib
  5. urls='http://xz5.mm667.com/xz82/images/01.jpg'
  6. def getHtml(url):
  7. page = urllib.urlopen(url)
  8. html = page.read()
  9. return html
  10. def getImg(html):
  11. reg = r'src="(.+?\.jpg)" pic_ext'
  12. imgre = re.compile(reg)
  13. imglist = imgre.findall(html)
  14. x = 0
  15. for imgurl in imglist:
  16. urllib.urlretrieve(imgurl,'%s.jpg' % x)
  17. x = x + 1
  18. html = getHtml("http://tieba.baidu.com/p/2460150866")
  19. getImg(html)
  20. '''
  21. import re
  22. import urllib
  23. import threading
  24. import time
  25. import socket
  26. socket.setdefaulttimeout(30)
  27. urls=[]
  28. j=0
  29. for i in xrange(1,81):
  30. if (i-1)%4 == 0:
  31. j += 1
  32. if ((j-1)%5) == 0 :
  33. j=1
  34. site='http://xz%d.mm667.com/xz%02d/images/' %(j,i)
  35. urls.append(site)
  36. print urls[i-1]
  37. #print urls
  38. '''
  39. urls.append('http://xz1.mm667.com/xz01/images/')
  40. urls.append('http://xz1.mm667.com/xz02/images/')
  41. urls.append('http://xz1.mm667.com/xz03/images/')
  42. urls.append('http://xz1.mm667.com/xz04/images/')
  43. urls.append('http://xz1.mm667.com/xz84/images/')
  44. urls.append('http://xz2.mm667.com/xz85/images/')
  45. urls.append('http://xz3.mm667.com/xz86/images/')
  46. urls.append('http://xz1.mm667.com/s/')
  47. urls.append('http://xz1.mm667.com/p/')
  48. '''
  49. def mkdir(path):
  50. # 引入模块
  51. import os
  52. # 去除首位空格
  53. path=path.strip()
  54. # 去除尾部 \ 符号
  55. path=path.rstrip("\\")
  56. # 判断路径是否存在
  57. # 存在 True
  58. # 不存在 False
  59. isExists=os.path.exists(path)
  60. # 判断结果
  61. if not isExists:
  62. # 如果不存在则创建目录
  63. print path+u' 创建成功'
  64. # 创建目录操作函数
  65. os.makedirs(path)
  66. return True
  67. else:
  68. # 如果目录存在则不创建,并提示目录已存在
  69. print path+u' 目录已存在'
  70. return False
  71. def cbk(a,b,c):
  72. '''''回调函数
  73. @a: 已经下载的数据块
  74. @b: 数据块的大小
  75. @c: 远程文件的大小
  76. '''
  77. per = 100.0 * a * b / c
  78. if per > 100:
  79. per = 100
  80. print '%.2f%%' % per
  81. #url = 'http://www.sina.com.cn'
  82. local = 'd:\\mysite\\pic1\\'
  83. d=0
  84. mutex = threading.Lock()
  85. # mutex1 = threading.Lock()
  86. class MyThread(threading.Thread):
  87. def __init__(self, url, name):
  88. threading.Thread.__init__(self)
  89. self.url=url
  90. self.name=name
  91. def run(self):
  92. mutex.acquire()
  93. print
  94. print 'down from %s' % self.url
  95. time.sleep(1)
  96. mutex.release()
  97. try:
  98. urllib.urlretrieve(self.url, self.name)
  99. except Exception,e:
  100. print e
  101. time.sleep(1)
  102. urllib.urlretrieve(self.url, self.name)
  103. threads=[]
  104. for u in urls[84:]:
  105. d += 1
  106. local = 'd:\\mysite\\pic1\\%d\\' %d
  107. mkdir(local)
  108. print 'download begin...'
  109. for i in xrange(40):
  110. lcal = local
  111. url=u
  112. url += '%03d.jpg' %i
  113. lcal += '%03d.jpg' %i
  114. th = MyThread(url,lcal)
  115. threads.append(th)
  116. th.start()
  117. # for t in threads:
  118. # t.join()
  119. print 'over! download finished'

爬虫抓取信息

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. Python爬虫,抓取一卡通相关企业信息
  5. Anthor: yangyongzhen
  6. Version: 0.0.2
  7. Date: 2014-12-14
  8. Language: Python2.7.5
  9. Editor: Sublime Text2
  10. """
  11. import urllib2, re, string
  12. import threading, Queue, time
  13. import sys
  14. import os
  15. from bs4 import BeautifulSoup
  16. #from pprint import pprint
  17. reload(sys)
  18. sys.setdefaultencoding('utf8')
  19. _DATA = []
  20. FILE_LOCK = threading.Lock()
  21. SHARE_Q = Queue.Queue() #构造一个不限制大小的的队列
  22. _WORKER_THREAD_NUM = 3 #设置线程的个数
  23. _Num = 0 #总条数
  24. class MyThread(threading.Thread) :
  25. def __init__(self, func,num) :
  26. super(MyThread, self).__init__() #调用父类的构造函数
  27. self.func = func #传入线程函数逻辑
  28. self.thread_num = num
  29. def run(self) :
  30. self.func()
  31. #print u'线程ID:',self.thread_num
  32. def worker() :
  33. global SHARE_Q
  34. while not SHARE_Q.empty():
  35. url = SHARE_Q.get() #获得任务
  36. my_page = get_page(url)
  37. find_data(my_page) #获得当前页面的数据
  38. #write_into_file(temp_data)
  39. time.sleep(1)
  40. SHARE_Q.task_done()
  41. def get_page(url) :
  42. """
  43. 根据所给的url爬取网页HTML
  44. Args:
  45. url: 表示当前要爬取页面的url
  46. Returns:
  47. 返回抓取到整个页面的HTML(unicode编码)
  48. Raises:
  49. URLError:url引发的异常
  50. """
  51. try :
  52. html = urllib2.urlopen(url).read()
  53. my_page = html.decode("gbk",'ignore')
  54. #my_page = unicode(html,'utf-8','ignore').encode('utf-8','ignore')
  55. #my_page = urllib2.urlopen(url).read().decode("utf8")
  56. except urllib2.URLError, e :
  57. if hasattr(e, "code"):
  58. print "The server couldn't fulfill the request."
  59. print "Error code: %s" % e.code
  60. elif hasattr(e, "reason"):
  61. print "We failed to reach a server. Please check your url and read the Reason"
  62. print "Reason: %s" % e.reason
  63. return my_page
  64. def find_data(my_page) :
  65. """
  66. 通过返回的整个网页HTML, 正则匹配名称
  67. Args:
  68. my_page: 传入页面的HTML文本用于正则匹配
  69. """
  70. global _Num
  71. temp_data = []
  72. items = BeautifulSoup(my_page).find_all("div", style="width:96%;margin:10px;border-bottom:1px #CCC dashed;padding-bottom:10px;")
  73. for index, item in enumerate(items) :
  74. #print item
  75. #print item.h1
  76. #print h.group()
  77. #temp_data.append(item)
  78. #print item.find(re.compile("^a"))
  79. href = item.find(re.compile("^a"))
  80. #soup = BeautifulSoup(item)
  81. #公司名称
  82. if item.a:
  83. data = item.a.string.encode("gbk","ignore")
  84. print data
  85. temp_data.append(data)
  86. goods = item.find_all("div", style="font-size:12px;")
  87. #经营产品与联系方式
  88. for i in goods:
  89. data = i.get_text().encode("gbk","ignore")
  90. temp_data.append(data)
  91. print data
  92. #b = item.find_all("b")
  93. #print b
  94. #链接地址
  95. pat = re.compile(r'href="([^"]*)"')
  96. h = pat.search(str(item))
  97. if h:
  98. #print h.group(0)
  99. href = h.group(1)
  100. print href
  101. temp_data.append(h.group(1))
  102. _Num += 1
  103. #b = item.find_all(text=re.compile("Dormouse"))
  104. #pprint(goods)
  105. #print href
  106. #pat = re.compile(r'title="([^"]*)"')
  107. #h = pat.search(str(href))
  108. #if h:
  109. #print h.group(1)
  110. #temp_data.append(h.group(1))
  111. _DATA.append(temp_data)
  112. #headers = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"}##浏览器请求头(大部分网站没有这个请求头会报错、请务必加上哦)
  113. #all_url = 'http://www.mzitu.com/all' ##开始的URL地址
  114. #start_html = requests.get(all_url, headers=headers) ##使用requests中的get方法来获取all_url(就是:http://www.mzitu.com/all这个地址)的内容 headers为上面设置的请求头、请务必参考requests官方文档解释
  115. #print(start_html.text) ##打印出start_html (请注意,concent是二进制的数据,一般用于下载图片、视频、音频、等多媒体内容是才使用concent, 对于打印网页内容请使用text)
  116. def main() :
  117. global SHARE_Q
  118. threads = []
  119. start = time.clock()
  120. douban_url = "http://company.yktworld.com/comapny_search.asp?page={page}"
  121. #向队列中放入任务, 真正使用时, 应该设置为可持续的放入任务
  122. for index in xrange(20) :
  123. SHARE_Q.put(douban_url.format(page = index * 1))
  124. for i in xrange(_WORKER_THREAD_NUM) :
  125. thread = MyThread(worker,i)
  126. thread.start() #线程开始处理任务
  127. threads.append(thread)
  128. for thread in threads :
  129. thread.join()
  130. SHARE_Q.join()
  131. i = 0
  132. with open("down.txt", "w+") as my_file :
  133. for page in _DATA :
  134. i += 1
  135. for name in page:
  136. my_file.write(name + "\n")
  137. print "Spider Successful!!!"
  138. end = time.clock()
  139. print u'抓取完成!'
  140. print u'总页数:',i
  141. print u'总条数:',_Num
  142. print u'一共用时:',end-start,u'秒'
  143. if __name__ == '__main__':
  144. main()

爬虫多线程下载电影名称

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. Python爬虫
  5. Anthor: yangyongzhen
  6. Version: 0.0.2
  7. Date: 2014-12-14
  8. Language: Python2.7.8
  9. Editor: Sublime Text2
  10. """
  11. import urllib2, re, string
  12. import threading, Queue, time
  13. import sys
  14. import os
  15. from bs4 import BeautifulSoup
  16. reload(sys)
  17. sys.setdefaultencoding('utf8')
  18. _DATA = []
  19. FILE_LOCK = threading.Lock()
  20. SHARE_Q = Queue.Queue() #构造一个不限制大小的的队列
  21. _WORKER_THREAD_NUM = 3 #设置线程的个数
  22. rootpath = os.getcwd()+u'/抓取的内容/'
  23. def makedir(path):
  24. if not os.path.isdir(path):
  25. os.makedirs(path)
  26. #创建抓取的根目录
  27. #makedir(rootpath)
  28. #显示下载进度
  29. def Schedule(a,b,c):
  30. '''''
  31. a:已经下载的数据块
  32. b:数据块的大小
  33. c:远程文件的大小
  34. '''
  35. per = 100.0 * a * b / c
  36. if per > 100 :
  37. per = 100
  38. print '%.2f%%' % per
  39. class MyThread(threading.Thread) :
  40. def __init__(self, func) :
  41. super(MyThread, self).__init__() #调用父类的构造函数
  42. self.func = func #传入线程函数逻辑
  43. def run(self) :
  44. self.func()
  45. def worker() :
  46. print 'work thread start...\n'
  47. global SHARE_Q
  48. while not SHARE_Q.empty():
  49. url = SHARE_Q.get() #获得任务
  50. my_page = get_page(url)
  51. find_title(my_page) #获得当前页面的电影名
  52. #write_into_file(temp_data)
  53. time.sleep(1)
  54. SHARE_Q.task_done()
  55. def get_page(url) :
  56. """
  57. 根据所给的url爬取网页HTML
  58. Args:
  59. url: 表示当前要爬取页面的url
  60. Returns:
  61. 返回抓取到整个页面的HTML(unicode编码)
  62. Raises:
  63. URLError:url引发的异常
  64. """
  65. try :
  66. html = urllib2.urlopen(url).read()
  67. my_page = html.decode("utf8")
  68. #my_page = unicode(html,'utf-8','ignore').encode('utf-8','ignore')
  69. #my_page = urllib2.urlopen(url).read().decode("utf8")
  70. except urllib2.URLError, e :
  71. if hasattr(e, "code"):
  72. print "The server couldn't fulfill the request."
  73. print "Error code: %s" % e.code
  74. elif hasattr(e, "reason"):
  75. print "We failed to reach a server. Please check your url and read the Reason"
  76. print "Reason: %s" % e.reason
  77. return my_page
  78. def find_title(my_page) :
  79. """
  80. 通过返回的整个网页HTML, 正则匹配前100的电影名称
  81. Args:
  82. my_page: 传入页面的HTML文本用于正则匹配
  83. """
  84. temp_data = []
  85. movie_items = BeautifulSoup(my_page).findAll('h1')
  86. for index, item in enumerate(movie_items) :
  87. #print item
  88. #print item.h1
  89. pat = re.compile(r'href="([^"]*)"')
  90. h = pat.search(str(item))
  91. if h:
  92. #print h.group(0)
  93. href = h.group(1)
  94. print href
  95. temp_data.append(h.group(1))
  96. #print h.group()
  97. #temp_data.append(item)
  98. #print item.find(re.compile("^a"))
  99. href = item.find(re.compile("^a"))
  100. #soup = BeautifulSoup(item)
  101. if item.a:
  102. #print item.a.string
  103. temp_data.append(item.a.string)
  104. #print href
  105. #pat = re.compile(r'title="([^"]*)"')
  106. #h = pat.search(str(href))
  107. #if h:
  108. #print h.group(1)
  109. #temp_data.append(h.group(1))
  110. _DATA.append(temp_data)
  111. def main() :
  112. global SHARE_Q
  113. threads = []
  114. start = time.clock()
  115. douban_url = "http://movie.misszm.com/page/{page}"
  116. #向队列中放入任务, 真正使用时, 应该设置为可持续的放入任务
  117. for index in xrange(5) :
  118. SHARE_Q.put(douban_url.format(page = index * 1))
  119. for i in xrange(_WORKER_THREAD_NUM) :
  120. thread = MyThread(worker)
  121. thread.start() #线程开始处理任务
  122. threads.append(thread)
  123. for thread in threads :
  124. thread.join()
  125. SHARE_Q.join()
  126. with open("movie.txt", "w+") as my_file :
  127. for page in _DATA :
  128. for movie_name in page:
  129. my_file.write(movie_name + "\n")
  130. print "Spider Successful!!!"
  131. end = time.clock()
  132. print u'抓取完成!'
  133. print u'一共用时:',end-start,u'秒'
  134. if __name__ == '__main__':
  135. main()

串口转tcp工具

  1. #coding=utf-8
  2. #author:yangyongzhen
  3. #QQ:534117529
  4. #'CardTest TcpServer - Simple Test Card Tool 1.00'
  5. import sys,threading,time;
  6. import serial;
  7. import binascii,encodings;
  8. import re;
  9. import os;
  10. from socket import *
  11. from struct import *;
  12. #from myutil import *;
  13. #name: myutil.py
  14. mylock = threading.RLock()
  15. Server_IP = ''
  16. Srever_Port = ''
  17. def print_hex1(s,prev='0x'):
  18. for c in s:
  19. print '%s%02x' %(prev,ord(c)),
  20. print
  21. def print_hex(s):
  22. for c in s:
  23. print '%02x' %(ord(c)),
  24. print
  25. def hexto_str(s):
  26. r =''
  27. for c in s:
  28. r += '%02x' %(ord(c))
  29. return r
  30. def strto_hex(s):
  31. r = s.decode('hex')
  32. return r
  33. #''代表服务器为localhost
  34. #在一个非保留端口号上进行监听
  35. class ComThread:
  36. def __init__(self, Port=0):
  37. self.l_serial = None;
  38. self.alive = False;
  39. self.waitEnd = None;
  40. self.port = Port;
  41. #TCP部分
  42. #self.sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  43. self.connection = None
  44. #数据
  45. self.snddata = ''
  46. self.rcvdata = ''
  47. def waiting(self):
  48. if not self.waitEnd is None:
  49. self.waitEnd.wait();
  50. def SetStopEvent(self):
  51. if not self.waitEnd is None:
  52. self.waitEnd.set();
  53. self.alive = False;
  54. self.stop();
  55. def start(self):
  56. self.l_serial = serial.Serial();
  57. self.l_serial.port = self.port;
  58. self.l_serial.baudrate = 115200;
  59. self.l_serial.timeout = 2; #秒
  60. self.l_serial.open();
  61. if self.l_serial.isOpen():
  62. self.waitEnd = threading.Event();
  63. self.alive = True;
  64. print 'open serial port %d ok!\n' %(self.port+1)
  65. print 'baudrate:115200 \n'
  66. self.thread_read = None;
  67. self.thread_read = threading.Thread(target=self.FirstReader);
  68. self.thread_read.setDaemon(1);
  69. self.thread_read.start();
  70. self.thread_write = None;
  71. self.thread_write = threading.Thread(target=self.FirstWriter);
  72. self.thread_write.setDaemon(1);
  73. self.thread_write.start();
  74. #TCP部分
  75. self.thread_TcpClient = None;
  76. self.thread_TcpClient = threading.Thread(target=self.TcpClient);
  77. self.thread_TcpClient.setDaemon(1);
  78. self.thread_TcpClient.start();
  79. self.thread_TcpSend = None;
  80. self.thread_TcpSend = threading.Thread(target=self.TcpSend);
  81. self.thread_TcpSend.setDaemon(1);
  82. self.thread_TcpSend.start();
  83. return True;
  84. else:
  85. return False;
  86. def FirstReader(self):
  87. while self.alive:
  88. # 接收间隔
  89. time.sleep(0.1);
  90. try:
  91. data = '';
  92. n = self.l_serial.inWaiting();
  93. if n:
  94. data = data+self.l_serial.read(n);
  95. #for l in xrange(len(data)):
  96. #print '%02X' % ord(data[l]),
  97. # 发送数据
  98. print u'->请求:'
  99. print data;
  100. mylock.acquire()
  101. self.snddata = data
  102. mylock.release()
  103. #print_hex(data);
  104. # 判断结束
  105. except Exception, ex:
  106. print str(ex);
  107. self.waitEnd.set();
  108. self.alive = False;
  109. def FirstWriter(self):
  110. while self.alive:
  111. # 接收间隔
  112. time.sleep(0.1);
  113. try:
  114. #snddata = raw_input('\nenter data send:\n')
  115. if self.rcvdata!='':
  116. self.l_serial.write(self.rcvdata);
  117. print u'-<应答:'
  118. print self.rcvdata;
  119. mylock.acquire()
  120. self.rcvdata = '';
  121. mylock.release()
  122. #print_hex(snddata);
  123. except Exception, ex:
  124. print str(ex);
  125. self.waitEnd.set();
  126. self.alive = False;
  127. def TcpClient(self):
  128. while True:
  129. # 接收间隔
  130. time.sleep(0.1);
  131. self.connection = socket(AF_INET, SOCK_STREAM);
  132. self.connection.connect((Server_IP, int(Server_Port)));
  133. print 'Connect to Server OK!';
  134. self.snddata = ''
  135. self.rcvdata = ''
  136. while True:
  137. #读取客户端套接字的下一行
  138. data = self.connection.recv(1024)
  139. #如果没有数量的话,那么跳出循环
  140. if not data: break
  141. #发送一个回复至客户端
  142. mylock.acquire()
  143. self.snddata = ''
  144. self.rcvdata = data
  145. mylock.release()
  146. #connection.send('Echo=>' + data)
  147. self.connection.close()
  148. self.waitEnd.set();
  149. self.alive = False;
  150. def TcpSend(self):
  151. while True:
  152. # 接收间隔
  153. time.sleep(0.1);
  154. while True:
  155. time.sleep(0.1);
  156. try:
  157. if not self.connection is None:
  158. if self.snddata != '':
  159. self.connection.send(self.snddata)
  160. mylock.acquire()
  161. self.rcvdata = ''
  162. self.snddata = ''
  163. mylock.release()
  164. except Exception, ex:
  165. pass
  166. def stop(self):
  167. self.alive = False;
  168. self.thread_read.join();
  169. if self.l_serial.isOpen():
  170. self.l_serial.close();
  171. #测试用部分
  172. if __name__ == '__main__':
  173. print 'Serial to Tcp Tool 1.00\n'
  174. print 'Author:yangyongzhen\n'
  175. print 'QQ:534117529\n'
  176. print 'Copyright (c) **cap 2015-2016.\n'
  177. Server_IP = raw_input('please enter ServerIP:')
  178. print 'Server_IP: %s' %(Server_IP)
  179. Server_Port = raw_input('please enter ServerPort:')
  180. print 'Server_Port: %s' %(Server_Port)
  181. com =raw_input('please enter com port(1-9):')
  182. rt = ComThread(int(com)-1);
  183. try:
  184. if rt.start():
  185. rt.waiting();
  186. rt.stop();
  187. else:
  188. pass;
  189. except Exception,se:
  190. print str(se);
  191. if rt.alive:
  192. rt.stop();
  193. os.system("pause")
  194. print '';
  195. print 'End OK .';
  196. del rt;

远程读卡器server端

很早之前做过一个远程读卡器工具,原理就是在现场客服电脑上装个python做的tcpserver服务端,操控现场的读卡器。在公司内部做个客户端连接过去,这样实现在公司调试现场的卡片业务。

这个就是服务端工具的实现:

  1. #coding=utf-8
  2. #author:yangyongzhen
  3. #QQ:534117529
  4. #'CardTest TcpServer - Simple Test Card Tool 1.00'
  5. import sys,threading,time;
  6. import serial;
  7. import binascii,encodings;
  8. import re;
  9. import os;
  10. from socket import *
  11. from struct import *;
  12. #from myutil import *;
  13. #name: myutil.py
  14. mylock = threading.RLock()
  15. def print_hex1(s,prev='0x'):
  16. for c in s:
  17. print '%s%02x' %(prev,ord(c)),
  18. print
  19. def print_hex(s):
  20. for c in s:
  21. print '%02x' %(ord(c)),
  22. print
  23. def hexto_str(s):
  24. r =''
  25. for c in s:
  26. r += '%02x' %(ord(c))
  27. return r
  28. def strto_hex(s):
  29. r = s.decode('hex')
  30. return r
  31. #''代表服务器为localhost
  32. #在一个非保留端口号上进行监听
  33. class ComThread:
  34. def __init__(self, Port=0):
  35. self.l_serial = None;
  36. self.alive = False;
  37. self.waitEnd = None;
  38. self.port = Port;
  39. #TCP部分
  40. self.myHost = ''
  41. self.myPort = 5050
  42. self.sockobj = socket(AF_INET, SOCK_STREAM)
  43. self.connection = None
  44. #数据
  45. self.snddata = ''
  46. self.rcvdata = ''
  47. def waiting(self):
  48. if not self.waitEnd is None:
  49. self.waitEnd.wait();
  50. def SetStopEvent(self):
  51. if not self.waitEnd is None:
  52. self.waitEnd.set();
  53. self.alive = False;
  54. self.stop();
  55. def start(self):
  56. self.l_serial = serial.Serial();
  57. self.l_serial.port = self.port;
  58. self.l_serial.baudrate = 115200;
  59. self.l_serial.timeout = 2; #秒
  60. self.l_serial.open();
  61. if self.l_serial.isOpen():
  62. self.waitEnd = threading.Event();
  63. self.alive = True;
  64. print 'open serial port %d ok!\n' %(self.port+1)
  65. print 'baudrate:115200 \n'
  66. self.thread_read = None;
  67. self.thread_read = threading.Thread(target=self.FirstReader);
  68. self.thread_read.setDaemon(1);
  69. self.thread_read.start();
  70. self.thread_write = None;
  71. self.thread_write = threading.Thread(target=self.FirstWriter);
  72. self.thread_write.setDaemon(1);
  73. self.thread_write.start();
  74. #TCP部分
  75. self.thread_TcpServer = None;
  76. self.thread_TcpServer = threading.Thread(target=self.TcpServer);
  77. self.thread_TcpServer.setDaemon(1);
  78. self.thread_TcpServer.start();
  79. self.thread_TcpSend = None;
  80. self.thread_TcpSend = threading.Thread(target=self.TcpSend);
  81. self.thread_TcpSend.setDaemon(1);
  82. self.thread_TcpSend.start();
  83. return True;
  84. else:
  85. return False;
  86. def FirstReader(self):
  87. while self.alive:
  88. # 接收间隔
  89. time.sleep(0.1);
  90. try:
  91. data = '';
  92. n = self.l_serial.inWaiting();
  93. if n:
  94. data = data+self.l_serial.read(n);
  95. #for l in xrange(len(data)):
  96. #print '%02X' % ord(data[l]),
  97. # 发送数据
  98. print 'serial recv:'
  99. print data;
  100. mylock.acquire()
  101. self.snddata = data
  102. mylock.release()
  103. #print_hex(data);
  104. # 判断结束
  105. except Exception, ex:
  106. print str(ex);
  107. self.waitEnd.set();
  108. self.alive = False;
  109. def FirstWriter(self):
  110. while self.alive:
  111. # 接收间隔
  112. time.sleep(0.1);
  113. try:
  114. #snddata = raw_input('\nenter data send:\n')
  115. if self.rcvdata!='':
  116. self.l_serial.write(self.rcvdata);
  117. print 'serial send:'
  118. print self.rcvdata;
  119. mylock.acquire()
  120. self.rcvdata = '';
  121. mylock.release()
  122. #print_hex(snddata);
  123. except Exception, ex:
  124. print str(ex);
  125. self.waitEnd.set();
  126. self.alive = False;
  127. def TcpServer(self):
  128. self.sockobj.bind((self.myHost, self.myPort))
  129. self.sockobj.listen(10)
  130. print 'TcpServer listen at 5050 oK!\n'
  131. print 'Waiting for connect...\n'
  132. while True:
  133. # 接收间隔
  134. time.sleep(0.1);
  135. self.connection, address = self.sockobj.accept()
  136. print 'Server connected by', address
  137. self.snddata = ''
  138. self.rcvdata = ''
  139. try:
  140. while True:
  141. #读取客户端套接字的下一行
  142. data = self.connection.recv(1024)
  143. #如果没有数量的话,那么跳出循环
  144. if not data: break
  145. #发送一个回复至客户端
  146. mylock.acquire()
  147. self.snddata = ''
  148. self.rcvdata = data
  149. mylock.release()
  150. #connection.send('Echo=>' + data)
  151. self.connection.close()
  152. except Exception, ex:
  153. self.connection.close()
  154. self.waitEnd.set();
  155. self.alive = False;
  156. def TcpSend(self):
  157. while True:
  158. # 接收间隔
  159. time.sleep(0.1);
  160. while True:
  161. time.sleep(0.1);
  162. try:
  163. if not self.connection is None:
  164. if self.snddata != '':
  165. self.connection.send(self.snddata)
  166. mylock.acquire()
  167. self.rcvdata = ''
  168. self.snddata = ''
  169. mylock.release()
  170. except Exception, ex:
  171. pass
  172. def stop(self):
  173. self.alive = False;
  174. self.thread_read.join();
  175. if self.l_serial.isOpen():
  176. self.l_serial.close();
  177. #测试用部分
  178. if __name__ == '__main__':
  179. print 'CardTest TcpServer - Simple Test Card Tool 1.00\n'
  180. print 'Author:yangyongzhen\n'
  181. print 'QQ:534117529\n'
  182. print 'Copyright (c) **** 2015-2016.\n'
  183. com =raw_input('please enter com port(1-9):')
  184. rt = ComThread(int(com)-1);
  185. try:
  186. if rt.start():
  187. rt.waiting();
  188. rt.stop();
  189. else:
  190. pass;
  191. except Exception,se:
  192. print str(se);
  193. if rt.alive:
  194. rt.stop();
  195. os.system("pause")
  196. print '';
  197. print 'End OK .';
  198. del rt;

黑客rtcp反向链接

  1. # -*- coding: utf-8 -*-
  2. '''
  3. filename:rtcp.py
  4. @desc:
  5. 利用python的socket端口转发,用于远程维护
  6. 如果连接不到远程,会sleep 36s,最多尝试200(即两小时)
  7. @usage:
  8. ./rtcp.py stream1 stream2
  9. stream为:l:port或c:host:port
  10. l:port表示监听指定的本地端口
  11. c:host:port表示监听远程指定的端口
  12. @author: watercloud, zd, knownsec team
  13. @web: www.knownsec.com, blog.knownsec.com
  14. @date: 2009-7
  15. '''
  16. import socket
  17. import sys
  18. import threading
  19. import time
  20. streams = [None, None] # 存放需要进行数据转发的两个数据流(都是SocketObj对象)
  21. debug = 1 # 调试状态 0 or 1
  22. def print_hex(s):
  23. for c in s:
  24. print '%02x' %(ord(c)),
  25. print
  26. def _usage():
  27. print 'Usage: ./rtcp.py stream1 stream2\nstream : L:port or C:host:port'
  28. def _get_another_stream(num):
  29. '''
  30. 从streams获取另外一个流对象,如果当前为空,则等待
  31. '''
  32. if num == 0:
  33. num = 1
  34. elif num == 1:
  35. num = 0
  36. else:
  37. raise "ERROR"
  38. while True:
  39. if streams[num] == 'quit':
  40. print("can't connect to the target, quit now!")
  41. sys.exit(1)
  42. if streams[num] != None:
  43. return streams[num]
  44. else:
  45. time.sleep(1)
  46. def _xstream(num, s1, s2):
  47. '''
  48. 交换两个流的数据
  49. num为当前流编号,主要用于调试目的,区分两个回路状态用。
  50. '''
  51. try:
  52. while True:
  53. #注意,recv函数会阻塞,直到对端完全关闭(close后还需要一定时间才能关闭,最快关闭方法是shutdow)
  54. buff = s1.recv(1024)
  55. if debug > 0:
  56. print num,"recv"
  57. if len(buff) == 0: #对端关闭连接,读不到数据
  58. print num,"one closed"
  59. break
  60. s2.sendall(buff)
  61. if debug > 0:
  62. print num,"sendall"
  63. print_hex(buff)
  64. except :
  65. print num,"one connect closed."
  66. try:
  67. s1.shutdown(socket.SHUT_RDWR)
  68. s1.close()
  69. except:
  70. pass
  71. try:
  72. s2.shutdown(socket.SHUT_RDWR)
  73. s2.close()
  74. except:
  75. pass
  76. streams[0] = None
  77. streams[1] = None
  78. print num, "CLOSED"
  79. def _server(port, num):
  80. '''
  81. 处理服务情况,num为流编号(第0号还是第1号)
  82. '''
  83. srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  84. srv.bind(('0.0.0.0', port))
  85. srv.listen(1)
  86. #print 'local listening at port %d' (%(port))
  87. while True:
  88. conn, addr = srv.accept()
  89. print "connected from:", addr
  90. streams[num] = conn # 放入本端流对象
  91. s2 = _get_another_stream(num) # 获取另一端流对象
  92. _xstream(num, conn, s2)
  93. def _connect(host, port, num):
  94. ''' 处理连接,num为流编号(第0号还是第1号)
  95. @note: 如果连接不到远程,会sleep 36s,最多尝试200(即两小时)
  96. '''
  97. not_connet_time = 0
  98. wait_time = 36
  99. try_cnt = 199
  100. while True:
  101. if not_connet_time > try_cnt:
  102. streams[num] = 'quit'
  103. print('not connected')
  104. return None
  105. conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  106. try:
  107. conn.connect((host, port))
  108. except Exception, e:
  109. print ('can not connect %s:%s!' % (host, port))
  110. not_connet_time += 1
  111. time.sleep(wait_time)
  112. continue
  113. print "connected to %s:%i" % (host, port)
  114. streams[num] = conn #放入本端流对象
  115. s2 = _get_another_stream(num) #获取另一端流对象
  116. _xstream(num, conn, s2)
  117. if __name__ == '__main__':
  118. print 'Tcp to Tcp Tool 1.00\n'
  119. print 'Author:yangyongzhen\n'
  120. print 'QQ:534117529\n'
  121. print 'Copyright (c) Newcapec 2015-2016.\n'
  122. Server_IP = raw_input('please enter Server IP:')
  123. print 'Server_IP: %s' %(Server_IP)
  124. Server_Port = raw_input('please enter Server Port:')
  125. print 'Server_Port: %s' %(Server_Port)
  126. com =raw_input('please enter Local Port:')
  127. tlist = [] # 线程列表,最终存放两个线程对象
  128. #targv = [sys.argv[1], sys.argv[2] ]
  129. t = threading.Thread(target=_server, args=(int(com), 0))
  130. tlist.append(t)
  131. t = threading.Thread(target=_connect, args=(Server_IP, int(Server_Port), 1))
  132. tlist.append(t)
  133. for t in tlist:
  134. t.start()
  135. for t in tlist:
  136. t.join()
  137. sys.exit(0)

调用c的动态库示例

  1. # -*- coding:utf8 -*-
  2. from ctypes import *
  3. from binascii import unhexlify as unhex
  4. import os
  5. dll = cdll.LoadLibrary('mydll.dll');
  6. print 'begin load mydll..'
  7. #key
  8. #str1='\x9B\xED\x98\x89\x15\x80\xC3\xB2'
  9. str1=unhex('0000556677222238')
  10. #data
  11. str2=unhex('002d2000000100015566772222383CD881604D0D286A556677222238000020141214181427')
  12. #output
  13. str3='\x12\x34\x56\x78\x12\x34\x56\x78'
  14. pstr1=c_char_p()
  15. pstr2=c_char_p()
  16. pstr3=c_char_p()
  17. pstr1.value=str1
  18. pstr2.value=str2
  19. pstr3.value=str3
  20. dll.CurCalc_DES_MAC64(805306481,pstr1,0,pstr2,13,pstr3)
  21. print pstr1
  22. print pstr2
  23. print pstr3
  24. stro= pstr3.value
  25. print stro
  26. strtemp=''
  27. for c in stro:
  28. print "%02x" % (ord(c))
  29. strtemp+="{0:02x}".format(ord(c))
  30. print strtemp
  31. os.execlp("E:\\RSA.exe",'')
  32. s=raw_input('press any key to continue...')

tcp的socket连接报文测试工具

  1. # -*- coding: utf-8 -*-
  2. import socket
  3. from myutil import *
  4. from binascii import unhexlify as unhex
  5. from ctypes import *
  6. dll = cdll.LoadLibrary('mydll.dll')
  7. print 'begin load mydll..'
  8. HOST, PORT = "192.168.51.28", 5800
  9. sd ="1234567812345678"
  10. # Create a socket (SOCK_STREAM means a TCP socket)
  11. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  12. try:
  13. # Connect to server and send data
  14. sock.connect((HOST, int(PORT))
  15. print "Sent1 OK:"
  16. print sd
  17. # Receive data from the server and shut down
  18. received = sock.recv(1024)
  19. print "Received:"
  20. print_hex(received)
  21. print 'received len is 0x%02x' %(len(received))
  22. print 'received data analysis...'
  23. re1=received[0:4]
  24. print_hex(re1)
  25. re1=received[4:6]
  26. print_hex(re1)
  27. re1=received[6:10]
  28. print_hex(re1)
  29. re1=received[10:16]
  30. print_hex(re1)
  31. #pack2 send
  32. sock.send(sd2.decode('hex'))
  33. print "Sent2 OK:"
  34. print sd2
  35. # Receive data from the server and shut down
  36. received1 = sock.recv(1024)
  37. print "Received1:"
  38. print_hex(received1)
  39. print 'received1 len is 0x%02x' %(len(received1))
  40. finally:
  41. sock.close()
  42. s=raw_input('press any key to continue...')

报文拼接与加解密测试

  1. # -*- coding: gb2312 -*-
  2. import socket
  3. from myutil import *
  4. from binascii import unhexlify as unhex
  5. from ctypes import *
  6. dll = cdll.LoadLibrary('mydll.dll')
  7. print 'begin load mydll..'
  8. #key
  9. key='\xF1\xE2\xD3\xC4\xF1\xE2\xD3\xC4'
  10. #output MAC
  11. mac='\x00'*8
  12. data='\x00'*8
  13. pkey=c_char_p()
  14. pdata=c_char_p()
  15. pmac=c_char_p()
  16. pkey.value=key
  17. pdata.value=data
  18. pmac.value=mac
  19. #pack1
  20. class pack:
  21. pass
  22. pk=pack()
  23. pk.len='00000032'
  24. pk.ID='0001'
  25. pk.slnum='00000004'
  26. pk.poscode='123456781234'
  27. pk.rand='1122334455667788'
  28. pk.psam='313233343536'
  29. pk.kind='0000'
  30. pk.ver='000001'
  31. pk.time='20140805135601'
  32. pk.mac='06cc571e6d96e12d'
  33. data=unhex(pk.len+pk.ID+pk.slnum+pk.poscode+pk.rand+pk.psam+pk.kind+pk.ver+pk.time)
  34. #print_hex(data)
  35. pdata.value=data
  36. #cacl MAC
  37. dll.CurCalc_DES_MAC64(805306481,pkey,0,pdata,42,pmac)
  38. stro= pmac.value
  39. strtemp=''
  40. for c in stro:
  41. strtemp+="{0:02x}".format(ord(c))
  42. #print strtemp
  43. pk.mac=strtemp
  44. #data to send
  45. sd=pk.len+pk.ID+pk.slnum+pk.poscode+pk.rand+pk.psam+pk.kind+pk.ver+pk.time+pk.mac
  46. print 'send1 len is 0x%02x' %(len(sd)/2)
  47. print sd
  48. #pack2
  49. class pack2:
  50. pass
  51. pk2=pack2()
  52. pk2.len='0000006E'
  53. pk2.ID='0012'
  54. pk2.slnum='00000005'
  55. pk2.fatCode='00'
  56. pk2.cardASN='0000000000000000'
  57. pk2.cardType='00'
  58. pk2.userNO= '0000000000000000'
  59. pk2.fileName1='00000000000000000000000000000015'
  60. pk2.dataLen1='00'
  61. pk2.dataArea1='00000000000000319999990800FB2014080620240806FFFFFFFFFFFFFFFFFFFF'
  62. pk2.fileName2='00000000000000000000000000000016'
  63. pk2.dataLen2='00'
  64. pk2.dataArea2='000003E800FFFF16'
  65. pk2.mac='06cc571e6d96e12d'
  66. data2=unhex(pk2.len+pk2.ID+pk2.slnum+pk2.fatCode+pk2.cardASN+pk2.cardType+pk2.userNO+pk2.fileName1+pk2.dataLen1+pk2.dataArea1+pk2.fileName2+pk2.dataLen2+pk2.dataArea2)
  67. pdata.value=data2
  68. #cacl MAC
  69. dll.CurCalc_DES_MAC64(805306481,pkey,0,pdata,102,pmac)
  70. stro= pmac.value
  71. strtemp=''
  72. for c in stro:
  73. strtemp+="{0:02x}".format(ord(c))
  74. #print strtemp
  75. pk2.mac=strtemp
  76. #data to send
  77. sd2=pk2.len+pk2.ID+pk2.slnum+pk2.fatCode+pk2.cardASN+pk2.cardType+pk2.userNO+pk2.fileName1+pk2.dataLen1+pk2.dataArea1+pk2.fileName2+pk2.dataLen2+pk2.dataArea2+pk2.mac
  78. print 'send2 len is 0x%02x' %(len(sd2)/2)
  79. print sd2
  80. #PORT="192.168.60.37"
  81. #PORT="localhost"
  82. HOST, PORT = "192.168.51.28", 5800
  83. # Create a socket (SOCK_STREAM means a TCP socket)
  84. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  85. try:
  86. # Connect to server and send data
  87. sock.connect((HOST, int(PORT))
  88. #data= "123456789"
  89. #s = struct.pack('bbb',1,2,3)
  90. sock.send(sd.decode('hex'))
  91. print "Sent1 OK:"
  92. print sd
  93. # Receive data from the server and shut down
  94. received = sock.recv(1024)
  95. print "Received:"
  96. print_hex(received)
  97. print 'received len is 0x%02x' %(len(received))
  98. print 'received data analysis...'
  99. re1=received[0:4]
  100. print_hex(re1)
  101. re1=received[4:6]
  102. print_hex(re1)
  103. re1=received[6:10]
  104. print_hex(re1)
  105. re1=received[10:16]
  106. print_hex(re1)
  107. #pack2 send
  108. sock.send(sd2.decode('hex'))
  109. print "Sent2 OK:"
  110. print sd2
  111. # Receive data from the server and shut down
  112. received1 = sock.recv(1024)
  113. print "Received1:"
  114. print_hex(received1)
  115. print 'received1 len is 0x%02x' %(len(received1))
  116. finally:
  117. sock.close()
  118. s=raw_input('press any key to continue...')

二进制文件解析工具

  1. # -*- coding: utf-8 -*-
  2. from myutil import *
  3. from binascii import unhexlify as unhex
  4. import os
  5. path=os.getcwd()
  6. path+='\\rec04.bin'
  7. #print path
  8. print "begin ans......"
  9. f1=open(path,'rb')
  10. for i in range(1,35):
  11. s=f1.read(280)
  12. print "data:",i
  13. print_hex(s)
  14. print 'read data is:'
  15. print_hex(s)
  16. recstatadd = 187
  17. print "终端编号:"
  18. print_hex(s[recstatadd:recstatadd+10])
  19. print "卡号长度:"
  20. print_hex(s[10])
  21. print "卡号: "
  22. print_hex(s[11:11+10])
  23. print "持卡序号1+所属地城市代码2+交易地城市代码2"
  24. print_hex(s[recstatadd+22:recstatadd+22+5])
  25. print "应用交易计数器"
  26. print_hex(s[92:92+2])
  27. print "交易前余额4,交易金额3"
  28. print_hex(s[recstatadd+29:recstatadd+29+7])
  29. print "交易日期:"
  30. print_hex(s[99:99+3])
  31. print "交易时间:"
  32. print_hex(s[44:44+3])
  33. print "终端编号"
  34. print_hex(s[21:21+8])
  35. print "商户编号"
  36. print_hex(s[21+8:21+8+15])
  37. print "批次号"
  38. print_hex(s[5:5+3])
  39. print "应用密文"
  40. print_hex(s[47:47+8])
  41. print "授权金额"
  42. print_hex(s[103:103+6])
  43. print "其他金额"
  44. print_hex(s[115:115+6])
  45. print "终端验证结果"
  46. print_hex(s[94:5+94])
  47. print "应用交易计数器"
  48. print_hex(s[92:92+4])
  49. print "卡片验证结果"
  50. print_hex(s[56:56+32])
  51. print "卡片序列号:"
  52. print_hex(s[131])
  53. f1.close()

抓取动漫图片

  1. # -*- coding:utf8 -*-
  2. # 2013.12.36 19:41
  3. # 抓取dbmei.com的图片。
  4. from bs4 import BeautifulSoup
  5. import os, sys, urllib2,time,random
  6. # 创建文件夹
  7. path = os.getcwd() # 获取此脚本所在目录
  8. new_path = os.path.join(path,u'暴走漫画')
  9. if not os.path.isdir(new_path):
  10. os.mkdir(new_path)
  11. def page_loop(page=1):
  12. url = 'http://baozoumanhua.com/all/hot/page/%s?sv=1389537379' % page
  13. content = urllib2.urlopen(url)
  14. soup = BeautifulSoup(content)
  15. my_girl = soup.find_all('div',class_='img-wrap')
  16. for girl in my_girl:
  17. jokes = girl.find('img')
  18. link = jokes.get('src')
  19. flink = link
  20. print flink
  21. content2 = urllib2.urlopen(flink).read()
  22. #with open(u'暴走漫画'+'/'+time.strftime('%H-%M-%S')+random.choice('qwertyuiopasdfghjklzxcvbnm')+flink[-5:],'wb') as code: #在OSC上现学的
  23. with open(u'暴走漫画'+'/'+flink[-11:],'wb') as code:
  24. code.write(content2)
  25. page = int(page) + 1
  26. print u'开始抓取下一页'
  27. print 'the %s page' % page
  28. page_loop(page)
  29. page_loop()

抓取网站模板

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # by yangyongzhen
  4. # 2016-12-06
  5. from bs4 import BeautifulSoup
  6. import urllib,urllib2,os,time
  7. import re
  8. rootpath = os.getcwd()+u'/抓取的模板/'
  9. def makedir(path):
  10. if not os.path.isdir(path):
  11. os.makedirs(path)
  12. #创建抓取的根目录
  13. makedir(rootpath)
  14. #显示下载进度
  15. def Schedule(a,b,c):
  16. '''''
  17. a:已经下载的数据块
  18. b:数据块的大小
  19. c:远程文件的大小
  20. '''
  21. per = 100.0 * a * b / c
  22. if per > 100 :
  23. per = 100
  24. print '%.2f%%' % per
  25. def grabHref(url,listhref,localfile):
  26. html = urllib2.urlopen(url).read()
  27. html = unicode(html,'gb2312','ignore').encode('utf-8','ignore')
  28. content = BeautifulSoup(html).findAll('link')
  29. myfile = open(localfile,'w')
  30. pat = re.compile(r'href="([^"]*)"')
  31. pat2 = re.compile(r'http')
  32. for item in content:
  33. h = pat.search(str(item))
  34. href = h.group(1)
  35. if pat2.search(href):
  36. ans = href
  37. else:
  38. ans = url+href
  39. listhref.append(ans)
  40. myfile.write(ans)
  41. myfile.write('\r\n')
  42. print ans
  43. content = BeautifulSoup(html).findAll('script')
  44. pat = re.compile(r'src="([^"]*)"')
  45. pat2 = re.compile(r'http')
  46. for item in content:
  47. h = pat.search(str(item))
  48. if h:
  49. href = h.group(1)
  50. if pat2.search(href):
  51. ans = href
  52. else:
  53. ans = url+href
  54. listhref.append(ans)
  55. myfile.write(ans)
  56. myfile.write('\r\n')
  57. print ans
  58. content = BeautifulSoup(html).findAll('a')
  59. pat = re.compile(r'href="([^"]*)"')
  60. pat2 = re.compile(r'http')
  61. for item in content:
  62. h = pat.search(str(item))
  63. if h:
  64. href = h.group(1)
  65. if pat2.search(href):
  66. ans = href
  67. else:
  68. ans = url+href
  69. listhref.append(ans)
  70. myfile.write(ans)
  71. myfile.write('\r\n')
  72. print ans
  73. myfile.close()
  74. def main():
  75. url = "http://192.168.72.140/qdkj/" #采集网页的地址
  76. listhref =[] #链接地址
  77. localfile = 'ahref.txt' #保存链接地址为本地文件,文件名
  78. grabHref(url,listhref,localfile)
  79. listhref = list(set(listhref)) #去除链接中的重复地址
  80. curpath = rootpath
  81. start = time.clock()
  82. for item in listhref:
  83. curpath = rootpath
  84. name = item.split('/')[-1]
  85. fdir = item.split('/')[3:-1]
  86. for i in fdir:
  87. curpath += i
  88. curpath += '/'
  89. print curpath
  90. makedir(curpath)
  91. local = curpath+name
  92. urllib.urlretrieve(item, local,Schedule) # 远程保存函数
  93. end = time.clock()
  94. print u'模板抓取完成!'
  95. print u'一共用时:',end-start,u'秒'
  96. if __name__=="__main__":
  97. main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/83072
推荐阅读
相关标签
  

闽ICP备14008679号