Python スクリプト シリーズ - xshell サーバーのパスワードをバッチで更新する

import os

'''
需求:公司要求定期修改服务器密码,xshell保存好的配置就得一个一个改,麻烦。
注意:
    1.确保xsh文件是utf-16的,默认的编码,不一致更新password时会无法使用
    2.先用一个xsh登录后,输入密码,再提取更新后的密码,作为update_pwd
    3.适用于所有的ssh登陆,password更新的时候记得加入换行符
场景:固定部分服务器更新密码;或者以前密码不统一,要求统一配置。
'''

# 找到xsh保存的路径下打开现有的xsh文件查看密码
curr_pwd = "Password=6yWqCKddddddv5laXfdrkC8gXeXcccccck+mUT6gv0Dj"
# xshell配置新密码后打开新的xsh文件查看密码,此处实际为12345678
update_pwd = "Password=jX/rfKIilf3veXyBGPAt+2SWB91dP4x2IwSMnAY9UyzJXF7XqJimTw==\n"
# 记录下更新了几套防止遗漏
count = 0

# age:C:\Users\18048\Documents\NetSarang Computer\6\Xshell\Sessions
path = input('请输入xsh文件路径:')

# 遍历文件夹
for root, dirs, files in os.walk(path):
    for f1 in files:
        # 判断为xsh文件
        if '.xsh' in f1:
            # xsh文件编码为utf16
            with open(path + '\\' + f1, encoding='utf-16') as f:
                # 判断out文件夹并创建
                if not os.path.exists(path+'\\out'):
                    os.makedirs(path+'\\out')
                fw = open(path+'\\out' + '\\' + f1, 'w', encoding='utf-16')
                # 遍历文件中每一行
                for line in f.readlines():
                    # 如果直接更新所有服务器配置
                    # 直接改为if line.startswith("Password="):
                    if curr_pwd in line:
                        # print(curr_pwd)
                        print("更新服务器密码:" + f1)
                        count = count + 1
                        fw.write(update_pwd)
                    else:
                        fw.write(line)
print('修改完成,共更新' + str(count) + '个配置!')

Supongo que te gusta

Origin blog.csdn.net/weixin_39855998/article/details/128937217
Recomendado
Clasificación