服务器要求每隔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()