python批量修改ssh密码的实现

  • 时间:
  • 浏览:27

因为事情需求本文主连系了excel表格,对表格中的ssh稀码停止批量修正

以下是具体代码(Python3):

'''
碰到成绩出人解问?小编创立了1个Python进修交换QQ群:857662006 
寻觅有情投意合的小火伴,互帮相助,群里借有没有错的视频进修教程战PDF电子书!
'''
#!/usr/bin/env python
#-*-coding:utf⑻-*-

import paramiko
import socket
import pandas as pd

def demo(Ip,user,old_password,new_password):
  # 成立1个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修正稀码两种办法
    #办法1
    # 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()
    #办法2
    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:\***.xlsx'
  pd.set_option('display.max_columns', None)
  pd.set_option('display.max_colwidth', 1000)
  n = pd.read_excel(file,sheet_name='***')  #表格中的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稀码修正。

以上便是本文的全数内容,期望对各人的进修有所帮忙,也期望各人多多撑持剧本之家。