1. 程式人生 > 實用技巧 >shell通過ssh批量修改centos密碼

shell通過ssh批量修改centos密碼

環境:centos7

思路:ssh與要修改密碼免密。指令碼讀取文字中ip地址,然後遠端修改密碼,並將密碼放入文字中。

1、準備ip地址文字

[root@186 ~]# cat ip
100.98.100.186
100.98.100.188

2、編寫批量修改密碼指令碼

[root@186 ~]# more change-passwd.sh 
#!/bin/bash
source /etc/profile
#人機互動是否執行批量修改密碼
while true;do
        stty -icanon min 0 time 100
        echo -n "Automatic execute ten seconds after,Are you sure you want to start the task(yes or no)?"
        read Arg
        case $Arg in
                Y|y|YES|yes)
                  break;;
                N|n|NO|no)
                  exit;;
                "")  #Autocontinue
                  break;;
        esac
done

#讀取ip地址使用隨機數作為密碼修改root密碼輸入到檔案ma.txt中
for ip in `cat ip`
    do
      p=`< /dev/urandom tr -dc 0-9-A-Z-a-z-/|head -c ${1:-10};echo`
      echo $p
      echo $ip
      ssh $ip "echo $p|passwd --stdin root"
      if [ $? = '0' ]
        then 
          echo $ip密碼$p >> ma.txt
        else
          echo 'faild'
      fi
    done

3、賦權並執行

[root@186 ~]# chmod u+x change-passwd.sh 
[root@186 ~]# ./change-passwd.sh 
Automatic execute ten seconds after,Are you sure you want to start the task(yes or no)?yes
zYUkJJNxEr
100.98.100.186
Changing password for user root.
passwd: all authentication tokens updated successfully.
42trLHphkA
100.98.100.188
Changing password for user root.
passwd: all authentication tokens updated successfully.
[root@186 ~]# cat ma.txt 
100.98.100.186密碼zYUkJJNxEr
100.98.100.188密碼42trLHphkA