在Python中循环读取文件中的一些IP吗?

1 投票
2 回答
2048 浏览
提问于 2025-04-17 16:46

我有一个CSV文件,里面包含了一些IP地址,排列成列,像这样:

10.38.227.233,VLAN-A,23
10.38.227.233,VLAN-XYZ,27
10.38.227.233,VLAN-XZ,27
10,38.169.103,VLAN-ABCD,11
10,38.169.103,VLAN-ABCD,16
10,38.169.103,VLAN-ABD,17

依此类推

对于每个IP,我需要登录到思科交换机上,并执行一些命令,比如对IP 10.38.227.233执行(VLAN-A,23|VLAN-XYZ,27|VLAN-XZ,27)的命令。

所有的IP都用同一个密码,所以我想只输入一次密码提示,然后对文件里的IP进行循环操作。

我还是个新手,刚开始这样做,但似乎不太管用。目前我在远程的*nix机器上执行简单的ls命令进行测试,但没有成功。

#!/usr/bin/python
import pexpect
import getpass
import time

iplist = ['10.39.5.41', '10.38.164.103', '10.38.227.229']

for ip in iplist:
                sshCmd = "ssh " + "auto21" + "@" + ip
                #auto21 is a username
                print "Command: " + sshCmd + "\n"

                answer = 'yes/no'
                prompt = 'password:'
                password = getpass.getpass('password:')

                #Sends answer based on target server response / known host
                p = pexpect.spawn(sshCmd)
                i = p.expect([answer,  prompt])
                print i
                if i==0:
                    print 'Sending yes...'
                    p.sendline('yes')
                    p.expect(prompt)
                    print 'Sending password...'
                    p.sendline(password)
                    p.sendline('ls\r')
                    p.expect(pexpect.EOF,timeout=20)
                    print p.before,p.after
                if i==1:
                    print 'Sending password...'
                    p.sendline(password)
                    p.sendline(password)
                    p.sendline('ls\r')
                    p.expect(pexpect.EOF)


                try:
                   p.interact()
                   sys.exit(0)
                except:
                   sys.exit(1)

这是我得到的结果:

bash-3.00# python ip.py
Command: ssh auto21@10.39.5.41

password:
1
Sending password...
Traceback (most recent call last):
  File "ip.py", line 35, in <module>
    p.expect(pexpect.EOF,timeout=20)
  File "/G4_Automation/user_mgmt/test/pexpect.py", line 1311, in expect
    return self.expect_list(compiled_pattern_list, timeout, searchwindowsize)
  File "/G4_Automation/user_mgmt/test/pexpect.py", line 1325, in expect_list
    return self.expect_loop(searcher_re(pattern_list), timeout, searchwindowsize)
  File "/G4_Automation/user_mgmt/test/pexpect.py", line 1409, in expect_loop
    raise TIMEOUT (str(e) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
<pexpect.spawn object at 0x15aef0>
version: 2.3 ($Revision: 399 $)
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'auto21@10.39.5.41']
searcher: searcher_re:
    0: EOF
buffer (last 100 chars): st login: Fri Feb 22 08:55:05 2013 from p13adv
Testgfs2
-sh-3.2$ ls
-sh-3.2$
-sh-3.2$
before (last 100 chars): st login: Fri Feb 22 08:55:05 2013 from p13adv
Testgfs2
-sh-3.2$ ls
-sh-3.2$
-sh-3.2$
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 29911
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1

请帮帮我。

另外,我该如何循环遍历文件中的IP,并在SSH环境中执行一系列命令呢?

注意:每个IP会有多个VLAN,但每个VLAN只有一个ID(比如11、12)。

编辑:我需要在SSH环境中运行一些命令。

ssh username@hosname "config t
                      int VLAN-A
                      switchport access VLAN-A  23
                      wr
                     #then for next VLAN for the current ip
                      config t
                      int VLAN-A
                      switchport access VLAN-A  23
                      wr
                     #and so on...............                        
                      "

2 个回答

0

这个命令是用来通过SSH连接到远程服务器的。我们来分解一下这个命令:

1. ssh:这是一个用来安全连接到另一台计算机的工具。

2. -o NumberOfPasswordPrompts=1:这个选项告诉系统只询问一次密码。

3. -o StrictHostKeyChecking=no:这个选项表示在连接时不检查对方的身份,这样可以避免一些安全提示。

4. -o UserKnownHostsFile=/dev/null:这个选项让系统不保存已知主机的信息,直接忽略它。

5. -l user:这里的user是你要登录的用户名。

6. [hostname or ip]:这里你需要填入你要连接的服务器的主机名或者IP地址。

7. -p 22:这个选项指定了连接的端口号,22是SSH的默认端口。

最后一句话的意思是:你不需要手动输入“yes”来确认连接,这个命令会自动处理。

0

首先,你需要把获取密码的那行代码移动到循环之前,这样它只会询问一次密码。

你遇到的错误是因为超时,简单来说就是ssh响应太慢了。

因为你想做的事情其实很简单。可以看看spur这个工具(https://pypi.python.org/pypi/spur)。它提供了一个非常简洁的界面来发送命令。

撰写回答