Android-Charts技术交流QQ群现已开通,欢迎加入。群号:170987350

DIR命令无法获得精确到秒的问题

July 5th, 2021 No comments

DIR命令无法获得精确到秒的问题

方法一,dir命令只能到分钟,如果需要到秒,建议改用forfiles命令

REM "delims=" is required to avoid stripping AM/PM
for /f "delims=" %%i in ('"forfiles /p C:\Users\limc /m *.bat /c "cmd /c echo @fdate @ftime" "') do set modif_time=%%i
echo %modif_time%

参考
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc753551(v=ws.11)?redirectedfrom=MSDN

方法二,用VBS的FileSystemObject方式解决

@set @n=0/*&echo off
dir /a-d/s/b|Cscript -nologo -e:jscript "%~f0" > 1.txt
pause&exit /b */
var fso=new ActiveXObject('scripting.FileSystemObject');
while(!WSH.StdIn.AtEndOfStream)
{
file=fso.GetFile(WSH.StdIn.ReadLine());
t=new Date(file.DateCreated);
t1 = t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate() + " " + t.getHours() + ":" + t.getMinutes() + ":" + t.getSeconds();
WSH.Echo(file + "\t" + t1);
}
Categories: 零敲碎打 Tags: , ,

nginx 首页不存在时默认返回404而不是403

July 5th, 2021 No comments

nginx 首页不存在时默认返回404而不是403

域名被某站劫持了导致整站被B,通过nginx设置将指定域名bound到指定的站点,然后强制返回404。

location = / {
return 404;
}

但是首页还是返回403代码。而不是预期的404。
于是让404正常,再直接把首页301 到一个不存在的资源。 完工

location = / {
index index.html
return 404;
}

location = /index.html {
return 301 /noexsit;
}

Categories: 零敲碎打 Tags:

windows计划任务指定时间段执行程序

July 5th, 2021 No comments

一个简单的需求,windows服务器设置计划任务,在需要在指定时间段9点到15点执行特定的程序。
但是windows的计划任务不像corntab那样支持设定指定时间区间,只可以设置每小时启动一次。

方法1.启动Bootstrap程序,根据当前时间决定是否继续执行任务

获取当前时间的字符串

SET curr_time=%TIME:~0,-5%
SET curr_time_str=%curr_time::=%

获取时间后,逻辑判断是否goto执行相应的代码

完整的代码

@echo off
ECHO "Time Schedule Bootstrap"
SET curr_time=%TIME:~0,-5%
SET curr_time_str=%curr_time::=%
IF %curr_time_str% leq 0900 (GOTO time_cancel) ELSE (
IF %curr_time_str% leq 1500 (GOTO time_exec) ELSE (
GOTO time_cancel
)
)
exit 0
 
:time_exec
ECHO "Call CMD.exe"
CMD.exe 
exit 0
 
:time_cancel
ECHO "Canceled"
exit 10

方法2.设置每天启动一次在指定的小时,需要设置多次,此处跳过

Categories: 系统管理 Tags: ,

[WordPress] 子目录下WP建站Nginx反向代理设置

July 5th, 2021 No comments

子目录下WP建站Nginx反向代理设置
参考官方文档,两种方式一下都可以实现要求

方法1,rewrite方式,适用php-fpm

location /替换子目录名称/ {
index index.html index.php;

if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}

if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}

if (!-f $request_filename){
rewrite (.*) /替换子目录名称/index.php;
}
}


方法2,使用try_files方式

location /替换子目录名称/ {
index index.php;
try_files $uri $uri/ /替换子目录名称/index.php?$args;
}

必须要做的,把wp-admin单独处理

rewrite /替换子目录名称/wp-admin$ $scheme://$host$uri/ permanent;

Categories: 博客技巧, 零敲碎打 Tags: , ,

Win10 DISM离线安装.net framework

June 16th, 2020 No comments

Win10 DISM离线安装.net framework

DISM(Deployment Image Servicing and Management)就是部署映像服务和管理 (DISM.exe) 用于安装、卸载、配置和更新脱机 Windows(R) 映像和脱机 Windows 预安装环境 (Windows PE) 映像中的功能和程序包。

安装.net framework, windows系统安装盘位置为E:盘

Dism /Online /Enable-Feature /FeatureName:netfx3 /Source:E:\sources\sxs

其他用途

1.扫描映像,查看映像是否有损坏(有损坏时电脑会遇到许多小问题,比如可能无法更新系统)

Dism /Online /Cleanup-Image /ScanHealth

2.最后是修复系统映像文件

Dism /Online /Cleanup-Image /RestoreHealth

使用本地源修复镜像,可以是windows安装光盘,或者虚拟光驱加载ISO文件

Dism /Online /Cleanup-Image /RestoreHealth /Source:c:\test\mount\windows /LimitAccess

PE环境下也可以用ImageFile方式,直接使用windows image格式文件

Dism /Apply-Image /ImageFile:X:sourcesinstall.wim /Index:1 /ApplyDir:C:

参考
https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/what-is-dism

Categories: 系统管理 Tags: ,

FastAPI 使用JWT认证的中间件

May 25th, 2020 No comments

