socks5协议(客户端)

1. PHP 版本

function main() {
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    $data = socks5Client($socket);
    socket_close($socket);
    var_dump($data);
}

function socks5Client($socket) {
    $buf = '';
    socket_connect($socket, '127.0.0.1', 1080);
    $send = "\x05\x01\x00";
    socket_write($socket, $send, strlen($send));
    socket_recv($socket, $buf, 2, MSG_WAITALL);
    if ($buf !== "\x05\x00") {
        return '';
    }

    $send = "\x05\x01\x00\x01" . ip2hex('1.1.1.1') . port2hex(80);
    socket_write($socket, $send, strlen($send));
    socket_recv($socket, $buf, 10, MSG_WAITALL);
    if ($buf !== "\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") {
        return '';
    }

    $send = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n";
    socket_write($socket, $send, strlen($send));
    socket_recv($socket, $buf, 4096, MSG_WAITALL);

    return $buf;
}

function ip2hex($ip) {
    $ip = explode('.', $ip);
    $hex = '';
    foreach($ip as $v) {
        $hex .= pack('H2', dechex($v));
    }
    return $hex;
}

function port2hex($n) {
    $h = floor($n / 256);
    $l = $n % 256;
    return pack('H2', dechex($h)) . pack('H2', dechex($l));
}

main();

2. Python3 版本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 9000))

# client -> server      初始化
# ver(1byte)            client版本,默认 \x05
# nmethods(1byte)       认证方式个数,默认 \x01
# methods(1-255byte)    认证方式种类,默认 \x00 不需要认证
client.send(b'\x05\x01\x00')

# server -> client      服务器回复
# ver(1byte)            client版本,默认 \x05
# method(1byte)         认证方式,默认 \x00 不需要认证
data = client.recv(2)
# b'\x05\x00'

# client -> server      客户端发送代理请求
# ver(1byte)            client版本,默认 \x05
# cmd(1byte)            代理方式 \x01(CONNECT) \x02(BIND) \x03(UDP)
# rsv(1byte)            保留字段,默认 \x00
# atype(1byte)          请求地址类型 \x01(IPV4 4byte) \x03(域名 1byte长度加域名) \x04(IPV6 16byte)
# addr()                目标地址
# port(2byte)           目标端口
client.send(b'\x05\x01\x00\x01\x08\x08\x08\x08\x00\x50')

# server -> client      服务器回复
# ver(1byte)            client版本,默认 \x05
# rep(1byte)            应答字段 0x00表示成功 0x01普通client服务器连接失败 0x02现有规则不允许连接 0x03网络不可达 0x04主机不可达 0x05连接被拒 0x06 TTL超时 0x07不支持的命令 0x08不支持的地址类型 0x09 - 0xFF未定义
# rsv(1byte)            保留字段,默认 \x00
# atype(1byte)          请求地址类型 \x01(IPV4 4byte) \x03(域名 1byte长度加域名) \x04(IPV6 16byte)
# addr()                目标地址,默认 \x00\x00\x00\x00
# port(2byte)           目标端口,默认 \x00\x00
data = client.recv(120)
# b'\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00'

# client -> server      客户端发送代理请求
client.send(b'GET / HTTP/1.1\r\nHost: www.mogublog.net\r\nConnection: close\r\n\r\n')

# server -> client      服务器回复
data = client.recv(10240)

client.close()

print(data)

Python配置虚拟环境

安装 virtualenv


pip install virtualenv

创建虚拟环境


mkdir myproject
cd myproject/
virtualenv --no-site-packages venv
source venv/bin/activate
deactivate

Python获取服务器网速

实时获取服务器网速的脚本

CentOS6版本


#!/usr/bin/python

import os, re, time

def get_net():
    return re.search('eth0: (\d+)(\d+\s+){8}(\d+)', os.popen('cat /proc/net/dev').read())

first = get_net()

time.sleep(1)

second = get_net()

recive_speed = (int(second.group(1)) - int(first.group(1))) / 1024
send_speed = (int(second.group(3)) - int(first.group(3))) / 1024

recive_company = 'K/s'
send_company = 'K/s'

if send_speed > 1024:
    send_speed = send_speed / 1024
    send_company = 'M/s'

print('Recive : ' + str(recive_speed) + recive_company)
print('Send : ' + str(send_speed) + send_company)

CentOS7版本


#!/usr/bin/python

import os, re, time

def get_net():
    return re.findall('\d+', os.popen('cat /proc/net/dev | grep ens33').read())

first = get_net()
time.sleep(1)
second = get_net()

recive_speed = (int(second[1]) - int(first[1])) / 1024
send_speed = (int(second[9]) - int(first[9])) / 1024

