当前位置: 移动技术网 > IT编程>脚本编程>Python > python批量修改ssh密码

python批量修改ssh密码

2019年04月17日  | 移动技术网IT编程  | 我要评论

梦幻华尔兹第一部全集,湖北通城网,驾驶技能准考证明的有效期是多久?

由于工作需要本文主结合了excel表格,对表格中的ssh密码进行批量修改

以下是详细代码(python3):

 

#!/usr/bin/env python
#-*-coding:utf-8-*-

import paramiko
import socket
import pandas as pd

def demo(ip,user,old_password,new_password):
# 建立一个sshclient对象
ssh = paramiko.sshclient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.autoaddpolicy())
# 调用connect方法连接服务器
#如果远程执行命令错误信息是b'the input device is not a tty\n' 去掉docker exec -it 中的t就好了
try:
ssh.connect(hostname=ip, port=22, username=user, password=old_password,timeout=5)
#ubuntu修改密码两种方法
#方法一
# command1 = "echo '%s:%s' | chpasswd"%(user,new_password)
# stdin, stdout, stderr = ssh.exec_command(command1)
# out, err = stdout.read(), stderr.read()
# if err != '':
# print(err)
#
# else:
# print(out)
# # 关闭连接
# ssh.close()
#方法二
command = "passwd %s" %(user)
stdin, stdout, stderr = ssh.exec_command(command)
#\n模拟回车 输两次密码
stdin.write(new_password + '\n' + new_password + '\n')
out, err = stdout.read(), stderr.read()
successful = 'password updated successfully'
#print(out,err)
if successful in str(err):
print(ip + " 密码修改成功!")
else:
print('\033[31m错误:\033[0m' + str(err))
print(ip + " 密码修改失败!")
# 关闭连接
ssh.close()
except paramiko.ssh_exception.authenticationexception as e:
print(ip + ' ' + '\033[31m账号密码错误!\033[0m')
with open('nossh.txt','a') as f:
f.write(ip + '\n')
except socket.timeout as e:
print(ip + ' ' + '\033[31m连接超时!\033[0m')
with open('timeoutssh','a') as f:
f.write(ip + '\n')
def red_excel(ip):
import sys
import time
file = r'e:\xxx.xlsx'
pd.set_option('display.max_columns', none)
pd.set_option('display.max_colwidth', 1000)
n = pd.read_excel(file,sheet_name='xxx') #表格中的sheet名
#print(n.values)
#显示含某字段的特定行
n1 = (n.loc[n['ip']==ip])
if not n1.empty:
n2 = n1.values
ip = n2[0][1]
user = n2[0][4]
password_old = n2[0][5]
password_new = n2[0][22]
houtai = n2[0][16]
print('ip:%s 账号:%s 旧密码:%s 是否后台:%s 新密码:%s' % (ip, user, password_old, houtai,password_new))
demo(ip,user,password_old,password_new)
else:
print('记录表无此ip!')

if __name__ == "__main__":
with open('ip.txt') as f:
for i in f:
ip = i.split('\n')[0]
red_excel(ip)


此代码可以适当修改,进行单独的ssh密码修改。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网