手机版
你好,游客 登录 注册
背景:
阅读新闻

Linux集群批量执行命令

[日期:2017-12-18] 来源:Linux社区  作者:wxshi [字体:大 中 小]

因为工作需要,需要修改集群中机器的配置,一台一台的修改太浪费时间,就想能不能通过自动化脚本批量执行命令,尝试写一个,自己shell不熟悉,写的有点肤浅,请见谅。

if [ "$#" -ne 2 ];then
    echo "USAGE:$0 -f host_file cmd"
    exit -1
fi

file_name=$1
cmds=$2
filepath=$(cd `dirname $0`; pwd)
host_file="$filepath/$file_name"

if [ ! -e $host_file ];then
    echo "$host_file not exit;"
    exit 0
fi

cat $host_file | while read line
do
    echo $line>>result
    ssh -n -p3600 $line source ~/.bash_profile;$cmds >> result
    #"source ~/.bash_profile;$cmds" > result
    if [ $? -eq 0 ] ; then
       echo "host:$line,$cmds done!"                      
    else
       echo "host:$line error: " $?                          
    fi
done

执行方式xxxx.sh host_file ‘cmd’
其中xxx.sh是脚本名称,host_file是需要操作机器的ip地址列表,需要可以免密码登陆;cmd是需要操作的命令,如果命令之间存在空格,则需要用引号包起来。
note:

  • 1.ssh和cmd需要写在同一行
  • 2.ssh -n使用本地作为标准输入
Redirects stdin from /dev/null (actually, prevents reading from stdin).  This must be used when ssh is run in the background.  A common trick is to use this to run X11 programs on a remote machine.  For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel.  The ssh program will be put in the background.  (This does not work if ssh needs to  ask for a password or passphrase; see also the -f option.)

本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-12/149556.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款