脚本库

本文最后更新于:2024年6月21日 凌晨

Windows - bat脚本

自动提交git文件

新建一个txt文件,进行编辑,编辑后,更改后缀为bat

chcp 65001:为了防止使用UTF-8编码出现中文乱码

我要提交的文件在E盘,而bat脚本在桌面,所以首先e:,进入E盘,再cd到对应的文件夹,提交信息使用系统时间

chcp 65001
rem 设置提交信息
set commit_msg=%date%
e:
cd E:\笔记\hexo-fluid
git add .
git commit -m "%commit_msg%"
git push
echo 已完成!
pause

演示的结果图:

image-20231227020050017

Linux脚本

集群分发脚本

可以同步多个服务器中的文件,在服务器任何地方使用脚本都可以同步文件

1.创建文件

为了让系统中的任何位置都能执行这个脚本,例如我们在当前用户wwj根目录创建一个文件夹bin(位置:/home/wwj/bin)

/home/wwj/bin加入全局环境变量:(root用户使用需要指定到脚本具体位置:/home/wwj/bin/xsync)

sudo vim /etc/profile

在文件的末尾添加以下行:

export PATH=$PATH:/home/wwj/bin

保存并关闭文件,为了使改动立即生效,需要执行以下命令:source /etc/profile,查看是否已经添加成功:

wwj@JD bin$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:
/home/wwj/bin

/home/wwj/bin中创建文件xsync,填入以下内容,需要替换host中的hadoop102-104为自己需要同步的服务器

#!/bin/bash

#1. 判断参数个数
if [ $# -lt 1 ]
then
    echo Not Enough Arguement!
    exit;
fi

#2. 遍历集群所有机器
for host in hadoop102 hadoop103 hadoop104
do
    echo ====================  $host  ====================
    #3. 遍历所有目录,挨个发送

    for file in $@
    do
        #4. 判断文件是否存在
        if [ -e $file ]
            then
                #5. 获取父目录
                pdir=$(cd -P $(dirname $file); pwd)

                #6. 获取当前文件的名称
                fname=$(basename $file)
                ssh $host "mkdir -p $pdir"
                rsync -av $pdir/$fname $host:$pdir
            else
                echo $file does not exists!
        fi
    done
done

为脚本赋予可执行权限:chmod 777 xsync, 执行命令xsync 文件地址,例如:

wwj@JD ~$ xsync bin/

首次使用时,需要输入目标服务器的密码,我们可以使用ssh免密登录:(演示服务器A -> 服务器B

服务器A生成ssh密钥对:ssh-keygen -t rsa

wwj@JD /$ cd ~/.ssh/
wwj@JD .ssh$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/wwj/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/wwj/.ssh/id_rsa
Your public key has been saved in /home/wwj/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:QigxmgXju6yJuFzOSqjR8MhDfbNsM+iKN4eJHchQotE wwj@JD
The key's randomart image is:
+---[RSA 3072]----+
|oo+              |
|+=Eo .           |
|+=. . .          |
|o o. .           |
|++ . o. S        |
|**o + o.         |
|+Oo* *           |
|Xo% o o          |
|O*o*             |
+----[SHA256]-----+

分享ssh公钥到服务器B上,使用命令:ssh-copy-id 服务器B

之后访问服务器B则不需要输入密码,使用xsync脚本分发时则不需要密码


脚本库
https://junyyds.top/2023/12/26/脚本库/
作者
Phils
发布于
2023年12月27日
更新于
2024年6月21日
许可协议