recive_company = 'K/s'
send_company = 'K/s'

if send_speed > 1024:
    send_speed = send_speed / 1024
    send_company = 'M/s'

if recive_speed > 1024:
    recive_speed = recive_speed / 1024
    recive_company = 'M/s'

print('Recive : ' + str(recive_speed) + recive_company)
print('Send : ' + str(send_speed) + send_company)

使用办法:
将此脚本保存到 /usr/local/bin/ 目录下,命名为 speed
添加可执行权限:chmod +x speed
watch -n 1 speed

Python创建守护进程

守护进程


import os, sys, time

def daemon():
    if os.fork() != 0:
        sys.exit(0)
    os.setsid()
    if os.fork() != 0:
        sys.exit(0)
    os.chdir('/tmp')
    os.umask(0)

if __name__ == "__main__":
    daemon()

Python使用MySQL

Python使用数据库


# pip3 install mysql-connector

import mysql.connector

conn = mysql.connector.connect(host='192.168.1.10', user='mogu', password='123456', database='mogu')

cursor = conn.cursor()

# 创建表
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')

# 插入一行记录
cursor.execute('insert into user (id, name) values (%s, %s)', ('1', 'Michael'))

print('rowcount =', cursor.rowcount)

conn.commit()

cursor.close()

# 运行查询:
cursor = conn.cursor()

cursor.execute('select * from user where id = %s', ('1',))

values = cursor.fetchall()

print(values)

cursor.close()

# 关闭数据库连接
conn.close()


Python实现HTTP服务器

Python实现简单HTTP服务器


import socket

response  = b'HTTP/1.0 200 OK\r\n\r\nHello, world!'

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 80))
server.listen(20)

try:
	while True:
		client, address = server.accept()
		request = b''
		while b'\r\n\r\n' not in request:
			request += client.recv(1024)
			if len(request) > 4000:
				break
		print('-'*40 + '\n' + request.decode()[:-2])
		client.send(response)
		client.close()
finally:
	server.close()

带守护进程:


import os, sys, SocketServer

def daemon():
    if os.fork() != 0:
        sys.exit(0)
    os.setsid()
    if os.fork() != 0:
        sys.exit(0)
    os.chdir('/tmp')
    os.umask(0)

class TCPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        self.data = self.request.recv(1024)
        respone = b'HTTP/1.1 200 OK\r\n\r\nOK'
        self.request.send(respone)

if __name__ == "__main__":
    daemon()
    SocketServer.ThreadingTCPServer.allow_reuse_address = True
    server = SocketServer.ThreadingTCPServer(('0.0.0.0', 8000), TCPHandler)
    try:
        server.serve_forever()
    except:
        pass
    server.server_close()

Python破解zip文件密码

Python破解zip文件密码


import zipfile

with zipfile.ZipFile('moon.zip', 'r') as myzip:
	for i in range(0, 10):
		for j in range(0, 1000):
			n = str( i * 1000 + j )
			try:
				myzip.extract('moon/1.jpg', '', n.encode())
				print(n)
			except:
				pass

Python简单字符串加密

加密



import base64

def encode(str):
	data = base64.b64encode(str)
	encode = []
	for i in range(len(data)):
		encode.append( '%d' % data[i] )
	encode = '-'.join(encode)
	return encode

def decode(str):
	encode = str.split('-')
	decode = []
	for i in encode:
		decode.append( chr( int(i) ) )
	decode = ''.join(decode)
	return base64.b64decode(decode.encode())

Python实现HTTPS服务器

Python2实现HTTPS服务器



# openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes

import ssl, BaseHTTPServer, SimpleHTTPServer

class MyHTTPSHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def handle(self):
        # self.request is the TCP socket
        self.data = self.request.recv(2048)
        self.request.sendall(self.data)

httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', 443), MyHTTPSHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='server.pem', server_side=True)
httpd.serve_forever()

Socket实例

Socket实例


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

host = '127.0.0.1'
port = 80

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')

buffer = []

while True:
    d = s.recv(1024)
    if not d:
        break
    buffer.append(d)

data = b''.join(buffer)

s.close()

print(data)

服务器端


# Python 3

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):

	def handle(self):
		self.data = self.request.recv(1024)
		respone = b'HTTP/1.1 200 OK\r\n\r\nOK'
		self.request.send(respone)

if __name__ == "__main__":
	server = socketserver.ThreadingTCPServer(('0.0.0.0', 8000), MyTCPHandler)
	try:
		server.serve_forever()
	except KeyboardInterrupt:
		pass
	server.server_close()
	print('Bye')