是在本地生成一个SSH key,并将其传输到远程服务器,然后在远程服务器上执行一个特定的命令,并将执行结果输出到一个指定的结果文件中。在输出结果前后都加入了当前时间信息,以便于在不同的执行时间点进行区分和对比。这个脚本通常用于快速搭建测试和开发环境。
确保整个远程命令都执行成功,可以在远程命令中加入 set -e命令开启 bash 的错误处理机制,保证在执行远程命令过程中任何错误都会导致远程命令退出并返回非零的退出代码。然后可以根据远程执行命令的退出代码进行判断,以此输出相应的成功或失败信息。同时,确保远程执行命令的路径是存在的,否则还是会报错找不到目录。
#!/bin/bash
# 远程操作服务器B的IP地址
remote_host="192.168.x.x"
# 远程操作服务器B的用户
remote_user="root"
# 定义结果文件路径
result_file="./result_$(date "+%Y-%m-%d_%H-%M-%S").log"
# 生成SSH公钥
generate_ssh_key() {
if [ ! -f ~/.ssh/id_rsa.pub ]; then
echo "Generating SSH key..."
ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa
else
echo "SSH key already exists, skipping..."
fi
}
# 传输SSH公钥到远程服务器
copy_ssh_key() {
echo "Copying SSH key to remote server ..."
ssh-copy-id -i ~/.ssh/id_rsa.pub "${remote_user}@${remote_host}"
ssh_copy_result=$?
if [ $ssh_copy_result -eq 0 ]; then
echo "SSH key added successfully!"
else
echo "Failed to add SSH key, error code: $ssh_copy_result"
exit 1
fi
}
# 生成SSH公钥并传输到远程服务器
generate_and_copy_ssh_key() {
generate_ssh_key
copy_ssh_key
}
# 执行远程命令
remote_command="set -e && mkdir -p /to/directory1 && touch /to/directory1/file.txt "
# 生成SSH公钥并传输到远程服务器
generate_and_copy_ssh_key
# 将输出结果同时输出到前台和结果文件中
{
echo -e "\n\n========== $(date "+%Y-%m-%d %H:%M:%S") ==========\n"
echo "SSH key generation and copy result:"
cat ~/.ssh/id_rsa.pub ~/.ssh/id_rsa || echo "No SSH key files found."
ssh "${remote_user}@${remote_host}" "${remote_command}" 2>&1 | tee -a "$result_file"
remote_exec_result=${PIPESTATUS[0]}
if [ $remote_exec_result -eq 0 ]; then
echo "Remote command execution succeeded."
else
echo "Remote command execution failed. Please check the result file for details."
fi
echo -e "\n\n"
}