python proxy

[python]
#!/usr/bin/python
# Filename s5.py
# Python Dynamic Socks5 Proxy
# Usage: python s5.py 1080
# Background Run: nohup python s5.py 1080 &
# Email: ringzero@557.im

import socket, sys, select, SocketServer, struct, time

class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass
class Socks5Server(SocketServer.StreamRequestHandler):
def handle_tcp(self, sock, remote):
fdset = [sock, remote]
while True:
r, w, e = select.select(fdset, [], [])
if sock in r:
if remote.send(sock.recv(4096)) <= 0: break
if remote in r:
if sock.send(remote.recv(4096)) <= 0: break
def handle(self):
try:
pass # print ‘from ‘, self.client_address nothing to do.
sock = self.connection
# 1. Version
sock.recv(262)
sock.send("x05x00");
# 2. Request
data = self.rfile.read(4)
mode = ord(data[1])
addrtype = ord(data[3])
if addrtype == 1: # IPv4
addr = socket.inet_ntoa(self.rfile.read(4))
elif addrtype == 3: # Domain name
addr = self.rfile.read(ord(sock.recv(1)[0]))
port = struct.unpack(‘>H’, self.rfile.read(2))
reply = "x05x00x00x01"
try:
if mode == 1: # 1. Tcp connect
remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
remote.connect((addr, port[0]))
pass # print ‘To’, addr, port[0] nothing do to.
else:
reply = "x05x07x00x01" # Command not supported
local = remote.getsockname()
reply += socket.inet_aton(local[0]) + struct.pack(">H", local[1])
except socket.error:
# Connection refused
reply = ‘x05x05x00x01x00x00x00x00x00x00’
sock.send(reply)
# 3. Transfering
if reply[1] == ‘x00’: # Success
if mode == 1: # 1. Tcp connect
self.handle_tcp(sock, remote)
except socket.error:
pass #print ‘error’ nothing to do .
except IndexError:
pass
def main():
filename = sys.argv[0];
if len(sys.argv)<2:
print ‘usage: ‘ + filename + ‘ port’
sys.exit()
socks_port = int(sys.argv[1]);
server = ThreadingTCPServer((”, socks_port), Socks5Server)
print ‘bind port: %d’ % socks_port + ‘ ok!’
server.serve_forever()
if __name__ == ‘__main__’:
main()
[/python]
[python]
# encoding=utf-8
# Usage: python filename.py
# Background Run: nohup python filename.py 2079 &
# http://yaonie.org/

import socket, thread, select, sys

BUFLEN = 8192
HTTPVER = ‘HTTP/1.1′

class ConnectionHandler:
def __init__(self, connection, address, timeout):
self.client = connection
self.client_buffer = ”
self.timeout = timeout
self.method, self.path, self.protocol = self.get_base_header()
if self.method==’CONNECT’:
self.method_CONNECT()
elif self.method in (‘OPTIONS’, ‘GET’, ‘HEAD’, ‘POST’,):# ‘PUT’,’DELETE’, ‘TRACE’):
self.method_others()
self.client.close()
self.target.close()

def get_base_header(self):
while 1:
self.client_buffer += self.client.recv(BUFLEN)
end = self.client_buffer.find(‘n’)
if end!=-1:
break
print ‘%s’%self.client_buffer[:end]#debug
data = (self.client_buffer[:end+1]).split()
self.client_buffer = self.client_buffer[end+1:]
return data

def method_CONNECT(self):
self._connect_target(self.path)
self.client.send(HTTPVER+’ 200 Connection establishednProxy-agent: %snn’) %
r"Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)’)"
self.client_buffer = ”
self._read_write()

def method_others(self):
self.path = self.path[7:]
i = self.path.find(‘/’)
host = self.path[:i]
path = self.path[i:]
self._connect_target(host)
self.target.send(‘%s %s %sn’%(self.method, path, self.protocol)+self.client_buffer)
self.client_buffer = ”
self._read_write()

