通过Python合并sqldb中的2行相关数据

2024-05-21 00:53:24 发布

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

我对Python和mysql都不太熟悉。我一直在编写一个python脚本,以自动发现新的Cisco交换机,并在mysql数据库中自动填充它们的数据。脚本有许多文件,但我会使它简单,因为我试图解决一个特定的问题。你知道吗

以下是我需要帮助的代码:

host = ['Switch1.abc.com', 'Switch2.abc.com']
while i<len(host):
    print "\n Logging into", host[i], "\n"
    #Logs in to host[i] and grabs data from switch and assigns it to variables below
    login(user, password, host[i], timeout)
    #Prints to test all variables have proper data fom host[i]
    print "DB Data: ", host[i], Pair2, Pair1_Vlan1, Pair1_Vlan2, Pair2_Vlan1, Pair2_Van2, ospf, interlink, mgmt, Env, Domain
    #Create a new entry in table with host[i] data
    updateDB.insertSQL(host[i], Pair2, Pair1_Vlan1, Pair1_Vlan2, Pair2_Vlan1, Pair2_Vlan2, ospf, interlink, mgmt, Env, Domain)


    '''
    pusdo code:
    if host2 == host1's peer
       # using UPDATE, it sets peer's vlan info 
       updateDB.updateSQL(Pair2, Pair2_Vlan1, Pair2_Vlan2, host[i])
   '''   
   i += 1

我静态地将两个交换机分配给主机变量进行测试,但它来自一个不同的函数,该函数执行snmp爬网并返回任何#个交换机。你知道吗

这是我运行后的数据库。你知道吗

| SW_Pair1        | SW_Pair2        | Pair1_VLAN1| Pair1_VLAN2| Pair2_VLAN1| Pair2_VLAN2| Inter | Mgmt| OSPF| Env | Domain|
|-----------------|-----------------|------------|------------|------------|------------|-------|-----|-----|-----|-------|
| Switch1.abc.com | Switch2.abc.com | VLAN-111   | VLAN-333   | Unknown    |  Unknown   |   47  | 24  | 0.1 | Dev | abc   |
| Switch2.abc.com | Switch1.abc.com | VLAN-222   | VLAN-444   | Unknown    |  Unknown   |   47  | 24  | 0.1 | Dev | abc   |

这些开关的设置方式是成对的。所以,如表中所示,当脚本登录到host1时,它会获取该主机上的所有数据,而host1只能看到host2的名称,因为它们是一对。你知道吗

现在,当while循环完成host1(Switch1)时,它将转到host2(switch2),然后执行相同的操作。现在和host1一样,host2存储它所有的信息,它只知道它的名字。你知道吗

因为它们是成对的,所以它们有许多相同的信息,如域、管理端口等。我唯一感兴趣的是VLAN,并确保两者都是成对的,因为它们在SW\u Pair1和SW\u Pair2中有彼此的名称。你知道吗

所以,我要做的是合并两行,使其看起来像这样:

| SW_Pair1        | SW_Pair2        | Pair1_VLAN1| Pair1_VLAN2| Pair2_VLAN1| Pair2_VLAN2| Inter | Mgmt| OSPF| Env | Domain|
|-----------------|-----------------|------------|------------|------------|------------|-------|-----|-----|-----|-------|
| Switch1.abc.com | Switch2.abc.com | VLAN-111   | VLAN-333   | VLAN-222   |  VLAN-444  |   47  | 24  | 0.1 | Dev | abc   |

此表中还有许多其他行,因此我要确保重写了正确的行。我不知道实现这一目标的最佳方法是什么。我尝试在while循环下比较pair1和pair2(参见上面的psudo代码),但似乎无法让它工作。你知道吗

任何帮助将不胜感激,因为我已经花了大量的时间研究和尝试多个东西没有成功。你知道吗

谢谢


Tags: envcomhostdomainswabcvlanhost2