常用bash脚本

Hello World, Hello Blog

Posted by stq on May 16, 2023

重启java

JAR_PATH="."
JAR_NAME="foo.jar"

# 找出运行foo.jar的进程ID (PID)
PID=$(ps aux | grep "$JAR_NAME" | grep -v grep | awk '{print $2}')

# 如果找到了PID,则杀死该进程
if [[ ! -z $PID ]]; then
  echo "Killing process $PID..."
  kill -9 $PID
else
  echo "No process found running $JAR_NAME"
fi

# 重新启动foo.jar
echo "Restarting $JAR_NAME..."
nohup java -jar $JAR_PATH/$JAR_NAME >/dev/null &

死循环启动

while true
do
   your-command
   sleep 10
done

批量配置免密登录

#!/bin/bash

# 使用你的用户名替换下面的值
USER="root"

# 使用你的远程主机的地址替换下面的值
REMOTE_HOSTS=("remote_host1" "remote_host2" "remote_host3")
# 生成SSH密钥对(如果不存在的话)
if [ ! -f ~/.ssh/id_rsa ]; then
    ssh-keygen -t rsa -b 2048 -N "" -f ~/.ssh/id_rsa
fi
for REMOTE_HOST in ${REMOTE_HOSTS[@]}
do
    # 复制公钥到远程主机
    ssh-copy-id $USER@$REMOTE_HOST

    # 验证免密登录
    ssh -o BatchMode=yes -o ConnectTimeout=5 $USER@$REMOTE_HOST echo "SSH connection to $REMOTE_HOST successful"
done

#!/bin/bash

# 使用你的用户名替换下面的值
USER="your_username"
# 生成SSH密钥对(如果不存在的话)
if [ ! -f ~/.ssh/id_rsa ]; then
    ssh-keygen -t rsa -b 2048 -N "" -f ~/.ssh/id_rsa
fi
# 使用你的远程主机的地址和端口替换下面的值
# 格式为 "hostname:port"
REMOTE_HOSTS=("remote_host1:port1" "remote_host2:port2" "remote_host3:port3")

for HOST_PORT in ${REMOTE_HOSTS[@]}
do
    IFS=':' read -ra ADDR <<< "$HOST_PORT"
    REMOTE_HOST=${ADDR[0]}
    PORT=${ADDR[1]}

    # 复制公钥到远程主机
    ssh-copy-id -p $PORT $USER@$REMOTE_HOST

    # 验证免密登录
    ssh -o BatchMode=yes -o ConnectTimeout=5 -p $PORT $USER@$REMOTE_HOST echo "SSH connection to $REMOTE_HOST on port $PORT successful"
done

配置免密登录简易版

ssh-keygen -t rsa -b 2048
ssh-copy-id username@hostname 

windows使用scp更新到服务器jar包脚本 –已经配置过免密登录

scp  ../../target/app.jar stq@10.1.19.40:/data/app/
ssh stq@10.1.19.40 "cd /data/app && ./restart.sh"