我有 2 台 Solaris 服务器。我想编写一个 shell 脚本,它将文件从一台服务器复制到另一台服务器。
scp /tmp/test/a.war [email protected]:/tmp/
在 PUTTY 中执行上述命令时,将要求我输入目标的密码。使用 PUTTY 时这很好。
如何通过shell脚本运行
scp
命令时输入密码?
提前致谢
您必须设置 SSH 私钥/公钥。
生成后,将公钥行条目放在目标服务器和用户的 ~/.ssh/authorized_keys 文件中。
确保源计算机上的文件(对于将运行 scp/ssh 命令的用户)将具有建议的文件权限 (400)。
http://docs.oracle.com/cd/E19253-01/816-4557/sshuser-33/index.html或类似的在线帮助可以帮助您。
#!/bin/bash
# Check if the input file exists
input_file="input.txt"
if [ ! -f "$input_file" ]; then
echo "Error: Input file '$input_file' not found."
exit 1
fi
# Read remote server IP and destination path from the input file
remote_server_ip=$(awk -F'=' '/^REMOTE_SERVER_IP=/ {print $2}'
"$input_file")
destination_path=$(awk -F'=' '/^DESTINATION_PATH=/ {print $2}'
"$input_file")
# Check if remote server IP and destination path are provided
if [ -z "$remote_server_ip" ] || [ -z "$destination_path" ]; then
echo "Error: Remote server IP or destination path not provided in
the input file."
exit 1
fi
# List of files to copy
files_to_copy=("file1.txt" "file2.txt" "file3.txt")
# Output file to log the copied files
output_file="copied_files.log"
# Copy files to the remote server using scp and log the details to
the output file
for file in "${files_to_copy[@]}"; do
# Check if the file exists in the destination folder
ssh "$remote_server_ip" "[ -e \"$destination_path/$file\" ]"
if [ $? -eq 0 ]; then
echo "File '$file' already exists in
'$remote_server_ip:$destination_path'. Not copied." >>
"$output_file"
else
scp "$file" "$remote_server_ip":"$destination_path"
if [ $? -eq 0 ]; then
echo "File '$file' copied successfully to
'$remote_server_ip:$destination_path'." >> "$output_file"
else
echo "Error: Failed to copy '$file' to
'$remote_server_ip:$destination_path'." >> "$output_file"
fi
fi
done
echo "Copying process completed. Details logged in '$output_file'."