Python 将行与用户名进行比较时出现逻辑问题

Python 将行与用户名进行比较时出现逻辑问题,python,python-3.x,Python,Python 3.x,因此,我正在为anyconnect转储ASA的输出。我将其写入一个文件,然后将其读回程序。我正在打开前一天的csv用户名,试图发现是否有新连接的用户。这个问题在我的逻辑中。我不知道如何将csv文件中的每一个用户(行)与输出中的每一行进行比较,如果他们都不在该行中,则打印该行。我的代码将找到一个不在该行中的用户,但在该行包含我列表中的用户时打印该行。例如,我有usrA和usrB,如果usrA不在行中,但usrB在行中,它将打印它,即使我的列表中有usrB def compare(e): w

因此,我正在为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)
(变量名出现了一些奇怪的情况,因此本文是根据一些假设编写的)

一种选择是将其更改为:

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)
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)
这里,我们只关心
(参数)是否在
用户
行(来自anyconnect文件)的

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

甚至像:

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)
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)

效率会更高

我喜欢有人投了反对票,但什么也没说。可能像
如果没有(usrf中用户对用户排队)
而不是你的第一个for循环+if.OP可能会想要重构代码,以避免为每一行分别加载
usrf
。@尾随空格我同意,我认为解析anyconnect文件中的名称(读取一次)并创建一个集合可能是最好的,但我在答案的底部添加了一个中间选项(因为我不知道anyconnect.csv的格式,所以无法进行名称解析)