执行 python 脚本时最后一行(调用函数行)的语法错误



我正在尝试通过使用 pexpect 的 python 脚本来自动化一些任务。我还使用了 2 个.sh脚本。1 调用此 python 脚本,第二个调用二进制脚本的执行。

以下是我正在使用的文件:

root@box: ~# cat while.sh
#!/bin/bash
while read line
do
    ./try $line
done < $1
root@box: ~# cat try
#!/usr/bin/python
import sys, pwd, os
sys.path.append('pexpect')
try:
        import pexpect
except(ImportError):
        print "nYou need the pexpect module."
        sys.exit(1)
#Change this if needed.
LOGIN_ERROR = 'not response! '
def connect(host):
        print "Trying: ",host
        child = pexpect.spawn ('./x '+host)
        child.expect ('Enter string: ')
        child.sendline ('blablastring')
        i = child.expect([LOGIN_ERROR, pexpect.TIMEOUT], timeout=10)
        if i  == 1:
                print "nt[!] OK:",host
                child.sendline ('echo OK')
                print "nCommand executed successfully on:",host
                print child.before
                child.interact()
        if i == 0:
                print "Failed to exec cmd on: ",host
if len(sys.argv) != 1:
        print "nUsage : ./try <host>"
        print "Eg: ./try 1.3.3.7n"
        sys.exit(1)
target = sys.argv[1]
try:
     connect(host)
root@box: ~# cat x
#!/bin/bash
./somescript -h $1 -d 22
root@box: ~#
root@box: ~# head -n 5 hosts
192.168.1.120
192.168.1.121
192.168.1.122
192.168.1.123
192.168.1.124
root@box: ~#
root@box: ~# sh while.sh hosts
  File "./try", line 34
                        ^
SyntaxError: invalid syntax
  File "./try", line 34
                        ^
SyntaxError: invalid syntax
  File "./try", line 34
                        ^
SyntaxError: invalid syntax
  File "./try", line 34
                        ^
SyntaxError: invalid syntax
  File "./try", line 34
root@box: ~#

这是失败的地方?

这是

错误的:

try:
   connect(host)

这将有助于:

try:
   connect(host)
except Exception:
    pass