当前位置:   article > 正文

【星海随笔】linux运维篇-精致小模块,小技巧。无他唯快尔_linux系统os升级后测试点

linux系统os升级后测试点

大家一定要点赞加关注哈。我会持续更新的。
这个我可是买了华为云主机去测试的。多多点赞关注。多给点正向反馈。

Windows 首装密钥安装篇

https://blog.csdn.net/sj349781478/article/details/130243884

docker Key认证获取篇

https://blog.csdn.net/weixin_44430301/article/details/129561939
只第二大步

常用命令:

sed -i "/config_path/s/\"\"/\"\/etc\/containerd\/certs.d\"/g" /etc/containerd/config.toml
  • 1
查看操作系统版本
lsb_release -a
  • 1
  • 2
NVCC编译

在这里插入图片描述

TOOL
https://developer.nvidia.com/cuda-12-3-0-download-archive

nvcc -c your_file.cu -o your_file.o -O3 -I/path/to/include
# -O3 是优先级
nvcc -o SummationOfConventions SummationOfConventions.cu
  • 1
  • 2
  • 3

设置Ubuntu可以root用户登录

sudo passwd root
/etc/ssh/sshd_config
PermitRootLogin yes
sudo systemctl restart sshd
  • 1
  • 2
  • 3
  • 4

Ubuntu离线安装包

sudo apt-get --download-only install gcc
sudo dpkg -i /var/cache/apt/archives/package-name.deb
  • 1
  • 2

Ubuntu离线卸载包

sudo apt-get remove package-name
sudo apt-get purge package-name
  • 1
  • 2

查看有哪些包安装了

dpkg --list | grep package-name
  • 1

Ubuntu自制service

#### Ubuntu设置服务
 /etc/systemd/system/multi-user.target.wants/nvidia-dcgm.service 
 -> 
 /lib/systemd/system/nvidia-dcgm.service
```bash
[Unit]
Description=NVIDIA DCGM service
Conflicts=dcgm.service

[Service]
User=root
PrivateTmp=false

Environment="DCGM_HOME_DIR=/var/log/nvidia-dcgm"

ExecStart=/usr/bin/nv-hostengine -n --service-account nvidia-dcgm

Restart=on-abort

[Install]
WantedBy=multi-user.target
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

**Ubuntu修改配置DNS**

```bash
vim /etc/resolv.conf
systemctl restart systemd-resolved.service
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Ubuntu设置英伟达的源

/etc/apt/source.list
deb http://10.10.254.30:8081/repository/ubuntu-nvidia/ /

Ubuntu Key
https://developer.download.nvidia.cn/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub
sudo apt-key add 3bf863cc.pub

sudo apt-get update
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

pip3
临时更换pip源

pip install markdown -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 1
离线下载某个包

python -m pip download -d /home/packs  setuptools==33.1.1 
# 下载setuptools==33.1.1模块,在/home/packs目录下
  • 1
  • 2
  • 3
  • 4
 pip3 download -d ${folder} -r /home/wx/requirements.txt
cat requirements.txt
tensorflow==2.8.0
pip3 install --no-index --find-links ${folder} -r /path/to/requirements.txt
  • 1
  • 2
  • 3
  • 4
重新安装一个python包
pip install auto-py-to-exe --upgrade --force-reinstall
If you downloaded the repo and ran auto-py-to-exe from there: 
pip install -r .\requirements.txt --upgrade --force-reinstall 
or
cd /path/to/your/repo
pip install . --upgrade --force-reinstall
at the root of this project
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
查看占用 Cpu 或者 Mem 最大的进程,并排序
ps -eo pid,ppid,cmd,%cpu,%mem --sort=-%cpu | head
最近一天被修改的文件
find ./ -type f -mtime -1
  • 1
  • 2
  • 3
  • 4
离线安装特定版本的python

注意/usr/local/python3是否存在
/usr/bin/python3 是否存在
本次安装的是3.10.13

# Step one 进入官网下载包
https://www.python.org/ftp/python/
# Step two 设置环境
./configure --prefix=/usr/local/python3 --enable-shared
make && make install
  • 1
  • 2
  • 3
  • 4
  • 5

安装路径

vim ~/.bashrc
>export PATH="/usr/local/python3/bin:$PATH"
bash
  • 1
  • 2
  • 3

建立软连接

ln -s /usr/local/python3/bin/python3.10 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3.10 /usr/bin/pip3
  • 1
  • 2

