我正在尝试通过使用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: ~#
这在哪里失败了?
答案 0 :(得分:3)
这是错误的:
try:
connect(host)
这会有所帮助:
try:
connect(host)
except Exception:
pass