想配置一个远程关机的脚本,发现shell语法虽然简单,但用java之类的高级语言久了,还是要有很多注意的地方。
最终成功执行的脚本如下,简单几行:
#!bin/bash
ip_array=("192.168.137.70" "192.168.137.69" "192.168.137.68")
user="hadoop"
remote_cmd="sudo shutdown -h now"
for ip in ${ip_array[*]}
do
ssh -t $user@$ip $remote_cmd
done
需要注意的地方:
- 赋值语句“=”两边不能有空格,开启vim的语法检查也会发现如果有空格,变量都不会识别;
- shutdown关机命令前要加sudo
- ssh远程登录脚本要加-t参数,否则ssh没有tty
- 注意shell中数组的使用和遍历
shell脚本执行的两种方式:
- ./xxxx.sh 要有可执行权限与头部的#!/bin/bash
- sh xxxx.sh
参考链接:
http://blog.csdn.net/wzb56_earl/article/details/19935649
http://blog.csdn.net/mqf163/article/details/71524676