如何编写一个bash脚本,该脚本登录到另一台计算机上以做事?


11

是否可以编写bash脚本,

  1. 将从机器A启动,通过ssh登录到另一台机器B(机器A和B均为Linux-Machines),
  2. 将一些文件复制到机器B上
  3. 在这些计算机上运行给定python脚本的python脚本。
  4. 将结果传送回机器A
  5. 从机器B注销。

这在技术上可行吗?

Answers:


15

当然是可行的:

scp file user@host:
ssh user@host path_to_script
scp user@host:file_to_copy ./

就是这样...

但是有一个问题:系统将要求您输入三次密码。为避免这种情况,您可以生成ssh密钥并通过这些密钥授权用户。

要生成ssh密钥,请运行ssh-keygen -t rsa,回答问题,并将公共密钥复制到远程主机(计算机B)到~/.ssh/authorized_keys文件中。私钥应保存在~/.ssh/id_rsa本地计算机(A)上。


如果没有公开密钥选项,您可以做一些粗略的操作以最小化密码提示,例如cat file | ssh user@host 'cat > /destination/of/file; /path/to/script &>/dev/null; cat results' > /destination/of/results
Patrick

如果确实要使用密码,则始终可以通过定义ControlMaster=yes和来使用OpenSSH的连接池ControlPath=/path/to/socketfile,然后使用-f来启动一个ssh连接以运行后台ssh。告诉所有后续的SSH连接使用相同的套接字文件。
jsbillings 2012年

4

我可以在单个ssh连接/会话中完成所有操作:

ssh user@host "cat > remote_dst; command; cat remote_src" < local_src > local_dst

这个:

  1. 复制local_srcremote_dst
  2. 执行command
  3. 复制remote_srclocal_dst

但是如果commandstdout,结果也就在local_dst。如果command从中读取输入stdin,它将接收和EOF


3

虽然您可以在单个ssh会话中完成此操作,但是将复制文件与正在运行的命令结合起来有点棘手。

解决此任务的最简单方法是为三个操作运行单独的SSH会话:

rsync -a inputs/ machineB:inputs/
ssh machineB 'some command -i inputs -o outputs'
rsync -a machineB:outputs/ outputs/

这需要对machineB进行三次身份验证。避免多次认证的推荐方法是在现代版本的OpenSSH中使用连接共享工具:一次永久地建立与B的主连接,然后让SSH自动piggy带到该主连接上。在您的服务器上添加ControlMaster autoControlPath一行~/.ssh/config,然后在后台启动主连接,然后执行您的任务。

ssh -fN machineB                         # start a master connection in the background
# Subsequent connections will be slaves to the existing master connection
rsync -a inputs/ machineB:inputs/
ssh machineB 'some command -i inputs -o outputs'
rsync -a machineB:outputs/ outputs/

与其使用scp或rsync来复制文件,不如使用SSHFS挂载远程文件系统,可能会更容易。顺便说一下,这将有助于建立主连接(假设您已经~/.ssh/config按照上面的指示进行了设置)。

mkdir /net/machineB
sshfs machineB: /net/machineB
cp -Rp inputs /net/machineB/
ssh machibeB 'some command -i inputs -o outputs'
cp -Rp /net/machineB/outputs .
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.