Shell练习题

1.编写脚本for1.sh,使用for循环创建20账户,账户名前缀由用户从键盘输入,账户初始密码由用户输入,例如: test1、 test2、 test3、…test10

#!/bin/bash

read -p "前缀:" prefix
read -p "密码:" passwd

for((i=1;i<20;i++))
do
        user=$prefix$i
        if id $user &> /dev/null
        then
                echo "$user 已存在"
        else
                useradd $user
                if (($?==0))
                then
                        echo #$passwd"|passwd --stdin $suer &> /dev/null
                else
                        echo "用户创建失败"
                        exit
                fi
        fi
done

2.编写脚本for2.sh,使用for循环,通过ping命令测试网段的主机连通性,IP前3段由用户输入,如:输入192.168.48 ,则ping 192.168.48.125 - 192.168.48.135,将可以ping通的主机IP地址写入到/tmp/host_up.txt文件中,不能ping通的主机IP地址写入到:/tmp/host_down.txt文件中

#!/bin/bash

read -p "请输入网段:" ip

for((i=0;i<=10;i++))
do
        IP="$ip"."$i"
        if ping -c 2 -w 3 $IP &> /dev/null
        then
                echo "$IP is up" > /tmp/host_up.txt
        else
                echo "$IP is down" > /tmp/host_down.txt
        fi
done

echo "up ip:"
cat /tmp/host_up.txt

echo
echo "down ip:"
cat /tmp/host_down.txt

3.使用for循环实现批量主机root密码的修改
(1)打开多台主机
(2)使用ssh-keygen命令建立密钥对
(3)多台主机间通过ssh-copy-id进行免密登录
(4)编写脚本for3.sh,通过for循环登录主机修改对方root账户密码

[root@server ~]# ssh-keygen -t rsa 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:8PPUl2uIcS2jgtUWMRcpu0DXqxeE+Dqmwk+5ubA0QBE root@server
The key's randomart image is:

[root@server ~]# ssh-copy-id root@192.168.209.10
[root@server ~]# ssh-copy-id root@192.168.209.11

脚本

#!/bin/bash

read -p "请输入密码"

for i in `cat ip.txt`
do
        ssh $i "echo "$passswd"|passwd -stdin root"
done

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值