Press "Enter" to skip to content

Tag: python

The easiest way to build a http/ftp server with Python

Build a HTTP Server

# Python2
python -m SimpleHTTPServer PORT

# Python 3
python -m http.server PORT
python -m http.server PORT --bind example.com

Build a FTP Server

pip install pyftpdlib

python -m pyftpdlib -p 21    # notice: it's ftpd, not ftp

# if you want a username and password
python -m pyftpdlib -u USERNAME -P PASSWORD

A powershell script could run in Windows

place a file named “ftp.ps1” with the following content:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Set-Location -Path D:\Download
Start-Process -NoNewWindow python --version
python -m pyftpdlib -p 21 -u USERNAME -P PASSWORD
Read-Host -Prompt "Press Enter to exit"

and then run with Powershell

Advanced Usage

from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer


authorizer = DummyAuthorizer()
authorizer.add_user('python', '123456', 'F:\\Working~Study', perm='elradfmwM')
handler = FTPHandler
handler.authorizer = authorizer


server = FTPServer(('0.0.0.0', 8888), handler)
server.serve_forever()

Reference
https://blog.51cto.com/phyger/5182139

Leave a Comment

pproxy简单介绍

pproxy是一个简单的小工具, 顾名思议它是一个临时的代理小工具. 下面介绍其使用方法.

安装

服务端和客户端都可以使用如下方式进行安装

pip3 install pproxy

服务端运行

pproxy -l ss://aes-128-gcm:MyPassword@:3389

客户端运行

客户端简单运行

pproxy -r ss://aes-128-gcm:MyPassword@ServerIP:3389 -vv

然后客户端会提示”Serving on :8080 by http,socks4,socks5″.

客户端建立http代理

sudo pproxy -l http://127.0.0.1:8080 -r ss://aes-128-gcm:MyPassword@ServerIP:3389 -vv

然后客户端会提示”Serving on 127.0.0.1:8080 by http”.

客户端建立DNS tunnel

由于ss(AEAD)协议不支持udp, 因此我们只能换用socks5或者tunnel (raw socket)协议来支持udp.

服务端:
pproxy -ul socks5://0.0.0.0:3389

客户端:
sudo pproxy -ul tunnel{8.8.8.8}://127.0.0.1:53 -ur socks5://ServerIP::3389 -vv

然后客户端会提示”Serving on UDP 127.0.0.1:53 by tunnel”, 可以在客户端使用dig @127.0.0.1 dropbox.com检验tunnel效果.

1 Comment

Python农历转换

在Python中进行公历转换农历, 是一件很简单的事儿.

>>> import datetime
>>> from zhdate import ZhDate

# 农历转公历
>>> date = ZhDate(2022,4,5)
>>> print(date)
农历2022年4月5日

>>> date.to_datetime().date().year
2022
>>> date.to_datetime().date().month
5
>>> date.to_datetime().date().day
5
Leave a Comment

使用python判断IP段可用IP及数量

使用python判断IP段可用IP及数量, 很简单.几个命令就可以(本文基于python3).

>>> import ipaddress
>>> bool(ipaddress.ip_address('172.21.97.12') in ipaddress.ip_network('172.16.0.0/12'))
True
>>>
>>> for ip in ipaddress.ip_network('192.168.0.0/28'):
...     print(ip)
...
192.168.0.0
192.168.0.1
192.168.0.2
192.168.0.3
192.168.0.4
192.168.0.5
192.168.0.6
192.168.0.7
192.168.0.8
192.168.0.9
192.168.0.10
192.168.0.11
192.168.0.12
192.168.0.13
192.168.0.14
192.168.0.15
>>>
>>> ipaddress.ip_network('192.168.0.0/28').num_addresses
16

批量计算