指定库文件,配置动态链接器

echo "/usr/local/python3/lib" > /etc/ld.so.conf.d/python3.8.conf
ldconfig
  • 1
  • 2

测试

python3 --version
pip3 --version

python3 -m venv myenv  
source myenv/bin/activate
  • 1
  • 2
  • 3
  • 4
  • 5
离线安装pip
首先下载对应版本的python包
https://www.python.org/ftp/python/3.7.3/Python-3.7.3.tgz
然后解压进入文件
sudo python3.7.3 setup.py install
  • 1
  • 2
  • 3
  • 4
离线安装pip附带问题解决
sudo apt remove python3.10-dev
sudo apt autoremove
sudo apt purge python3.10-dev
 
sudo apt-get --download-only install python3.10-dev

dpkg -i {}  #顺序执行,不能乱序
libexpat1-dev_2.4.7-1ubuntu0.2_amd64.deb
libpython3.10-dev_3.10.12-1~22.04.3_amd64.deb
python3.10-dev_3.10.12-1~22.04.3_amd64.deb
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
子用户免密登录
chmod u+w /etc/sudoers
echo "子用户 ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
chmod u-w /etc/sudoers```
  • 1
  • 2
  • 3

子用户bashsudo -s

demo 0

像快捷登录某个设备,又不想将其写在/etc/hosts ,又不想记他的IP。
就创建一个文件,命名一个自己方便记忆的名称。

#/bin/bash

echo "Please Input PASSWORD:"
ip=xx.xx.xx.xx
user=admin
ssh ${user}@${ip}
random_number=${RANDOM}
#read ${PASSWORD}
#file_name=${random_number}.expect
#cat >> ${file_name} << EOF
##!/usr/bin/expect -f
#set timeout 30
#spawn ssh ${user}@${ip}
#expect{
#"password:" {send "${PASSWORD}\r"}
#}
#EOF
#rm -rf ${file_name}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
demo1

hosts.sh
#实现将IP列表,以client的模式写入hosts。就不用手写了。
如果想换其他名称,修改local_name就可以。

#!/bin/bash
ip_list=("192.168.0.197" "192.168.0.120" "192.168.0.191")
local_name="client"
function rewrite_host(){
    local ip=${1}
    local host_name=${2}
    echo "${ip} ${host_name}" >> /etc/hosts
}

count=0
for value in "${ip_list[@]}"; do
    echo ${value}
    ((count++))
done

host_num=1
local_val=0
let "local_val=count-1"
for i in $(seq 0 ${local_val} ); do
    num=${i}
    host_name=${local_name}${host_num}
    rewrite_host "${ip_list[${num}]}" "${host_name}"
    ((host_num++))
    echo "${host_num}-${host_name}"
done
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

效果图

[root@ecs-t1 note]# cat /etc/hosts
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
127.0.0.1 ecs-t1 ecs-t1

192.168.0.197 client1
192.168.0.120 client2
192.168.0.191 client3

扩展:

如果一个密钥重复,则使用 -R 去清除。

ssh-keygen -R 124.71.200.20
  • 1
demo2

ssh_copy_id.exp
#如果想实现免密钥登录就不用手写了。
执行语句:./ssh_copy_id.exp 123456

#!/usr/bin/expect -f

set username "root"
set host "192.168.0.241"

if { $argc > 0 } {
    set passwd [lindex $argv 0]
}

spawn ssh-copy-id $username@$host
expect {
    "*assword*" {
        #
        send "${passwd}\r"
        exp_continue
    }
    # 其他情况,例如确认是否继续连接等,你可以根据需要处理
    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        exp_continue
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

效果图

[root@ecs-t1 ~]# ./ssh_copy_id.exp
spawn ssh-copy-id root@192.168.0.241
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: “/root/.ssh/id_rsa.pub”
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed – if you are prompted now it is to install the new keys
root@192.168.0.241’s password:

Number of key(s) added: 1

Now try logging into the machine, with: “ssh ‘root@192.168.0.241’”
and check to make sure that only the key(s) you wanted were added.

[root@ecs-t1 ~]# expect -f ssh_copy_id.exp 123456
  • 1
demo3

无交互生成本地密钥。
无交互生成本地可执行脚本。

yum -y install chrony
yum -y install expect
[无交互生成本地密钥。]
ssh-keygen -t rsa -q -P "" -f ~/.ssh/id_rsa

[无交互生成脚本]
cat > /root/expectssh.sh <<EOF
#!/usr/bin/expect -f
spawn ssh-keygen -i -F ${remote_ip}
expect "ssh-rsa"
send "\r"
expect eof
EOF
expect -f /root/expectssh.sh
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
demo4

下载安装

pip3 install pdf2docx
  • 1

PCW.py
pdf转word。

from pdf2docx import parse

pdf_path = "t1.pdf"
docx_path = "t1.docx"

parse(pdf_path, docx_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
demo5

download.py
#实现将本级目录下的文件展示出去。可供其他主机下载。
#8000端口

import http.server
import socketserver
import os

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 处理目录请求,返回目录列表
        if self.path == '/':
            self.path = '/'  # 修改为根目录
            self.list_directory(os.getcwd())  # 获取当前目录的文件列表并返回
            return
        # 否则,继续处理文件请求
        return super().do_GET()

    def list_directory(self, path):
        # 获取目录中的文件列表,并返回适当的HTTP响应
        files = os.listdir(path)  # 获取当前目录的文件列表
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        # 构造一个简单的HTML页面来显示文件列表
        html = "<html><body><h1>Files in {}</h1><ul>".format(path)
        for file in files:
            html += "<li><a href={}>{}</a></li>".format(file, file)
        html += "</ul></body></html>"
        self.wfile.write(html.encode())  # 将HTML内容写入响应中

if __name__ == '__main__':
    PORT = 8000  # The port to run the server on
    handler = MyHttpRequestHandler
    httpd = socketserver.TCPServer(("", PORT), handler)
    print(f"Serving at port {PORT}")
    httpd.serve_forever()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
demo6

该方法使用的是python312,需要重新装一些pip包

curl https://bootstrap.pypa.io/get-pip.py | python3
  • 1

在windows的git中执行的。
将your_script.py 编译为exe执行文件。

pip install pyinstaller
pyinstaller --onefile your_script.py
  • 1
  • 2

如果有第三方库,第三库的安装一版会安装在本地目录,而不是python包的环境目录,所以需要把一些三方的包copy到python的环境目录里

python -m eel T1.py GUI
pip install PyInstaller
  • 1
  • 2

设置一个.vbs文件,实现无CMD窗口执行

Set objShell = CreateObject("WScript.Shell")
objShell.Run "cmd.exe /c your_command_here", 0, False
  • 1
  • 2
Traceback (most recent call last):
  File "T1.py", line 20, in <module>
    from dlls import shell
  File "PyInstaller\loader\pyimod02_importers.py", line 419, in exec_module
  File "dlls\shell.py", line 258, in <module>
    import pymysql
ModuleNotFoundError: No module named 'pymysql'

pip install pymysql
Requirement already satisfied: pymysql in c:\users\asus\desktop\test report\4tomyself\pythonproject\.venv\lib\site-packages (1.1.0)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
demo7

快速创建一个文件上传服务。
清华源更新一下pip的版本

pip3 install --upgrade pip -i https://pypi.mirrors.ustc.edu.cn/simple/
  • 1

flask实现简易文件服务器

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Flask
  • 1

当前版本为:
pip3 list
Flask 2.0.3

pip3 -V
pip 21.3.1 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)

nginx的配置:
将8000:api 映射到后台的flask的5000端口上

    server {
        listen       80;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

    server {
        listen 8000;
        listen [::]:8000;
        server_name test.com;

        location /api {
            proxy_pass http://localhost:5000/upfile;
        }
    }

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

访问:<host>:<port>/upfile

app.py

import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from flask import send_from_directory
BASE_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'file')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/upfile', methods=['GET', 'POST'])
def up_file():
    if request.method == 'GET':
        return render_template('upfile.html')
    if request.method == 'POST':
        title = request.form.get('title')  # form 获取表单参数
        file = request.files.get('file')  # file 或取文件参数
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 校验文件名称合法
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return {
                'msg': 'success',
                'url': f'/images/{filename}/',
            }
        else:
            return {
                'msg': '文件格式不支持'
            }

@app.route('/images/<filename>/')
def get_image(filename):
    return send_from_directory(UPLOAD_FOLDER, filename)

if __name__ == '__main__':
    app.run(host="192.168.0.160", port="5000")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

templates/upfile.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件功能</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <div>
            <label for="title">文件名称</label>
            <input id="title" type="text" name="title">
        </div>
        <div>
            <label for="file">文件名称</label>
            <input id="file" type="file" name="file">
        </div>
      <input type=submit value="提交">
    </form>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

手动创建一个文件夹

mkdir file
  • 1
demo8

快速格式化磁盘

disk_part=${1-vdb}
disk_size=${2-20G}

fdisk /dev/${disk_part} <<EOF
n
p
2048

w
EOF
mkfs.ext4 /dev/${disk_part}1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
demo9

快速初始化数据库

快速初始化数据库
```bash
password="test123456!"

