逻辑问题:将行与用户名进行比较

2024-09-30 04:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我正在为anyconnect转储ASA的输出。我把它写进一个文件,然后读回程序。我正在打开一个csv的用户名从前一天,试图发现如果有任何新的连接。这个问题在我的逻辑里。我不知道如何将csv文件中的每个用户(行)与输出中的每一行进行比较,如果它们都不在该行中,则打印该行。我的代码将找到一个不在该行中的用户,但在该行包含我的列表中的用户时打印该行。例如,我有usrA和usrB,如果usrA不在行中,但usrB在行中,它将打印它,即使我的列表中有usrB

def compare(e):
    with open("anyconnect.csv", 'r') as usrf:
        for user in usrf:
            if user not in line:
                print(line)



def asa1(asaip0):
    device = {
        'device_type': 'cisco_asa',
        'ip': asaip0,
        'username': ("username"),
        'password': ("password"),
        'secret': ("password"),
        'port': 22,
        }

    with open(asaip0 + ".txt", 'w') as of:
        with open("log.csv", 'w') as log:
            net_connect = netmiko.ConnectHandler(**device)
            output = net_connect.send_command("show logging | grep LOCAL")
            of.writelines(output)
            log.writelines(output)
            log.close()

        with open("log.csv", 'r') as log:
            for line in log:
                compare(line)

###### MAIN ######
if __name__ == "__main__":

    asa1 = ('10.210.92.4')
    asa2 = ('10.210.109.4')
    ips = (asa1, asa2)
    asa1(asa1)
    asa1(asa2)

Tags: csv用户inlogoutputdeviceaswith
1条回答
网友
1楼 · 发布于 2024-09-30 04:40:33

变量名有一些奇怪的地方,所以这篇文章是用一些假设编写的

一种选择是将其更改为:

def compare(line):
    with open("anyconnect.csv", 'r') as usrf:
        user_found = False
        for user in usrf:
            if user in line:
                user_found = True
                break        # Not necessary, but will speed things up

        if not user_found:
            print(line)

这里,我们只关心line(参数)是否在user行的任何中(来自anyconnect文件)

对于每个compare(e)调用,肯定有比打开并循环所有循环更好的方法(比如读一次,提取已知用户名,创建一个集合,并使用e in your_set),但这应该可以让您开始

甚至像:

with open("anyconnect.csv", 'r') as usrf:
    ANYCONNECT = [line for line in usrf]

def is_known(name):
    return any(name in line for line in ANYCONNECT)

会更有效率

相关问题 更多 >

    热门问题