来自服务器的 scp 文件来自 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16182190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:16:00  来源:igfitidea点击:

scp documents from server from inside Bash script

linuxbashshellscp

提问by Pradeep Pati

I normally use scplike so:

我通常这样使用scp

myUser@myMachine:~/myapp$ scp [email protected]:/path/to/bin/*.derp .
[email protected]'s password: ********
herp1.derp                                100%  732     0.7KB/s   00:00    
herp2.derp                                100%  215     0.2KB/s   00:00    
herp3.derp                                100%  682     0.7KB/s   00:00    
myUser@myMachine:~/myapp$

I now want to write a Bash script that, among other things, does this for me, but where the password is stored in the script, and the script doesn't query the user to enter it:

我现在想编写一个 Bash 脚本,除其他外,它为我执行此操作,但密码存储在脚本中,并且脚本不询问用户输入密码:

sh dostuff.sh

Just running that should scpall the *.derpfiles to the user's local directory.

刚运行那应该把scp所有的*.derp文件都放到用户的本地目录下。

So I ask: how can I supply the password to scpfrom inside my script?Thanks in advance!

所以我问:如何scp从我的脚本内部提供密码?提前致谢!

回答by Pradeep Pati

Instead of hardcoding password in a shell script, use SSH keys, its easier and secure.

使用 SSH 密钥,而不是在 shell 脚本中硬编码密码,它更容易和安全。

$ scp -i ~/.ssh/id_rsa [email protected]:/path/to/bin/*.derp .

assuming your private key is at ~/.ssh/id_rsa

假设你的私钥在 ~/.ssh/id_rsa

To generate a public / private key pair :

生成公钥/私钥对:

$ ssh-keygen -t rsa

The above will generate 2 files, ~/.ssh/id_rsa(private key) and ~/.ssh/id_rsa.pub(public key)

以上将生成2个文件,~/.ssh/id_rsa(私钥)和~/.ssh/id_rsa.pub(公钥)

To setup the SSH keys for usage (one time task) : Copy the contents of ~/.ssh/id_rsa.puband paste in a new line of ~devops/.ssh/authorized_keysin a new line in myserver.orgserver. If ~devops/.ssh/authorized_keysdoesn't exist, feel free to create it.

设置 SSH 密钥以供使用(一次性任务):复制内容~/.ssh/id_rsa.pub并粘贴~devops/.ssh/authorized_keysmyserver.org服务器中的新行中。如果~devops/.ssh/authorized_keys不存在,请随意创建它。

A lucid how-to guide is available here.

此处提供清晰的操作指南。