python的commands.getstatusoutput出现sh执行错误,请大侠帮忙看一下

python的commands.getstatusoutput出现sh执行错误,请大侠帮忙看一下

问题:
用telnet的方式去连接指定IP的PORT,以确定该PORT是否打开

ipadd.txt文件这么写的:
192.168.199.10,21,80,22,53
192.168.199.11,21,80,22,53
192.168.199.12,21,80,22,53

脚本:

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/env python
import os, sys,commands

def ReadIp(filepath):
    """read ip address adn ports from file"""
    if os.path.isfile(filepath):
        for count, line in enumerate(open(filepath, 'rU')):
            seps = line.split(',')
            ip = ''.join(seps[0])
            ports = seps[1:]
            for port in ports:
                cmdstr = "echo QUIT  | telnet " + ip +"  "+''.join(port)
                print cmdstr
                [id,str] = commands.getstatusoutput(cmdstr)
                print str
            
    else:
        print "not a file!Usage:cmd filename"
   
if __name__ == "__main__":
    ReadIp("ipadd.txt")



python monet.py
执行结果,其中“会随机的sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
”错误,这个是从何处来的?


echo QUIT  | telnet 192.168.199.10  21
Trying 192.168.199.10...
Connected to 192.168.199.10.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.10  80
telnet: Unable to connect to remote host: Connection refused
Trying 192.168.199.10...
echo QUIT  | telnet 192.168.199.10  22
Trying 192.168.199.10...
Connected to 192.168.199.10.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.10  53

sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'

echo QUIT  | telnet 192.168.199.11  21
Trying 192.168.199.11...
Connected to 192.168.199.11.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.11  80
Trying 192.168.199.11...
Connected to 192.168.199.11.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.11  22
Trying 192.168.199.11...
Connected to 192.168.199.11.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.11  53

sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'

echo QUIT  | telnet 192.168.199.12  21
telnet: Unable to connect to remote host: Connection refused
Trying 192.168.199.12...
echo QUIT  | telnet 192.168.199.12  80
telnet: Unable to connect to remote host: Connection refused
Trying 192.168.199.12...
echo QUIT  | telnet 192.168.199.12  22
Trying 192.168.199.12...
Connected to 192.168.199.12.
Escape character is '^]'.
Connection closed by foreign host.
echo QUIT  | telnet 192.168.199.12  53
telnet: Unable to connect to remote host: Connection refused
Trying 192.168.199.12...

我想你每后后面的回车符没有去掉。改造:

[Copy to clipboard] [ - ]
CODE:
        for count, line in enumerate(open(filepath, 'rU')):
            seps = line.split(',')
            ip = ''.join(seps[0])

去掉每行的回车符,然后再split()处理。而且第一个ip为什么需要''.join呢?因为seps[0]得到的应该是一个字符串呀,不是一个tuple。