![](/img/trans.png)
[英]Shell Script to SSH to Multiple Remote Machines and Leave a Command Running
[英]shell script to ssh remote machines and print the output of the top command
我想写一个shell脚本来做以下四件事:
我试过这个:
#! /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),但是对于像host1-4这样的早期机器人来说它是空白的。 如果我尝试没有“echo”主机$ i“>>〜/ mysh / top_out”,我可以得到所有host1-8的最高输出。
当你这样做
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
你可以尝试一个expect脚本来保存每个主机连接后的输出,你也可以添加更多的命令,ps:这假设你拥有所有主机的相同用户名和密码:
#/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
}
检查未获得输出的主机是否显示以下错误:
未设置TERM环境变量。
如果您为某些主机收到此错误,可以尝试以下命令:
ssh user @ host“screen -r; top”>> file_where_you_want_to_save_output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.