简体   繁体   English

使用带有if语句的ssh命令的Shell脚本

[英]Shell script with ssh command with an if statement

I want to write a shell script to do the following: 我想编写一个shell脚本来执行以下操作:

  1. login some remote machines, say host1 and host2, each at a time 一次登录一些远程计算机,例如host1和host2
  2. go to the /tmp directory and check whether a particular directory named 'dirname' exists or not. 转到/ tmp目录,并检查是否存在名为“ dirname”的特定目录。 If it doesn't exist, make a directory 'dirname' 如果不存在,请创建目录“ dirname”
  3. go to the directory /tmp/dirname 转到目录/ tmp / dirname
  4. copy a file with a variable runNo from the local machine to this directory 将具有变量runNo的文件从本地计算机复制到此目录

I tried something like this, but it doesn't work.. any help would be much appreciated. 我尝试过类似的方法,但是它不起作用..任何帮助将不胜感激。 Thanks! 谢谢!

#! /bin/bash
dir1=dirname
runNo=0

for i in 1 2
do
  runNo=$(($runNo+1))
  echo "host$i runNo$runNo"

  ssh host$i "cd /tmp;
    if [ -d $dir1 ]; then
      cd $dir1;
    else
      mkdir $dir1;
      cd $dir1;
    fi;
    cp ~/local/file$runNo file"

  echo "done"
done

How about 怎么样

ssh host$i "mkdir -p /tmp/$dir1"
scp ~/local/file$runNo host$i:/tmp/$dir1/file

mkdir -p suppresses errors if the directory already exists. 如果该目录已存在,则mkdir -p抑制错误。

Like this perhaps? 也许这样?

runNo=1
for h in host1 host2; do
    cat ~/local/file$runNo |
    ssh "$h" 'mkdir -p /tmp/dirname; cat >/tmp/dirname/file'
    runNo=$(($runNo+1))
done

If I interpret your description correctly, the cd is superfluous. 如果我正确解释了您的描述,则该cd是多余的。

If Bourne shell compatibility is necessary, you can replace the increment with 如果需要Bourne shell兼容性,则可以将增量替换为

    runNo=$(expr $runNo + 1)

Try this: 尝试这个:

ssh -t -t host$i <<eod1
echo "your command goes here"
add eod1 to terminate your ssh
eod1

Note two -t -t is required to overwrite the sudo terminal error 注意两个-t -t是覆盖sudo终端错误的必要条件

this editing rules is driving me crazy 这个编辑规则让我发疯

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

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