[Shell] Linux主机密码批量回收 脚本

 

需求:每月末定时回收主机密码,但是规定我堡垒机与各主机不能做公钥,只能明文。。。本来准备用python paramiko 模块做的,但是还是没弄好,就先用shell吧。。。有的地方写的比较挫。。

 

scp_shell.sh

#!/usr/bin/expect

#author: yifangyou

#create time:2011-05-17

set scphost "[lindex $argv 0]"

set port "[lindex $argv 1]"

set scpuser "[lindex $argv 2]"

set scppw "[lindex $argv 3]"

#要执行的shell命令

set cmd "[lindex $argv 4]"

spawn ssh -p $port $scpuser@$scphost "$cmd"

set timeout 100

expect {

#respose: "[email protected]'s password:"

"*assword*" {

set timeout 30

send "$scppw\r"

}

#the first connect will respose "Are you sure you want to continue connecting (yes/no)? yes"

"*yes*" {

set timeout 100

send "yes\r"

set timeout 100

expect "*assword*"

set timeout 100

send "$scppw\r"

}

busy {send_user "\n";exit 1;}

failed {send_user "\n";exit 2;}

timeout {send_user "\n";exit 3;}

}

#Permission denied not try again

expect {

"*denied*" {

send_user "\n"

exit 4

}

busy {send_user "\n";exit 5;}

failed {send_user "\n";exit 6;}

timeout {send_user "\n";exit 7;}

}

exit 0

 

 

passroot.sh

#!/bin/bash

tmp_usr=root

dir=/usr/sh/shell/linux/password/root_pass_smredhat_20170901

dir1=scp_shell.sh

data1=$(date +%Y%m%d)

dir2="/usr/sh/shell/linux/log/pass_root_smredhat_$data1.log"

echo "Begin! $(date +%Y%m%d-%T)" >> $dir2

more "$dir" | while read line

do

  randroot=`cat /dev/urandom | tr -dc "a-eA-E0-5_\~\#\%\&\."| fold -w 10 | head -n 1` # 生成随机数密码

  tmp_ip=`echo $line | awk '{print $1}'`

  tmp_cmd="echo '"$randroot"' | passwd --stdin root && echo yes"

  tmp_pwd=`echo $line | awk '{print $3}'`

  echo -e "$tmp_ip\troot\t$randroot" >> /usr/sh/shell/linux/password/root_pass_smredhat_$data1

 /usr/bin/expect $dir1 $tmp_ip 22 $tmp_usr "$tmp_pwd" "$tmp_cmd" >> $dir2      # 传参,ipportuserold-passwdcmd

done

echo "End! $(date +%Y%m%d-%T)" >> $dir2

tol_num=`more $dir2 | awk '{print $1}' | grep yes | wc -l`

echo "$tol_num" >> $dir2


Over ~

你可能感兴趣的:(【脚本语言】,----,Shell)