$ cat 2
172.16.128.0/18
172.16.32.0/20
172.16.64.0/19
172.19.192.0/19
172.16.240.0/21
172.16.48.0/20
172.16.192.0/19
172.19.160.0/19
172.19.64.0/18
172.16.24.0/21
172.16.96.0/19
172.19.128.0/19


$ python3
>>> import ipaddress
>>> with open("./2", "r") as f:
...     for i in f.readlines():
...         print(ipaddress.ip_network(i.rstrip()).num_addresses)
...
16384
4096
8192
8192
2048
4096
8192
8192
16384
2048
8192
8192

 

3 Comments

ElasticSearch DSL聚合查询语句

本来像聚合(aggregation)这种东西, 在Grafana中可以轻易的实现, 但是偶尔会有需求, 需要自己写DSL脚本实现一些功能, 于是, 只好自己动手了.

例子1

查询serverName=”dns-server-1″结果里, 按hostip的数量进行排序, 取前5

GET /my-service-2020.07.22/_search
{
  "query": {
    "term": { "serverName.keyword": "dns-server-1" }
  },
  "size" : 0,
  "aggs": {
    "top-10-hostip": {
      "terms": {
      	"field": "hostip.keyword",
        "size": 5
      }
    }
  }
}

结果

Leave a Comment

python字符串对齐

对于基本的字符串对齐操作,可以使用字符串的 ljust() , rjust() 和 center() 方法。比如:

>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '

所有这些方法都能接受一个可选的填充字符。比如:

>>> text.rjust(20,'=')
'=========Hello World'
>>> text.center(20,'*')
'****Hello World*****'
>>>

如果你想指定一个非空格的填充字符,将它写到对齐字符的前面即可:

>>> format(text, '=>20s')
'=========Hello World'
>>> format(text, '*^20s')
'****Hello World*****'

当格式化多个值的时候,这些格式代码也可以被用在 format() 方法中。比如:

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'

下面是一个例子

>>> top_5_domain = [{'key': 'www.hizy.net', 'doc_count': 32109556}, {'key': 'www.xpdo.net', 'doc_count': 12070}, {'key': 'www.zhukun.net', 'doc_count': 1156}, {'key': 'image.baidu.com', 'doc_count': 114}, {'key': 'cloudrea.ksidc.com', 'doc_count': 11}]
>>>
>>> format_temp = "\t {:<20} \t\t {:>12}"
>>> for d in top_5_domain:
...     print(format_temp.format(d["key"],str(d["doc_count"])))
...
     www.hizy.net         		     32109556
     www.xpdo.net         		        12070
     www.zhukun.net       		         1156
     image.baidu.com      		          114
     cloudrea.ksidc.com   		           11

 

Leave a Comment

Django parse a json/dictionary reminder on template

如果想在一个Django template里引入json, 正确的template写法为

python的views.py的写法

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import Http404, HttpResponse

def get_product(request):
context1 = {}
context1[‘env’] = ‘production’
context1[‘mydict’] = {"key1":"value1", "key2":"value2", "key3":"value3", "key4":"value4"}
context1[‘days’] = [1,2,3]

if request.GET.get("item") == "ec2" or not request.GET.get("item"):
return render(request, ‘main_content.html’, context1)
else:
raise Http404()

main_content.html使用extends引入index.html

{% extends 'index.html' %}
{% block content %}
{% for day in days %}
<li>day: {{ day }}</li>
{% endfor %}
{% endblock %}

index.html使用include引入sidebar.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="header">My page</div>
<div class="content">
<div class="sidebar">

<ul>
{% if env == 'production' %}
{% include 'production.sidebar.html' %}
{% elif env == 'development %}
{% include 'development.sidebar.html' %}
{% elif env == 'staging' %}
{% include 'staging.sidebar.html' %}
{% elif env == 'legacy' %}
{% include 'legacy.sidebar.html' %}
{% endif %}
</ul>

</div>
<div class="maincontent">

{% block content %} {% endblock %}

</div>
</div>
</body>
</html>
Leave a Comment