yum group install mariadb mariadb-client -y
systemctl enable mariadb
systemctl status mariadb
systemctl start mariadb
netstat -lant | grep 3306
mysql_secure_installation << EOF

Y
${password}
${password}
Y
Y
Y
Y
EOF
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
demo10

实现一个数据库的记录。设置一个操作时间戳记录措施。

setup.sh

echo "please input password:"
read password
echo "please input you want create account!"
read account
mysql -uroot -p ${password} -e " CREATE USER '${account}'@'localhost' IDENTIFIED BY 'password123'; "
mysql -uroot -p ${password} -e "create database ${account};"

mysql -uroot -p ${password} -e "create TABLE ${account}.safe (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL, description TEXT, At_Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP  );"

mysql -uroot -p ${password} -e "GRANT ALL PRIVILEGES ON ${account}.* TO '${account}'@'localhost';"

mysql -uroot -p  ${password} -e "FLUSH PRIVILEGES;"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

手敲阶段

mysql -uroot -p123456! -e "CREATE USER 'admin'@'localhost' IDENTIFIED BY 'password123';"
mysql -uroot -p123456! -e "CREATE USER 'service'@'localhost' IDENTIFIED BY 'password123';"
mysql -uroot -p123456! -e "CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password123';"

mysql -uroot -p123456! -e "create database admin;"
mysql -uroot -p123456! -e "create database service;"
mysql -uroot -p123456! -e "create database newuser;"

