python批量修改centos账户密码

服务器要求每隔1个月就要修改一次密码,但是由于服务器较多,导致重复工作。所以写个python脚本来自动化完成该操作,具体思路:

1.由于服务器禁止超管直接登录,所以需要借助其他账号先连接服务器
2.连接到服务器上之后,执行命令切换到超管账号,并录入超管密码,从而将身份切换到超管
3.在超管角色下,执行命令修改密码即可
import paramiko as paramiko
from colorama import Fore

def recv_all(shell):
    result = ''
    while not (result.endswith(':') or result.endswith(': ') or result.endswith("# ")):
        result += shell.recv(4096).decode('utf-8')
    return result


class CentOsServer:
    def __init__(self):
        self.host_list = [
            ('ip', 'port', 'loginUserName', 'loginPassword', 'oldRootPassword', 'newRootPassword', 'serverName'),
            ('ip', 'port', 'loginUserName', 'loginPassword', 'oldRootPassword', 'newRootPassword', 'serverName'),
        ]

    def getClient(self):
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        return ssh_client

    def changeRootPass(self, ssh_client, host_info):
        ip, port, loginUsername, loginPassword, oldRootPassword, newRootPassword, serverName = host_info
        ssh_client.connect(hostname=ip, port=port, username=loginUsername, password=loginPassword, timeout=60)

        # 切换到root用户
        shell = ssh_client.invoke_shell()
        shell.send('su -\n')
        recv_all(shell)
        shell.send(oldRootPassword + '\n')
        recv_all(shell)

        # 更新密码
        shell.send('passwd \n')
        recv_all(shell)
        shell.send(newRootPassword + '\n')
        recv_all(shell)
        shell.send(newRootPassword + '\n')
        result = recv_all(shell)
        if 'successfully' in result or '成功更新' in result:
            print(Fore.GREEN + '%s 密码更新成功' %serverName)
        else:
            print(Fore.RED + '%s 密码更新失败' %serverName)

if __name__ == '__main__':
    centos = CentOsServer()
    client = centos.getClient()
    for host_info in centos.host_list:
        centos.changeRootPass(client, host_info)
    client.close()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值