ansible非root用户批量修改root密码

前言:

由于线上服务器密码长久没有更新,现领导要求批量更换密码。线上的之前部署过salt,但由于各种因素没有正常使用。

使用自动化工具批量修改的计划搁浅了,后来领导给了个python多线程修改密码脚本。但实际测试效果并不理想,会出现卡住情况

#!/usr/bin/python
import paramiko#ssh连接模块
import time,sys,re,os
import socket
import threading,Queue#线程模块

root_cmd = r'''
这里输入你要执行的命令
'''
user_cmd = r''' echo ''  '''
issu = 1 
root_pwd='你要修改的root密码'
login_user = '普通用户名'
key_file = '/home/.ssh/id_rsa'#普通用户key
sshport = 22#端口
time_out = 60 #超时时间
Numer_Thread = 300#最大线程数(根据主机数量修改)


q = Queue.Queue()#线程队列
socket.setdefaulttimeout(time_out)
lock = threading.RLock()#线程锁(同时只允许一个线程执行动作)
onlydir = dir()

def sshgo(host,rootuser,rootpwd):
    rtn = []
    key = paramiko.RSAKey.from_private_key_file(key_file)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()

    rtn.append('________________________________%s'%host)
    try:
        ssh.connect(host,sshport,login_user,pkey=key)
    except Exception,e:
        rtn.append('%s__ERROR_________________________%s'%(e,host))
        return rtn
    if 'user_cmd' in onlydir:
        stdin, stdout, stderr = ssh.exec_command('LANG=en_US.UTF-8;LANGUAGE=en_US.UTF-8; %s'%user_cmd)
        rtn.append(stdout.read() + stdout.read())
        #rtn.append(stdout.read() + stderr.read())
    if not issu:
            #return rtn
            return "",(rtn)
    shell = ssh.invoke_shell()
    while not shell.recv(4096).endswith(']$ '):
        time.sleep(0.1)

    buff  =''
    shell.send('LANG=en_US.UTF-8;LANGUAGE=en_US.UTF-8;su - %s'%rootuser)
    shell.send('
')
    while not buff.endswith('Password: '):
        time.sleep(0.1)
        resp = shell.recv(4096)
        buff += resp
        if buff.endswith('exist') or buff.endswith(']$ '):
            rtn.append('ERROR_SSH.RECV_____1________________%s'% resp)
            return rtn
    buff  =''
    shell.send(root_pwd)
    shell.send('
')
    while not buff.endswith(']# '):
        time.sleep(0.1)
        resp = shell.recv(4096)
        buff += resp
        if buff.endswith('password') or buff.endswith(']$ '):
            rtn.append('ERROR_SSH.RECV_____2________________%s'% resp)
            return rtn
    shell.send('LANG=en_US.UTF-8;LANGUAGE=en_US.UTF-8; %s '%root_cmd)
    shell.send('
')
    buff = ''
    while not buff.endswith(']# '):
        time.sleep(0.1)
        resp = shell.recv(4096)
        buff += resp
        if buff.endswith(']$ '):
            rtn.append('ERROR_SSH.RECV_____3________________%s'% resp)
            break
        elif buff.endswith('? '):
            rtn.append('ERROR_SSH.RECV_____4________________??')
            break
    #print buff
    #rtn= (''.join(rtn)).strip()+"  "+host
    rtn.append('
'.join(buff.split('
')[1:-1]))
    ssh.close()
     return "",(rtn)    
    #return rtn

def do_echo(host,rootuser,rootpwd):
    result = sshgo(host,rootuser,rootpwd)
    lock.acquire()
    for pp in result:
        print pp
    print
    sys.stdout.flush()
    lock.release()

def working():
    while 1:
        args = q.get()
        do_echo(args[0],args[1],args[2])
        q.task_done()

for i in range (Numer_Thread):
    t = threading.Thread(target=working)
    t.setDaemon(1)
    t.start()
print "Begin......" 
fn = open("/var/tmp/169" ,"r")
#fn = open("/tmp/1.log" ,"r")
for i in fn:
    if not re.match('#',i) and re.search('.',i):
        c = i.split()
        q_args = [c[0],'','']
        #q_args = [c[0],c[1],c[2]]
        q.put(q_args)
fn.close()
q.join()
python多线程修改root密码脚本
后来想到了不需要安装客户端的自动化管理工具:ansible 好吧那就查下相关资料吧

1.安装ansible

yum -y install ansible

2.修改主机配置文件

vim /etc/ansible/hosts
[web]#主机组
10.18.111.123 ansible_ssh_user=usernam ansible_ssh_private_key_file=/home/maintain/username/.ssh/id_rsa
192.168.1.1 ansible_become_pass='password' ansible_ssh_user=username  ansible_ssh_private_key_file=/home/maintain/username/.ssh/id_rsa

配置得了root密码,及普通用户和相应的key,这样做其实并不理想,1:不安全2:配置复杂点。后续可以使用ansible的playbook实现

2.切换普通用户执行命令

ansible web -S -R root -m raw -a 'echo '需要修改的root密码' | passwd --stdin root'
 

3.playbook版本

 

这脚本参照网上的脚本修改的,但没生效。期待大牛的完善。

参考链接:

http://zylhz.com/?p=107

原文地址:https://www.cnblogs.com/zhanmeiliang/p/6197762.html