1. 程式人生 > >使用python的paramiko模塊對多臺機器更新密碼

使用python的paramiko模塊對多臺機器更新密碼

str log def ddp -s gin __name__ main function

廢話不多說,直接上代碼

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import paramiko


def connect_modify(ip, username, password, newpass):
paramiko.util.log_to_file(‘syslogin.log‘)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
client.connect(hostname=ip, username=username, password=password)
except:
print(ip+‘network not connect‘)
return 0
stdin, stdout, stderr = client.exec_command(‘echo %s | passwd --stdin %s ‘ % (newpass, username))
result = stdout.read(), stderr.read()
for line in result:
print(line.decode(‘utf-8‘))
print(ip, ‘OK!‘)
client.close()
return 1


def main():
try:
with open(‘hosts‘) as f:
for item in f:
item = item.strip().split(‘,‘)
ip = item[0]
username = item[1]
password = item[2]
newpass = item[3]
connect_modify(ip, username, password, newpass)
except Exception as e:
print(e, ‘not open password configfile‘)


if __name__ == ‘__main__‘:
main()

需要有一個hosts文件被讀取

文件格式為:

192.168.1.1,root,123456,654321

英文逗號分隔

也可以做成多線程,更快的執行

使用python的paramiko模塊對多臺機器更新密碼