# -*- coding: utf-8 -*-
# tcp mapping
import sys
import socket
import logging
import threading
# 端口映射配置信息
CFG_REMOTE_IP = '127.0.0.1'
CFG_REMOTE_PORT = 23
CFG_LOCAL_IP = '0.0.0.0'
CFG_LOCAL_PORT = 1023
# 接收数据缓存大小
PKT_BUFF_SIZE = 2048
logger = logging.getLogger("Proxy Logging")
formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(lineno)-4d %(message)s',
'%Y %b %d %a %H:%M:%S', )
stream_handler = logging.StreamHandler(sys.stderr)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.setLevel(logging.DEBUG)
# 单向流数据传递
def tcp_mapping_worker(conn_receiver, conn_sender):
while True:
try:
data = conn_receiver.recv(PKT_BUFF_SIZE)
except Exception:
logger.debug('Connection closed.')
break
if not data:
logger.info('No more data is received.')
break
try:
conn_sender.sendall(data)
except Exception:
logger.error('Failed sending data.')
break
# logger.info('Mapping data > %s ' % repr(data))
logger.info(
'Mapping > %s -> %s > %d bytes.' % (conn_receiver.getpeername(), conn_sender.getpeername(), len(data)))
conn_receiver.close()
conn_sender.close()
return
# 端口映射请求处理
def tcp_mapping_request(local_conn, remote_ip, remote_port):
remote_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
remote_conn.connect((remote_ip, remote_port))
except Exception:
local_conn.close()
logger.error('Unable to connect to the remote server.')
return
threading.Thread(target=tcp_mapping_worker, args=(local_conn, remote_conn)).start()
threading.Thread(target=tcp_mapping_worker, args=(remote_conn, local_conn)).start()
return
# 端口映射函数
def tcp_mapping(remote_ip, remote_port, local_ip, local_port):
local_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local_server.bind((local_ip, local_port))
local_server.listen(5)
logger.debug('Starting mapping service on ' + local_ip + ':' + str(local_port) + ' ...')
while True:
try:
(local_conn, local_addr) = local_server.accept()
except KeyboardInterrupt as Exception:
local_server.close()
logger.debug('Stop mapping service.')
break
threading.Thread(target=tcp_mapping_request, args=(local_conn, remote_ip, remote_port)).start()
logger.debug('Receive mapping request from %s:%d.' % local_addr)
return
# 主函数
if __name__ == '__main__':
tcp_mapping(CFG_REMOTE_IP, CFG_REMOTE_PORT, CFG_LOCAL_IP, CFG_LOCAL_PORT)
标签: python
设置ubuntu中默认Python的版本
ubuntu 18.04默认的Python版本是2的,要改成3的。
可以变更快捷方式,也可以增加alias,还可以用下面的方式去更改:
update-alternatives --install /usr/bin/python python /usr/bin/python3 1
pip也一起修改一下:
update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
pip使用国内源
1 国内源
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:https://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:http://pypi.douban.com/simple/
需要注意的是新版ubuntu要求使用https源。
2 修改配置文件
Linux: 修改 ~/.pip/pip.conf (没有就创建一个文件夹及文件。文件夹要加“.”,表示是隐藏文件夹) MacOS: 修改 ~/.pip/pip.conf (没有就创建一个文件夹及文件。文件夹要加“.”,表示是隐藏文件夹) windows:,直接在user目录中创建一个pip目录,再新建文件pip.ini。例如:C:\Users\comet\pip\pip.ini
内容如下:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
DHT22温湿度传感器的使用
使用python读取dht22温湿度传感器的值。
import sys import Adafruit_DHT import requests import json url = 'https://www.3gcomet.com/iot/iot_receive.php' sensor = Adafruit_DHT.DHT22 pin = 4 humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: temp = '{:.1f}'.format(temperature) humi = '{:.1f}'.format(humidity) payload = {"ac":'iotofict',"loc":'CloudDC',"tem":temp,"hum":humi} response = requests.post(url=url,data=payload) print(response.text) #print('Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity)) else: print('Failed to get reading. Try again!') sys.exit(1)
python读取串口信息
python读取配置文件中串口的名称,然后打开串口接受读卡器信息,再提交到某个网页上。
reader.ini:
[Default]
port=/dev/ttyUSB0
serial-test.py:
#!/usr/bin/python import serial import urllib2 import ConfigParser def hexShow(argv): result = '' hLen = len(argv) for i in xrange(hLen): hvol = ord(argv[i]) hhex = '%02x'%hvol result += hhex # print 'hexShow:',result return result config = ConfigParser.ConfigParser() config.readfp(open('reader.ini')) sPort = config.get("Default","port") ser = serial.Serial(sPort,9600) while ser.isOpen(): sdata = ser.read(5) cardid = hexShow(sdata) # print cardid cidurl = "http://127.0.0.1/cid.php?cid="+cardid res_data = urllib2.urlopen(cidurl) res = res_data.read() print res