2014-01-06 134 views
6

我想写一个shell脚本来做到以下四件事情:shell脚本SSH远程计算机并打印top命令的输出

  1. SSH远程机器(说hosti)
  2. 打印机名称到一个文件(top_out)
  3. 打印的“顶部”命令的输出到同一文件的前几行按照在步骤2
  4. 重复1-3的其他机器

我尝试这样做:

#! /bin/bash 

for i in 1 2 3 4 5 6 7 8 

do 
    echo "host$i" >> ~/mysh/top_out 
    ssh host$i "top -n1 -b | head -n 15>> ~/mysh/top_out" 
    echo "done" 
done 

,我得到了保存一些机器上输出(说像host5-8)输出文件,但它是空白的,争取早日machinessay像host1-4。如果我尝试不使用“echo”主机$ i“>>〜/ mysh/top_out”这一行,我可以得到所有host1-8的最高输出。

+0

最好的,包括在你的脚本的顶部为“零”出该文件每次运行(至少在测试),也就是'回声> 〜/ mysh/top_out'。祝你好运。 – shellter

+0

你需要改变这个:'ssh host $ i“top -n1 -b | head -n 15 >>〜/ mysh/top_out”'to this:'ssh host $ i“top -n1 -b | head - “〜〜/ mysh/top_out”,即'〜〜/ mysh/top_out'需要在引号之外。 – bluesmoon

+0

文件〜/ mysh/top_out需要驻留在host1-htos8中,还是应该驻留在执行ssh的本地主机中? – alvits

回答

6

当你

ssh host$i "top -n1 -b | head -n 15>> ~/mysh/top_out" 

你的远程主机,而不是在本地计算机上,并将输出写入~/mysh/top_out。远程主机可能没有使用与本地计算机相同的物理主目录。如果你的NFS或某些机器上共享你的主目录,但不是全部,那么你会看到你描述的症状。

尝试做

ssh host$i "top -n1 -b | head -n 15" >> ~/mysh/top_out 

代替,或使事情稍微干净,甚至

#!/bin/bash 

for i in $(seq 1 8); do 
    (echo "host$i" 
    ssh host$i "top -n1 -b | head -n 15") >> ~/mysh/top_out 
    echo "done host$i" 
done 
+0

这个工程!谢谢。 – user3154564

0

检查主机你没有得到的输出显示以下错误,其中:

TERM environment variable not set.

如果某些主机出现此错误,您可以尝试以下命令:

ssh [email protected] "screen -r; top" >> file_where_you_want_to_save_output

2

您可以尝试一个expect脚本来保存每个主机连接到它后的输出,您也可以为它添加更多的命令,p.s. :这里假设你有所有主机的相同用户名和密码:

#/usr/bin/expect -f 

#write your hosts on a new line inside a file and save it in your workging directory as: 

#host 1 
#host 2 
#host 3 

#user '' for password if it contains special chars 
#pass arguments to the script as ./script $username '$password' $hosttxt 
set user [lindex $argv 0] 
set pass [lindex $argv 1] 
#pass path to txt file with line separated hosts 
set fhost [lindex $argv 2] 
#set this to the path where you need to save the output e.g /home/user/output.txt 
set wd "/home/$user/log.txt" 
#open hosts file for parsing 
set fhosts [open $fhost r] 
exec clear 
#set loguser 1 

proc get_top {filename line user pass} { 
    spawn ssh -l $user $line 
     expect { 
      "$ " {} 
     "(yes/no)? " { 
      send "yes\r" 
      expect -re "assword:|assword: " 
      send "$pass\r" 
     } 
    -re "assword:|assword: " { 
      send "$pass\r" 
     } 
    default { 
     send_user "Login failed\n" 
    exit 1 
    } 
    } 
    expect "$ " {} 
    send "top -n1 -b | head -n 15\r" 
    expect -re "\r\n(.*)\r(.*)(\\\$ |#)" { 
     set outcome "$expect_out(1,string)\r" 
     send "\r" 
    } 

    puts $filename "$outcome\n\n-------\n" 
} 


while {[gets $fhosts line] !=-1} { 
     set filename [open $wd "a+"] 
     get_top $filename $line $user $pass 
     close $filename 
} 
相关问题