shell5(进度条、主机在线测试、免密登录)

1、显示进度条

#!/bin/bash
# 编写脚本,显示进度条
myProgress(){
while :
do
   	echo -n '#'
 
   	sleep 0.2
done
}
myProgress &
cp -a $1 $2
killall $0
echo "拷贝完成"

 2、编写脚本测试 192.168.4.0/24 整个网段主机的开关机状态

多进程版

#!/bin/bash
# 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机
# 状态(多进程版)
 
#定义一个函数,ping 某一台主机,并检测主机的存活状态
myping(){
ping ‐c 2 ‐i 0.3 ‐W 1 $1  &>/dev/null
if  [ $? -eq 0 ];then
	echo "$1 is up"
else
	echo "$1 is down"
fi
}
for i in {1..254}
do
   	myping 192.168.4.$i &
done
# 使用&符号,将执行的函数放入后台执行
# 这样做的好处是不需要等待ping第一台主机的回应,就可以继续并发ping第二台主机,依次类推

在线和离线主机输出到文件

#!/bin/bash

ping_success_status() {
if ping -c 1 $IP >> /dev/null; then
echo "$IP is on" >> /root/success-host.txt
continue
fi
}

success=/root/success-host.txt
failure=/root/failure-host.txt

rm -rf $success
rm -rf $failure

if [[ ! -f  $success ]];then
touch  /root/success-host.txt  && chmod 777 /root/success-host.txt
echo "$success 文件创建成功"
else
echo "$success 文件已经存在"
fi

if [[ ! -f  $failure ]];then
touch  /root/failure-host.txt && chmod 777 /root/failure-host.txt
echo "$failure 文件创建成功"
else
echo "$failure 文件已经存在"
fi

for IP in `echo 10.1.1.{1..254}`
do
{ ping_success_status
echo "$IP  is off!" >> /root/failure-host.txt
} &
done
wait

echo "在线主机数如下:" && cat /root/success-host.txt  | wc -l
#cat /root/success-host.txt

echo "离线主机数如下:" && cat /root/failure-host.txt  | wc -l
#cat /root/failure-host.txt

while版

#!/bin/bash
# 编写脚本测试 192.168.4.0/24 整个网段中哪些主机处于开机状态,哪些主机处于关机
# 状态(while 版本) 
i=1
while [ $i -le 254 ]
do
   	ping ‐c 2 ‐i 0.3 ‐W 1 192.168.4.$i  &>/dev/null
   	if  [ $? -eq 0 ];then
       	echo "192.168.4.$i is up"
    else
       	echo  "192.168.4.$i is down"
   	fi
   	let i++
done

3、免密登录

先准备一个主机文件

vim ip.txt
192.66.66.101
192.66.66.102
192.66.66.103
192.66.66.104

上述假设上述主机密码都相同且都是 1

#!/usr/bin/bash

get_keygen(){
/usr/bin/expct <<-EOF &>/dev/null
spawn  ssh-keygen
expect {

		".ssh/id_rsa):"  { send "\r"; exp_continue }
		"Overwrite (y/n)?" { send "y\r"; exp_continue }
		"no passphrase):"  { send "\r"; exp_continue }
		"passphrase again:"  {  send "\r" };

}
	interact
	expect eof
	EOF
}
send_key(){
/usr/bin/expct <<-EOF &>/dev/null
spawn  ssh-copy-id -i  $ip
expect {
		"connecting (yes/no)?"  { send "yes\r"; exp_continue}
		"password:"		{ send "1\r"}


}
	interact
	expect eof
EOF
}
echo "正在制作密钥"
echo "存放的ip的文件是ip.txt,对方密码是必须是1"
sleep 5

get_keygen
for ip  in $(cat ./ip.txt)
do 
	send_key $ip
	echo "$ip,密钥发送成功"
done

  

 

posted @ 2020-07-14 00:08  凡人半睁眼  阅读(272)  评论(0编辑  收藏  举报