场景:服务器:A、B 和 C(全部 linux)
文件:文件.txt
现在我需要使用 SCP 将文件从服务器 A 发送到 B&C,但我只需输入密码和文件名一次。
需要知道如何实现它。
尝试过sshpass
,但似乎未安装,我无法安装它:(
sshpass:command not found
使用的密码:(这里每次都需要输入密码)
#!/bin/bash
echo "Enter Package Name:\c"
read package
package1="$package"
echo
scp ${package1} User@ServerB:/tmp/
scp ${package1} User@ServerC:/tmp/
答案1
您可以像这样删除“密码”请求。在包含该文件的 PC(服务器 A)上,在终端中键入:
ssh-keygen -t rsa -b 2048
Enter file in which to save the key (/<user>/.ssh/id_rsa): [Hit Enter]
Enter passphrase (empty for no passphrase): [Hit Enter]
Enter same passphrase again: [Hit Enter]
Your identification has been saved in /<user>/.ssh/id_rsa.
Your public key has been saved in /<user>/.ssh/id_rsa.pub.
然后您需要复制/<user>/.ssh/id_rsa.pub
到服务器B和C。在服务器B和C上,执行以下操作。注意:mkdir -p ~/.ssh
可能不需要。
mkdir -p ~/.ssh
cat id_rsa.pub >> ~/.ssh/authorized_keys
rm id_rsa.pub
现在您无需密码即可从服务器 A 连接到 B 和 C。例如,您的脚本现在将非常简单(通过基本文件检查):
#!/bin/sh
ask () {
echo -n "Enter Package Name: "
read package
if [ ! -f "$package" ]
then
echo "
${package} is not a file. Try again.
"
ask
else
upload "$package"
fi
}
upload () {
echo "put \"$1\" \"/tmp/$1\" > sftp.cmd
sftp User@serverB < sftp.cmd
sftp User@serverC < sftp.cmd
rm -f sftp.cmd
}
ask
exit