shell 编程

开启关闭SSH

# 开启ssh
function disable_ssh() {
    sed -i "s/PasswordAuthentication yes/PasswordAuthentication no/g" /etc/ssh/sshd_config
    systemctl restart ssh
    w | grep sshd | awk '{print $2}' | while read one; do pkill -9 -t $one; done #退出当前登录的用户
    return 0
}

# 关闭ssh
function enable_ssh() {
    sed -i "s/#PermitRootLogin prohibit-password/PermitRootLogin yes/g" /etc/ssh/sshd_config
    sed -i "s/PasswordAuthentication no/PasswordAuthentication yes/g" /etc/ssh/sshd_config
    systemctl restart ssh
    return 0
}

修改当前用户登录密码

function change_passwd() {
    passwd=$1
    [[ -z "$passwd" ]] && return 0
    echo "$(whoami):$passwd" | /usr/sbin/chpasswd || true
    sync
    return 0
}

# usage: change_passwd pwd

shell 实现并发执行并且控制并发数量

#!/bin/bash
start_time=$(date +%s)             #定义脚本运行的开始时间
[ -e /tmp/fd1 ] || mkfifo /tmp/fd1 #创建有名管道
[ -e /tmp/fd2 ] || mkfifo /tmp/fd2
exec 3<>/tmp/fd1 #创建文件描述符,以可读(<)可写(>)的方式关联管道文件,这时候文件描述符3就有了有名管道文件的所有特性
exec 4<>/tmp/fd2
rm -rf /tmp/fd1 #关联后的文件描述符拥有管道文件的所有特性,所以这时候管道文件可以删除,我们留下文件描述符来用就可以了
rm -rf /tmp/fd2
for ((i = 1; i <= 10; i++)); do
    echo >&3 #&3代表引用文件描述符3,这条命令代表往管道里面放入了一个"令牌"
done

totalCount=0
failCount=0
mkfifo -m 777 npipe
rm -rf npipe
for ((i = 1; i <= 20; i++)); do
    read -u3 #代表从管道中读取一个令牌
    {
        sleep 1 #sleep 1用来模仿执行一条命令需要花费的时间(可以用真实命令来代替)
        if [[ $i -lt 10 ]]; then
            echo "fail $i" >&4
            echo 'fail'$i
        else
            echo "success $i" >&4 #输出到结果管理
            echo 'success'$i
        fi
        echo >&3 #代表我这一次命令执行到最后,把令牌放回管道
    } &
done
wait
#获取结果
for ((i = 1; i <= 20; i++)); do
    read s a <&4
    echo "s=$s,a=$a"
    if [[ $s == "success" ]]; then
        totalCount=$(($totalCount + 1))
    else
        failCount=$(($failCount + 1))
    fi
done

echo "totalCount:$totalCount,failCount:$failCount"

stop_time=$(date +%s) #定义脚本运行的结束时间

echo "TIME:$(expr $stop_time - $start_time)"
exec 3<&- #关闭文件描述符的读
exec 3>&- #关闭文件描述符的写
exec 4<&-
exec 4>&-

byte 格式化显示

function byte_format() {
    totalsize=$1
    if [[ "$totalsize" =~ ^[0-9]+$ ]]; then
        if [ 1024 -gt $totalsize ]; then
            size="$totalsize"B
        elif [ 1048576 -gt $totalsize ]; then
            size=$(echo "scale=3; a = $totalsize / 1024 ; if (length(a)==scale(a)) print 0;print a" | bc)
            size="$size"KB
        elif [ 1073741824 -gt $totalsize ]; then
            size=$(echo "scale=3; a = $totalsize / 1048576 ; if (length(a)==scale(a)) print 0;print a" | bc)
            size="$size"MB
        elif [ 1073741824 -le $totalsize ]; then
            size=$(echo "scale=3; a = $totalsize / 1073741824 ; if (length(a)==scale(a)) print 0;print a" | bc)
            size="$size"GB
        else
            size="0"
        fi
    else
        size="NULL"
    fi
    echo $size
}

你可能感兴趣的:(shell)