mysql -uroot -p123456! -e "create TABLE admin.safe (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL, description TEXT, At_Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP  );"
mysql -uroot -p123456! -e "create TABLE service.safe (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL, description TEXT, At_Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP  );"
mysql -uroot -p123456! -e "create TABLE newuser.safe (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(255) NOT NULL, description TEXT, At_Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP  );"

mysql -uroot -p123456! -e "GRANT ALL PRIVILEGES ON admin.* TO 'admin'@'localhost';"
mysql -uroot -p123456! -e "GRANT ALL PRIVILEGES ON service.* TO 'service'@'localhost';"
mysql -uroot -p123456! -e "GRANT ALL PRIVILEGES ON newuser.* TO 'newuser'@'localhost';"

mysql -uroot -p123456! -e "FLUSH PRIVILEGES;"

mysql -unewuser -ppassword123 -e "INSERT INTO newuser.safe ( name, description ) VALUES ( 'wang xin', 'test' );"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

read.sh

设置一个操作时间戳记录措施。入口。可以对一些敏感操作增加时间戳。

#!/bin/bash

echo "请输入你的账号;"
read account
echo "请输入你的密码:"
read passwd

function xxx(){
    echo "pass"
}

mysql -u${account} -p${passwd} -e "INSERT INTO ${account}.safe ( name, description ) VALUES ( '${account}', 'test' );"

xxx
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

yum install Cython
  • 1
MD5校准
shasum -a 512 -b  \<file>
shasum -a 512 -b -c \<hash_file> > $LOG
cat > hash_file << EOF
md5sauhduasncioadhwoadhaduohhawdahio  ./test/xxx.sh
EOF
cat $LOG | grep FAILED
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
rubbish

record mistake of myself

#!/bin/bash
pip3_url="https://downloads.python.org/pypy/pypy3.10-v7.3.14-linux64.tar.bz2"

function up_pip3(){
    wget ${pip3_url}
    local_dir=$(echo ${pip3_url} | awk -F "/" '{print $NF}')
    tar -xvjf ${local_dir}
    bin_dir=$(echo ${local_dir} | sed -n 's/\(.*\).tar\.bz2.*/\1/p' )
    echo "bin_dir: ${bin_dir}"
    cd ${bin_dir} && ./bin/pypy --update && ./bin/pypy --version
}

code=$(pip3 -V)
if [ ! $? -eq 0 ];then
    echo "not have pip3"
else
    echo -e "\033[1;32m [INFO] already has pip3 \033[0m"
