【星海随笔】linux运维篇

阅读: 评论:0

【星海随笔】linux运维篇

【星海随笔】linux运维篇

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

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[@]}"; doecho ${value}((count++))
donehost_num=1
local_val=0
let "local_val=count-1"
for i in $(seq 0 ${local_val} ); donum=${i}host_name=${local_name}${host_num}rewrite_host "${ip_list[${num}]}" "${host_name}"((host_num++))echo "${host_num}-${host_name}"
done

效果图

[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
demo2

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

#!/usr/bin/expect -fset 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 "yesr"exp_continue}
}

效果图

[root@ecs-t1 ~]# ./ssh_p
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_p 123456
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
demo4

下载安装

pip3 install pdf2docx

PCW.py
pdf转word。

from pdf2docx import parsepdf_path = "t1.pdf"
docx_path = "t1.docx"parse(pdf_path, docx_path)
demo5

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

import http.server
import socketserver
import osclass MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):def do_GET(self):# 处理目录请求,返回目录列表if self.path == '/':self.path = '/'  # 修改为根目录self.list_wd())  # 获取当前目录的文件列表并返回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')d_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.de())  # 将HTML内容写入响应中if __name__ == '__main__':PORT = 8000  # The port to run the server onhandler = MyHttpRequestHandlerhttpd = socketserver.TCPServer(("", PORT), handler)print(f"Serving at port {PORT}")httpd.serve_forever()
demo6

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

pip install pyinstaller
pyinstaller --onefile your_script.py
demo7

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

pip3 install --upgrade pip -i /

flask实现简易文件服务器

pip install -i  Flask

当前版本为:
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;location /api {proxy_pass localhost:5000/upfile;}}

访问:<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(alpath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'file')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}app = Flask(__name__)
fig['UPLOAD_FOLDER'] = UPLOAD_FOLDER
fig['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024def allowed_file(filename):return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS&#ute('/upfile', methods=['GET', 'POST'])
def up_file():hod == 'GET':return render_template('upfile.html')hod == 'POST':title = ('title')  # form 获取表单参数file = ('file')  # file 或取文件参数if file and allowed_file(file.filename):filename = secure_filename(file.filename)  # 校验文件名称合法print(filename)file.save(os.path.fig['UPLOAD_FOLDER'], filename))return {'msg': 'success','url': f'/images/{filename}/',}else:return {'msg': '文件格式不支持'}&#ute('/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")

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>

手动创建一个文件夹

mkdir file
demo8

快速格式化磁盘

disk_part=${1-vdb}
disk_size=${2-20G}fdisk /dev/${disk_part} <<EOF
n
p
2048w
EOF
4 /dev/${disk_part}1
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 << EOFY
${password}
${password}
Y
Y
Y
Y
EOF
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;"

手敲阶段

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' );"

read.sh

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

#!/bin/bashecho "请输入你的账号;"
read account
echo "请输入你的密码:"
read passwdfunction xxx(){echo "pass"
}mysql -u${account} -p${passwd} -e "INSERT INTO ${account}.safe ( name, description ) VALUES ( '${account}', 'test' );"xxx

yum install Cython
rubbish

record mistake of myself

#!/bin/bash
pip3_url=".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 ];thenecho "not have pip3"
elseecho -e "33[1;32m [INFO] already has pip3 33[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}') ];thenprintf "33[1;33m [Warning] Need upgrade pip vresio

本文发布于:2024-01-28 07:04:48,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/17063966935661.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:星海   随笔   运维篇   linux
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23