自动远程连接服务器,执行运维命令脚本

自动远程连接服务器,执行运维命令脚本

两个服务,服务a,服务b

  1. a服务生成密钥,上传到远程服务
1
2
ssh-keygen -t rsa -b 4096
ssh-copy-id root@47.107.226.36
  1. a服务编写shell脚本内容如下
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
#!/bin/bash

# 设置远程服务器的 IP 地址和用户名
REMOTE_IP="47.107.226.36"
REMOTE_USERNAME="root"

# 连接到远程服务器
ssh -o StrictHostKeyChecking=no "$REMOTE_USERNAME@$REMOTE_IP" << 'EOF'
# 确保 /root/yjb 目录存在
mkdir -p /opt/project/JUYUAN-AI-WEB-HTPPS/api/yjb

# 在 /root/yjb 目录下创建一个文本文件
output_file="/opt/project/JUYUAN-AI-WEB-HTPPS/api/yjb/output.txt"

# 写入内容到文件
echo "This is a test file created by the script aaa bbb ccc ddd." > "$output_file"

# 输出文件内容
if [ -f "$output_file" ]; then
cat "$output_file"
echo "File created successfully at $output_file"
else
echo "Error: Failed to create file $output_file"
exit 1
fi
EOF

# 检查 SSH 命令是否成功
if [ $? -eq 0 ]; then
echo "Script executed successfully on $REMOTE_IP"
else
echo "Error: Failed to connect or execute commands on $REMOTE_IP"
exit 1
fi

  1. 授予脚本执行权限
1
chmod 7777 a.sh
  1. 执行