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

时间:2014-12-23 14:21:18

标签: python automation pexpect

我正在尝试通过使用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 "\n\t[!] 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.7\n"
        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: ~#

这在哪里失败了?

1 个答案:

答案 0 :(得分:3)

这是错误的:

try:
   connect(host)

这会有所帮助:

try:
   connect(host)
except Exception:
    pass