Linux报错:“/bin/bash^M: 坏的解释器
原因是linux下的文件,在windows下面编辑过。在win下编辑的时候,换行结尾是\n\r , 而在linux下 是\n
解决方法,将文件里面的内容做替换即可
sed -i 's/\r$//' build.sh
免密登录
#!/bin/bash
#ssh免密登录shell脚本
#配置免密登录的所有机子都要运行该脚本
#修改/etc/ssh/sshd_config配置文件
#sed -i 's/被替换的内容/替换成的内容/' /配置文件地址
#sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config
#cat >> /etc/ssh/sshd_config <<EOF
#RSAAuthentication yes
#EOF
yum install expect #安装expect
echo "按enter键3次即可"
ssh-keygen -t rsa #生成秘钥(按enter键3次即可生成)
SERVERS="spark12 spark13 spark14" #需要配置的主机名
PASSWORD=123 #需要配置的主机登录密码
#将本机生成的公钥复制到其他机子上
#如果(yes/no)则自动选择yes继续下一步
#如果password:怎自动将PASSWORD写在后面继续下一步
auto_ssh_copy_id(){
expect -c "set timeout -1;
spawn ssh-copy-id $1;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*password:* {send -- $2\r;exp_continue;}
eof {exit 0;}
}";
}
ssh_copy_id_to_all(){
for SERVER in $SERVERS #遍历要发送到各个主机的ip
do
auto_ssh_copy_id $SERVER $PASSWORD
done
}
ssh_copy_id_to_all
分发文件
#!/bin/bash
#查出参数个数
pcount=$#
if((pount<1)) ; then
echo no args;
exit;
fi
#取出第一个参数
p1=$1;
fname=`basename $p1`
#echo fname=$fname;
#取出文件的绝对路径
pdir=`cd -P $(dirname $p1) ; pwd`
cuser=`whoami`
#for((host=100;host<102;host=host+1)); do
#echo ---------- s$host -------------
#rsync -rvl $pdir/$fname $cuser@s$host:$pdir
#done
start_x(){
for SERVER in $SERVERS #遍历要发送到各个主机的ip
do
rsync -rvl $pdir/$fname $SERVER:$pdir
done
}
start_x
命令分发
#!/bin/bash
if [ "$#" -ne 2 ] ; then
echo "USAGE: $0 -f server_list_file cmd"
exit -1
fi
file_name=$1
cmd_str=$2
cwd=$(pwd)
cd $cwd
serverlist_file="$cwd/$file_name"
if [ ! -e $serverlist_file ] ; then
echo 'server.list not exist';
exit 0
fi
while read line
do
#echo $line
if [ -n "$line" ] ; then
echo "DOING--->>>>>" $line "<<<<<<<"
ssh $line $cmd_str < /dev/null > /dev/null
if [ $? -eq 0 ] ; then
echo "$cmd_str done!"
else
echo "error: " $?
fi
fi
done < $serverlist_file
使用方法:
1. 新建一个文件host_file_list,文件中为服务器的地址,每个一行;
2. 保存上面shell 脚本, 如保存为 allcmd.sh,注意使用 chmod +x allcmd.sh 使之成为可执行脚本;
3. 运行 allcmd.sh host_file_list md 即可, host_file_list 是第1步的文件名(记得和 allcmd.sh 放在相同目录下), cmd 就是要执行的命令,用单引号包起来,例如:删除/home/nuaazdh/下面的一个 tmp.txt 文件: allcmd.sh host_file_list 'rm /home/nuaazdh/tmp.txt'
4. done!