如何在Bash脚本中将密码传递给ssh/scp命令

时间:2019-05-19 01:26:25  来源:igfitidea点击:

sshpass是一个有用的工具,用于在非交互模式下运行ssh身份验证。使用sshpass,我们可以使用ssh或scp命令的密码,而无需交互,这有助于在shell脚本中加以利用。我们建议使用基于密钥的身份验证,而不是使用此方法。

安装sshpass

sshpass包在大多数最新操作系统的默认包存储库中可用。我们可以使用以下命令将其安装到系统上。

在Debian上:

sudo apt install sshpass

在CentOS上:

yum --enablerepo=epel -y install sshpass

使用sshpass

sshpass使用SSHPASS环境变量存储用户密码。我们需要首先使用带密码的SSHPASS变量,然后使用此命令。下面是一个使用sshpass的简单shell脚本。

export SSHPASS=ry3AvbWO0oupYX9HCMzp0Axx

sshpass -e scp testfile.csv [email protected]:/uploads/

我们还可以使用sshpass运行ssh命令,如下所示。

sshpass -e ssh [email protected]