繁体   English   中英

如何在Shell Script中制作scp要求我输入密码

[英]How to make scp in Shell Script ask me for password

我正在编写一个脚本,以通过scp在两台计算机之间安全地传输数据。

但是在脚本中,由于没有密码,因此显示错误。 那么执行scp命令后,如何使我的shell脚本要求我输入密码?

这是我的csh脚本。

# ssh shahk@sj-shahk
# ls -al
echo "Source Location of Remote Server - $1"
echo "Destination Location of Local Server - $2"
echo "File/Folder to be Transferred from Remote Server - $3"

echo "File Transfer Starts"
scp -rv $1/$3 <username>@<hostname>:$2
echo "File Transfer Completed"

# exit

现在,我通过以下方式将上述脚本与ssh一起使用。

ssh <username>@<hostname> "<script name> <args>"

当我以上述方式使用时,执行scp命令时不会提示输入密码。

您可以使用sshpass https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/

我曾经用它直接输入scp或ssh而不提示输入密码。

例如 :

 sshpass -p 'password' scp file.tar.gz root@xxx.xxx.xxx.194:/backup

正如另一个答案所提到的那样, sshpass将完美地完成这项工作。 如果您无法在本地计算机上安装新软件包,则也可以使用expect (大多数发行版中默认安装)来自动执行交互式会话。

Expect的基本语法是等待程序显示特定的字符串( expect mystring ),这会触发特定的行为( send command

以下脚本显示了实现所需内容的基本结构:

#!/usr/bin/expect -f
# syntax to specify which command to monitor
spawn scp myfile user@remote.host:/dest_folder

# this syntax means we expect the spawned program to display "password: "
# expect can understand regex and glob as well. read the man page for more details
expect "password: "

# the \r is needed to submit the command
send "PASSWORD\r"

# expect "$ " means we wait for anything to be written.
# change if you want to handle incorrect passwords
expect "$ "
send "other_command_to_execute_on_remote\r"
expect "$ "
send "exit\r"

附带说明,您还可以通过ssh密钥设置无密码授权。

#1) create a new ssh key on your local computer
> ssh-keygen -t rsa
#2) copy your public key to your remote server
# you will need to login, but only once. Once the key is on the remote server, you'll be able to connect without password.
> ssh-copy-id -i ~/.ssh/id_rsa.pub user@ip_machine
# OR
> cat ~/.ssh/id_rsa.pub | ssh user@ip_machine "cat - >> ~/.ssh/authorized_keys"

本教程说明了如何使用keychain工具来管理多个ssh密钥和用户。

ssh <username>@<hostname> "<script name> <args>"

scp将仅从TTY中读取密码,在这种情况下,它没有TTY。 当您运行ssh并指定要在远程系统上执行的命令时(如您在此处所做的那样),默认情况下ssh不会在远程系统上分配PTY(伪tty)。 您的脚本以及从中启动的所有命令(包括scp最终都可以在没有TTY的情况下运行。

您可以使用ssh -t选项使其在远程系统上分配一个tty:

ssh -t <username>@<hostname> "<script name> <args>"

如果收到类似“因为stdin不是终端,将不会分配伪终端”的消息,请添加另一个-t

ssh -tt <username>@<hostname> "<script name> <args>"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM