#!/bin/bash # 获取环境变量 USER=${USER} HOST=${HOST} SUDO_PASS=${SUDO_PASS} USER_HOME=/home/$USER # 检查环境变量是否为空 if [ -z "$HOST" ]; then echo "Error: 远程主机地址不能为空" exit 1 fi if [ -z "$USER" ]; then echo "Error: 用户名不能为空" exit 1 fi if [ -z "$SUDO_PASS" ]; then echo "Error: sudo 密码不能为空" exit 1 fi # 将 start_socat.sh 拷贝到 host 的用户 home 目录上 rsync -avz start_socat.sh $USER@$HOST:$USER_HOME/ # 创建一个临时远程脚本文件 REMOTE_SCRIPT=$(mktemp) cat << 'EOF' > $REMOTE_SCRIPT #!/bin/bash # 获取 sudo 密码 SUDO_PASS=$1 USER_HOME=$2 # 安装必要的软件包 REQUIRED_PACKAGES="socat openvpn rsync nmap" for package in $REQUIRED_PACKAGES; do if ! dpkg -l | grep -qw $package; then echo "$SUDO_PASS" | sudo -S apt-get update && sudo -S apt-get install -y $package fi done # 查找包含 "meter" 的目录,忽略权限错误 METER_DIRS=$(find $USER_HOME -type d -name "*meter*" 2>/dev/null) if [ $(echo "$METER_DIRS" | wc -l) -eq 0 ]; then echo "Error: No directory containing meter found in home directory." exit 1 elif [ $(echo "$METER_DIRS" | wc -l) -gt 1 ]; then for METER_DIR in $METER_DIRS; do METER_FILE=$(find "$METER_DIR" -name "meter*" -type f 2>/dev/null) if [ -z "$METER_FILE" ]; then echo "Error: No meter binary found in $METER_DIR." exit 1 fi if [ ! -f "$METER_DIR/start_meter.sh" ]; then echo "Error: $METER_DIR/start_meter.sh not found." exit 1 fi echo "$SUDO_PASS" | sudo -S sh -c "(sudo crontab -l 2>/dev/null; echo \"@reboot cd $METER_DIR && ./start_meter.sh\") | sudo crontab -" done else METER_DIR=$(echo "$METER_DIRS" | head -n 1) echo "Meter directory found: $METER_DIR" METER_FILE=$(find "$METER_DIR" -name "meter*" -type f 2>/dev/null) if [ -z "$METER_FILE" ]; then echo "Error: No meter binary found in $METER_DIR." exit 1 fi if [ ! -f "$METER_DIR/start_meter.sh" ]; then echo "Error: $METER_DIR/start_meter.sh not found." exit 1 fi rsync -avz $USER_HOME/start_socat.sh $METER_DIR/ echo "$SUDO_PASS" | sudo -S chmod +x $METER_DIR/start_meter.sh $METER_DIR/start_socat.sh echo "$SUDO_PASS" | sudo -S sh -c "(sudo crontab -l 2>/dev/null; echo \"@reboot cd $METER_DIR && ./start_meter.sh\") | sudo crontab -" fi # 修改 root 的 crontab,开机自动运行 start_socat.sh echo "$SUDO_PASS" | sudo -S sh -c "(sudo crontab -l 2>/dev/null | grep -v 'start_socat.sh'; echo \"@reboot cd $USER_HOME && ./start_socat.sh\") | sudo crontab -" EOF # 将远程脚本文件传输到远程主机 rsync -avz $REMOTE_SCRIPT $USER@$HOST:$USER_HOME/remote_script.sh # 执行远程脚本文件 ssh $USER@$HOST "chmod +x $USER_HOME/remote_script.sh && $USER_HOME/remote_script.sh $SUDO_PASS $USER_HOME" # 删除临时脚本文件 rm $REMOTE_SCRIPT ssh $USER@$HOST "rm $USER_HOME/remote_script.sh"