经验分享:使用Python3删除ansible主机known_hosts文件中已下线主机的公钥信息

使用Python3删除ansible主机known_hosts中已下线主机的公钥信息。

简介

在使用ansible工具批量管理主机时,通常会让ansible主机与被控主机之间实现免密登录,从而方便工作的开展。值得注意的是,当被控主机需要下线不再被工具管理时,应当删除ansible主机known_hosts文件中已下线主机的公钥信息,以便当有新主机复用旧ip时,还可以顺利被ansible管理,避免报错。

为此我使用Python3编写了批量删除下线主机公钥信息的脚本,以提高工作效率,现分享出来,愿与志同道合的朋友、同事一同成长。

代码部分

python 复制代码
# -*- coding: utf-8 -*-
import sys
import os
import shutil
from datetime import datetime

'''
备份文件
f_name: 需要备份的文件,全路径
bf_name:备份后的文件,全路径
'''
def backup_file(f_name):
    timestr = datetime.now().strftime('%Y%m%d%H%M%S')
    bf_name = f_name + ".bak" + "-" + timestr
    shutil.copy(f_name,bf_name)
    if not check_file_exists(bf_name):
        print("%s 备份失败" % f_name)
        exit(1)

'''
判断文件是否存在,返回True或False
'''
def check_file_exists(f_name):
    check_result = os.path.isfile(f_name)
    return check_result
    
'''
将文件读入列表
'''
def file_to_list(f_name):
    f_list = []
    with open(f_name,"r") as f:
        for line in f:
            f_list.append(line)
    return f_list

'''
将列表写入文件
'''
def list_to_file(f_name,f_list):
    with open(f_name,"w") as f:
        for line in f_list:
            f.write(line)

'''
在known_hosts文件中,删除已下线主机的pub key
'''
def clean_content(key_file,ip_str):
    temp_file = key_file + ".temp"
    key_list = file_to_list(key_file) 
    for ip in ip_str.split(','):
        key_list = [ item for item in key_list if ip not in item ]

    list_to_file(temp_file,key_list)
    if not check_file_exists(temp_file):
        print("下线主机pub key清理失败。")
        exit(1)
    os.remove(key_file)
    os.rename(temp_file,key_file)

def main():
    key_file = '/root/.ssh/known_hosts'
    if not check_file_exists(key_file):
        print("%s 不存在,请确认本机是否为汇聚代理。" % key_file)
        exit(1)
    backup_file(key_file)
    clean_content(key_file,sys.argv[1])
    
if __name__ == "__main__":
    main()

调用方法

python3 clean_sshkey.py 192.168.1.40,192.168.1.41,192.168.1.42

结果验证

清理前

[root@localhost .ssh]# cat known_hosts
192.168.1.40 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM0=
192.168.1.41 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM1=
192.168.1.42 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM2=
192.168.1.43 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM3=
192.168.1.44 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM4=
192.168.1.45 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM5=

清理后

[root@localhost .ssh]# cat known_hosts
192.168.1.43 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM3=
192.168.1.44 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM4=
192.168.1.45 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBO17Pvvo3HFYGD19Dmf/kprUXLexRhuqpL0NvKjAzHjH6tJSZK0xpMY814uHArpNHvMI2yKDxu+LPo1a/iRVOIM5=
相关推荐
会掉头发8 分钟前
Linux进程通信之共享内存
linux·运维·共享内存·进程通信
我言秋日胜春朝★10 分钟前
【Linux】冯诺依曼体系、再谈操作系统
linux·运维·服务器
努力的家伙是不讨厌的13 分钟前
解析json导出csv或者直接入库
开发语言·python·json
云空35 分钟前
《Python 与 SQLite:强大的数据库组合》
数据库·python·sqlite
饮啦冰美式41 分钟前
22.04Ubuntu---ROS2使用rclcpp编写节点
linux·运维·ubuntu
wowocpp41 分钟前
ubuntu 22.04 server 安装 和 初始化 LTS
linux·运维·ubuntu
Huaqiwill43 分钟前
Ubuntun搭建并行计算环境
linux·云计算
wclass-zhengge1 小时前
Netty篇(入门编程)
java·linux·服务器
Lign173141 小时前
ubuntu unrar解压 中文文件名异常问题解决
linux·运维·ubuntu