FastAPI 使用JWT认证的中间件
fastapi的中间件还是太少,单独开发JWT需要,starlette本身提供认证相关实现,只需要自定义一个AuthenticationBackend即可,本次我们实现使用中间价方式拆包JWT的令牌,获取payload里面的用户信息

私有定义的payload内容格式如下

{
"usid": "SkDQBhEjUfygRSeEBech", //UUID Short
"uname": "test user name",  //Username
"mid":"700010001" // Member ID
}

调用代码

app = FastAPI()
app.add_middleware(AuthenticationMiddleware,backend=JWTAuthenticationBackend(secret_key="YOUR_SECRET_KEY"))

完整的代码

import jwt
 
from starlette.authentication import (
    AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials,
    UnauthenticatedUser )
 
 
class JWTUser(BaseUser):
    def __init__(self, user_id_short: str, member_number: str, user_name: str,token: str, payload: dict) -> None:
        self.user_name = user_name
        self.user_id_short = user_id_short
        self.member_number = member_number
        self.token = token
        self.payload = payload
 
    @property
    def is_authenticated(self) -> bool:
        return True
 
    @property
    def display_name(self) -> str:
        return self.user_name   ## 会员名处理,加*?
 
    @property
    def display_user_id_short(self) -> str:
        return self.user_id_short   ## 会员id处理
 
    @property
    def display_member_number(self) -> str:
        return self.member_number  ## 会员号处理,加*?
 
 
class JWTAuthenticationBackend(AuthenticationBackend):
 
    def __init__(self, secret_key: str, algorithm: str = 'HS256', prefix: str = 'JWT', user_name_field:str = 'uname' , user_id_field: str = 'usid',member_number_field: str = 'mid'):
        self.secret_key = secret_key
        self.algorithm = algorithm
        self.prefix = prefix
        self.user_name_field = user_name_field
        self.user_id_field = user_id_field
        self.member_number_field = member_number_field
 
 
    @classmethod
    def get_token_from_header(cls, authorization: str, prefix: str):
        """
        Parses the Authorization header and returns only the token
        :param authorization:
        :return:
        """
        try:
            scheme, token = authorization.split()
        except ValueError:
            raise AuthenticationError('Could not separate Authorization scheme and token')
        if scheme.lower() != prefix.lower():
            raise AuthenticationError(f'Authorization scheme {scheme} is not supported')
        return token
 
    async def authenticate(self, request):
        if "Authorization" not in request.headers:
            return None
 
        auth = request.headers["Authorization"]
        token = self.get_token_from_header(authorization=auth, prefix=self.prefix)
        try:
            payload = jwt.decode(token, key=self.secret_key, algorithms=self.algorithm)
        except jwt.InvalidTokenError as e:
            raise AuthenticationError(str(e))
 
        return AuthCredentials(["jwt_authenticated"]), JWTUser(user_id_short=payload[self.user_id_field], member_number=payload[self.member_number_field],user_name=payload[self.user_name_field],token=token,
                                                           payload=payload)
 
 
class JWTWebSocketAuthenticationBackend(AuthenticationBackend):
 
    def __init__(self, secret_key: str, algorithm: str = 'HS256', query_param_name: str = 'jwt',
                 user_name_field:str = 'uname' , user_id_field: str = 'usid',member_number_field: str = 'mid'):
        self.secret_key = secret_key
        self.algorithm = algorithm
        self.query_param_name = query_param_name
        self.user_name_field = user_name_field
        self.user_id_field = user_id_field
        self.member_number_field = member_number_field
 
    async def authenticate(self, request):
        if self.query_param_name not in request.query_params:
            return AuthCredentials(), UnauthenticatedUser()
 
        token = request.query_params[self.query_param_name]
 
        try:
            payload = jwt.decode(token, key=self.secret_key, algorithms=self.algorithm)
        except jwt.InvalidTokenError as e:
            raise AuthenticationError(str(e))
 
        return AuthCredentials(["jwt_authenticated"]), JWTUser(user_id_short=payload[self.user_id_field], member_number=payload[self.member_number_field],user_name=payload[self.user_name_field],token=token,
                                                           payload=payload)
Categories: 语言编程 Tags: , ,

Docker中使用conda不能激活环境问题

May 6th, 2020 No comments

Anaconda或者miniconda在容器中安装以后,需要手动执行一下
conda init以后才可以激活相应的环境

假设conda的安装目录prefix为

/opt/conda/

查看init以后的~/.bashrc,发现conda是根据shell的类型执行相应的安装

__conda_setup="$('/opt/conda/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
if [ $? -eq 0 ]; then
    eval "$__conda_setup"
else
    if [ -f "/opt/conda/etc/profile.d/conda.sh" ]; then
        . "/opt/conda/etc/profile.d/conda.sh"
    else
        export PATH="/opt/conda/bin:$PATH"
    fi
fi
unset __conda_setup

安装完成conda以后,直接执行相同的操作,启动/bin/bash时默认就会激活base环境

Ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh
echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc      #
echo "conda activate base" >> ~/.bashrc 
export PATH="/opt/conda/bin:$PATH"

如果需要激活其他环境,需要先行配置好虚拟环境
修改

echo "conda activate base" >> ~/.bashrc

为需要的环境即可

Categories: 系统管理 Tags: