shell中使用ssh

  遇到一个场景,容器的日志以hostpath方式挂在到node的路径下。但是容器重启后会换到不同的node,查询历史日志就成了头疼的事情。

        我遇到的一个paas环境有70多个node,找历史日志要遍历这么多的node太难了。

       就尝试写一个脚本来找日志,效率还是高了很多。主要是沮丧感就没那么强烈了,不需要ssh到每个节点去找了,这有点low了。

       后续还要确定一下有没有,重启容器后到其他node时,有没有办法顺便删除或者转移持久卷。没有清理也是有问题的。

      下面的部分来自https://blog.csdn.net/jinking01/article/details/84386769

       前提是需要配置ssh免密码登陆,各节点间ssh不需要输入密码的。

#!/bin/bash
ssh user@remoteNode > /dev/null 2>&1 << eeooff
cd /home
touch abcdefg.txt
exit
eeooff
echo done! 

  远程执行的内容在“<< eeooff ” 至“ eeooff ”之间,在远程机器上的操作就位于其中,注意的点:

  1.  << eeooff,ssh后直到遇到eeooff这样的内容结束,eeooff可以随便修改成其他形式。
  2.  重定向目的在于不显示远程的输出了
  3.  在结束前,加exit退出远程节点

      下面部分来自:https://www.cnblogs.com/seasonsstory/p/3277473.html

       我没有这种方式,环境上并没有装expect。

  expect

  1.首先确认expect的包要安置。

  [root@localhost]$ rpm -qa | grep expect

  如果没有则需要下载安装,yum -y install expect expect-devel

  安装过后会显示:

  [root@localhost] rpm -qa | grep expect

  expect-5.43.0-5.1
  expect-devel-5.42.1-1

  2.查看expect的路径,可以用

  [root@localhost] which expect 

  /usr/bin/expect

  3.确定脚本有可执行权限

  chmod +x test.sh

  #!/usr/bin/expect   //这个expect的路径就是用which expect 查看的结果

  spawn ssh -l     远程主机的用户名 远程主机的ip地址    
  expect "password:"           //提示让输入密码
  send "远程主机的密码 "       
  interact                             //操作完成

  !

  另外需要注意的是:

  不能按照习惯来用sh test.sh来这行expect的程序,会提示找不到命令,如下:

  test.sh: line 2: spawn: command not found
  couldn't read file "password": no such file or directory
  test.sh: line 4: send: command not found
  test.sh: line 5: interact: command not found

 

  因为expect用的不是bash所以会报错。执行的时候直接./test.sh就可以了

原文地址:https://www.cnblogs.com/lnlvinso/p/12688122.html