由于工作需要本文主結合了excel表格,對表格中的ssh密碼進行批量修改
以下是詳細代碼(python3):
'''
遇到問題沒人解答?小編創建了一個Python學習交流QQ群:857662006
尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書!
'''
#!/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密碼修改。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