def _connect_target(self, host):
i = host.find(‘:’)
if i!=-1:
port = int(host[i+1:])
host = host[:i]
else:
port = 80
(soc_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
self.target = socket.socket(soc_family)
self.target.connect(address)

def _read_write(self):
time_out_max = self.timeout/3
socs = [self.client, self.target]
count = 0
while 1:
count += 1
(recv, _, error) = select.select(socs, [], socs, 3)
if error:
break
if recv:
for in_ in recv:
data = in_.recv(BUFLEN)
if in_ is self.client:
out = self.target
else:
out = self.client
if data:
out.send(data)
count = 0
if count == time_out_max:
break

def start_server(host, port, IPv6=False, timeout=60, handler=ConnectionHandler):
if IPv6==True:
soc_type=socket.AF_INET6
else:
soc_type=socket.AF_INET
soc = socket.socket(soc_type)
soc.bind((host, port))
print "Serving on %s:%d."%(host, port)#debug
soc.listen(0)
while 1:
thread.start_new_thread(handler, soc.accept()+(timeout,))

if __name__ == ‘__main__’:
if len(sys.argv) != 2:
print ‘usage: python %s port’ % sys.argv[0]
sys.exit()
try:
port = int(sys.argv[1])
except:
print ‘usage: python %s port’ % sys.argv[0]
sys.exit()

start_server(‘10.1.14.2’,port)
[/python]

Python的静态方法和类成员方法

Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还是有区别的:

  1. 静态方法无需传入self参数,类成员方法需传入代表本类的cls参数;
  2. 从第1条,静态方法是无法访问实例变量的,而类成员方法也同样无法访问实例变量,但可以访问类变量;
  3. 静态方法有点像函数工具库的作用,而类成员方法则更接近类似Java面向对象概念中的静态方法;

[python]
class MyClass:
val1 = ‘Value 1’
def __init__(self):
self.val2 = ‘Value 2’

@staticmethod
def staticmd():
print ‘静态方法,无法访问val1和val2’

@classmethod
def classmd(cls):
print ‘类方法,类:’ + str(cls) + ‘,val1:’ + cls.val1 + ‘,无法访问val2的值’
[/python]

 

结论

如果上述执行过程太复杂,记住以下两点就好了:

静态方法:无法访问类属性、实例属性,相当于一个相对独立的方法,跟类其实没什么关系,换个角度来讲,其实就是放在一个类的作用域里的函数而已。

类成员方法:可以访问类属性,无法访问实例属性。上述的变量val1,在类里是类变量,在实例中又是实例变量,所以容易混淆。

微信/邮箱,远程控制关机

应用场景是这样的:

有人打开你的电脑时,电脑联网后,自动给特定邮箱发一封邮件,然后等待回复,如果在这个小时内收到一封有“shut down ”关键词的邮件,电脑自动关机

程序设计的关键点:

1.获取最新邮件,判断邮件收到日期和是否含有关机关键词2.开机自启动

开机自启动可参考http://lvxinwei.sinaapp.com/1066.html 这篇文章介绍的

收发邮件可参考http://lvxinwei.sinaapp.com/1069.html

下面放源代码:

[python]
import win32serviceutil
import win32service
import win32event
import smtplib
import poplib,email,time,os
class test1(win32serviceutil.ServiceFramework):
_svc_name_ = "test_python"
_svc_display_name_ = "test_python"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.running = True
self.is_sent=0
def SvcStop(self):
self.running = False
def SvcDoRun(self):
while self.running:
time.sleep(1)
if self.is_sent==0:
try:
handle = smtplib.SMTP(‘smtp.163.com’, 25)
handle.login(‘xx@163.com’,’xx_pwd’)
msg = "To:yy@qq.comrnFrom:xx@163.comrnSubject:start pc rnrn —-rn"
handle.sendmail(‘xx@163.com’,’yy@qq.com’, msg)
handle.close()
self.is_sent=1
except Exception,e:
print e
self.is_sent=0
if self.is_sent==1:
try:
p=poplib.POP3(‘pop.qq.com’)
p.user(‘xx’)
p.pass_(‘xx_pwd’)
ret = p.stat()
except poplib.error_proto,e:
print "Login failed:",e
list=p.list()[1]
list.reverse()
number,octets =list[0].split(‘ ‘)
lines=p.retr(number)[1]
has_order=[None,None]
for piece in lines:
if "shut down" in piece:
has_order[0]=1
continue
if time.strftime(‘%a, %d %b %Y %H’,time.localtime(time.time())) in piece:
has_order[1]=1
continue
if has_order[0]==1 and has_order[1]==1:
os.system(‘shutdown -f -s -t 10 -c closing…’)
if __name__==’__main__’:
win32serviceutil.HandleCommandLine(test1)
[/python]

Python收发邮件

问题是,邮件正文可能是base64编码也可能是gb2312编码,如何始终获取正文呢
[python]
import poplib,email
try:
p=poplib.POP3(‘pop.qq.com’)
p.user(‘xx’)
p.pass_(‘xx’)
ret = p.stat()
except poplib.error_proto,e:
print "Login failed:",e
list=p.list()[1]
list.reverse()
for item in list:
number,octets = item.split(‘ ‘)
lines=p.retr(number)[1]
for piece in lines:
print piece
[/python]
发邮件:
[python]
import smtplib
try:
handle = smtplib.SMTP(‘smtp.163.com’, 25)
handle.login(‘xx@163.com’,’xx’)
msg = "To:to@qq.comrnFrom:xx@163.comrnSubject:hi rnrnhellorn"
handle.sendmail(‘xx@163.com’,’to@qq.com’, msg)
handle.close()
except Exception,e:
print e
[/python]

python 脚本作为Windows服务启动

相关包:http://sourceforge.net/projects/pywin32/
[python]
import win32serviceutil
import win32service
import win32event
import time
class test1(win32serviceutil.ServiceFramework):
_svc_name_ = "test_python"
_svc_display_name_ = "test_python"
def __init__(self, args):
win32serviceutil.ServiceFramework.__init__(self, args)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
#在这里写入启动后的操作
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
#在这里写入关闭服务前的操作
win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
if __name__==’__main__’:
win32serviceutil.HandleCommandLine(test1)
[/python]