bash 通过脚本登录远程服务器并执行一组命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6239291/
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
Logging in via a script to a remote server and execute a set of commands
提问by emurad
How can I login to a remote server and execute a set of commands then when done logout and continue my script?
如何登录到远程服务器并执行一组命令,然后在完成注销并继续我的脚本?
Thanks.
谢谢。
回答by Louis Marascio
ssh can be used to execute a command, rather than start a remote interactive login shell. For example:
ssh 可用于执行命令,而不是启动远程交互式登录 shell。例如:
ssh user@host ls
Will log into host and execute the ls
command.
将登录到主机并执行ls
命令。
You can use this inside a bash script as normal:
您可以像往常一样在 bash 脚本中使用它:
#!/bin/bash
# do local commands
ssh user@host "ls; grep something file.txt; copy a b"
# do more local commands
From ssh's man page, the exit status will be the exit status of the remove command or 255 if an error occurred.
从 ssh 的手册页中,退出状态将是 remove 命令的退出状态,如果发生错误,则为 255。
回答by acolo
Small variation with easier code formatting using ssh
and bash -s
:
使用ssh
和更容易格式化代码的小变化bash -s
:
echo '
globchar="*"
ls -1d $globchar
ls -ld $globchar
' |
ssh user@host "bash -s --"
回答by David W.
As others have stated, you can use ssh
. However, if you're running a script, you may want to setup ssh
to login without a password. You can do that by setting up a public/private key via the ssh-keygencommand. Also change the permission of keyfiles (id_rsa, id_rsa.pub) as 600 for public key and 400 for private key for security of modification. chmod 600 id_rsa.pub ;chmod 400 id_rsa
正如其他人所说,您可以使用ssh
. 但是,如果您正在运行脚本,您可能希望设置ssh
为无需密码即可登录。您可以通过ssh-keygen命令设置公钥/私钥来实现。还要将密钥文件(id_rsa、id_rsa.pub)的权限更改为 600 公钥和 400 私钥,以确保修改安全。chmod 600 id_rsa.pub ;chmod 400 id_rsa
On your system, you run ssh-keygen
to generate the public and private keys. On Unix/Linux/Mac, these sit in the $HOME/.ssh
directory. (Keep the passphrase blank!). Then, you want to create a file called authorized_keys
on the remote machine under the $HOME/.ssh
directory and copy your public key there.There is no need of generating encryption keys on remote m/c.
在您的系统上,您运行ssh-keygen
以生成公钥和私钥。在 Unix/Linux/Mac 上,这些位于$HOME/.ssh
目录中。(保持密码为空!)。然后,您要authorized_keys
在$HOME/.ssh
目录下创建一个在远程机器上调用的文件,并将您的公钥复制到那里。不需要在远程m/c 上生成加密密钥。
Now, when you do ssh
or scp
to the remote machine, you don't have to give the password.
现在,当您执行ssh
或scp
访问远程机器时,您不必提供密码。