fi
pip_version=$(pip3 -V | sed -n 's/.*pip \([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\).*/\1/p')

if [ "23" -gt $(echo ${pip_version} | awk -F "." '{print $1}') ];then
    printf "\033[1;33m [Warning] Need upgrade pip vresio
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
Git上一串代码写的不错,反手就是一个截胡
import sys, platform, socket, os, json, hashlib
sys.dont_write_bytecode = True
RED = "\033[91m"
GREEN = "\033[92m"
RESET = "\033[0m"

def colored_print(color, message):
    print(f"{color}{message}{RESET}")

def calculate_checksum(file_path, hash_algorithm="sha256", buffer_size=8192):
    hasher = hashlib.new(hash_algorithm)
    with open(file_path, 'rb') as file:
        buffer = file.read(buffer_size)
        while len(buffer) > 0:
            hasher.update(buffer)
            buffer = file.read(buffer_size)
    return hasher.hexdigest()

def load_checksums_from_json(json_file="checksums.json"):
    try:
        with open(json_file, 'r') as file:
            checksums = json.load(file)
        return checksums
    except FileNotFoundError:
        print(f"Error: The checksums file '{json_file}' not found.")
        return {}
    except json.JSONDecodeError:
        print(f"Error: Failed to decode JSON in '{json_file}'. Make sure the file is valid JSON.")
        return {}
    
def verify_checksums(directory, checksums):
    invalid_files = [(os.path.join(root, file_name), checksums[os.path.join(root, file_name)])
                     for root, _, files in os.walk(directory)
                     for file_name in files
                     if file_name != 'checksums.json'
                     if os.path.join(root, file_name) in checksums
                     if checksums[os.path.join(root, file_name)] != calculate_checksum(os.path.join(root, file_name))]

    for file_path, expected_checksum in invalid_files:
        print(f"Error: Checksum mismatch for file '{file_path}'.")
    message = f"All files have valid checksums." if not invalid_files else f"{len(invalid_files)} file(s) have invalid checksums."
    colored_print(GREEN if not invalid_files else RED, message)



def check_import(module_name):
    try:
        __import__(module_name)
        colored_print(GREEN, f"Import '{module_name}' successful.")
        return True
    except ImportError:
        colored_print(RED, f"Import '{module_name}' failed.")
        input(f"{RESET}Press enter to continue\n")
        return False

def check_internet_connection():
    try:
        socket.create_connection(("8.8.8.8", 53), timeout=5)
        colored_print(GREEN, "Connected to the internet.")
        return True
    except OSError:
        colored_print(RED, "No internet connection.")
        return False


def check_python_version():
    major, minor = sys.version_info[:2]
    if major < 3 or (major == 3 and minor < 12):
        colored_print(GREEN, f"Python version {major}.{minor} is supported.")
        return False
    else:
        colored_print(RED, f"Python version {major}.{minor} is not supported. Required: 3.11-3.8")
        input(f"{RESET}Press enter to continue\n")
        return True

def check_system_architecture():
    system_architecture = platform.architecture()[0]
    if system_architecture == '64bit':
        colored_print(GREEN, f"System Architecture: {system_architecture}")
        return True
    else:
        colored_print(RED, f"Unsupported System Architecture: {system_architecture}")
        print("You need to compile the de4py tools for your device.")
        return False

def main():
    colored_print(RED, "BEFORE THE CHECKING PROCESS START IGNORE checksums.json or __pycache__ FILES !")
    input(f"{RED}Press enter to start{RESET}\n")
    print("Checking the environment...")
    if check_python_version() or not check_internet_connection() or not check_system_architecture():
        sys.exit(1)

    imports_to_check = [
        'os', 'msvcrt', 'eel', 'logging', 'requests', 'platform', 'threading', 'psutil', 'colorama', 'signal',
        'config', 'plugins', 'TUI.cli', 'deobfuscators.detector', 'dlls.shell', 'analyzer', 'time', 'inspect', 'importlib.util'
    ]
    for module in imports_to_check:
        if not check_import(module):
            sys.exit(1)

    print("Environment checks passed. Verifying checksums...")
    directory_to_check = "."
    checksums_json_file = "checksums.json" 
    loaded_checksums = load_checksums_from_json(checksums_json_file)
    verify_checksums(directory_to_check, loaded_checksums)
    sys.exit(1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/905072
推荐阅读
相关标签
  

闽ICP备14008679号