概述
由于机房线上有多台主机,为了保障安全,需要定期修改密码。若手动修改,费时费力易出错。而expect在特殊字符的处理上极为恶心,故用python脚本简单实现需求。
1、安装依赖包
基于python3环境
pip install paramikoexport CRYPTOGRAPHY_ALLOW_OPENSSL_102=1
2、密码文件(passwd.txt)
IP用户名 旧密码 新密码
3、修改密码脚本(change_password.py)
#!/usr/bin/python# -*- coding: utf-8 -*-import paramikoimport ostest_fail='result.fail'if os.path.exists(test_fail): os.remove(test_fail)test_ok='result.ok'if os.path.exists(test_ok): os.remove(test_ok)pass_file=open('passwd.txt','r')for line in pass_file: inform=line.split() ipaddr=inform[0] username=inform[1] old_pass=inform[2] new_pass=inform[3] port=22 try: ssh=paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=ipaddr,username=username,password=old_pass,timeout=10) ssh.exec_command('echo "%s"|passwd --stdin root'%new_pass) ret_ok=open('result.ok','a+') ret_ok.write(ipaddr+" is OK") ret_ok.close() ssh.close() except Exception as e: ret_fail=open('result.fail','a+') ret_fail.write(ipaddr+" is failed") ret_fail.close()pass_file.close()
以上就是脚本及实际的应用了,后面会分享更多devops和DBA方面内容,感兴趣的朋友可以关注下!