当使用 Python 脚本连接到一组主机并执行命令时,可能会遇到某些主机无法连接或无法执行命令的情况。如果遇到这种情况,脚本就会终止运行,无法继续执行后续操作。为了解决这个问题,我们需要让脚本在遇到错误时能够继续运行,并记录下错误信息,以便后续分析。
2. 解决方案
解决这个问题的一种方法是使用异常处理来捕获错误。异常处理是一种用于处理脚本运行时遇到的错误的机制,它可以在脚本中定义异常处理块来处理特定的异常。
下面是一个使用异常处理来处理连接错误的示例代码:
import pexpect
def connect(user, host, passwd, en_passwd):
ssh_newkey = 'Are you sure you want to continue connecting?'
constr = 'ssh ' + user + '@' + host
child = pexpect.spawn(constr)
ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
if ret == 0:
print('[-] Error Connecting to ' + host)
return None
if ret == 1:
child.sendline('yes')
ret = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])
if ret == 0:
print('[-] Could not accept new key from ' + host)
return None
child.sendline(passwd)
child.expect(PROMPT)
child.sendline('enable')
child.sendline(en_passwd)
child.expect(PROMPT)
child.sendline('config t')
child.expect(PROMPT)
return child
def send_command(child, cmd):
try:
child.sendline(cmd)
child.expect(PROMPT)
print child.before
except pexpect.EOF:
print('[-] Error: Connection to ' + child.remoteip + ' closed unexpectedly.')
except pexpect.TIMEOUT:
print('[-] Error: Connection to ' + child.remoteip + ' timed out.')
def main():
parser = argparse.ArgumentParser('--host --host_file --username --password--enable --group --snmp_user --snmp_host\
--snmp_contact --int_name --snmp_v3_auth --snmp_v3_hmac --snmp_v3_priv --snmp_v3_encr')
parser.add_argument('--host_file', dest='hosts', type=file, help='specify a target host file')
hosts = args.hosts
if hosts:
for line in hosts:
host = line.rstrip()
child = connect(user, host, passwd, en_passwd)
if child:
send_command(child, SNMPGROUPCMD + group + V3PRIVCMD)
send_command(child, SNMPSRVUSRCMD + snmpuser + ' ' + group + V3AUTHCMD + SHAHMACCMD + snmpauth + PRIVCMD +
snmpencrypt + ' ' + snmppriv)
send_command(child, SNMPSRVHOSTCMD + intname + ' ' + snmphost + VERSION3CMD + snmpuser)
send_command(child, SNMPSRVCONTACTCMD + snmpcontact)
send_command(child, SNMPSRVENTRAP)
send_command(child, WRME)
if __name__ == '__main__':
main()
在这个示例代码中,我们在 connect 函数中使用 pexpect.spawn() 函数来连接到目标主机,并在 expect() 函数中捕获连接错误。如果连接失败,我们会打印一条错误消息并返回 None。
在 send_command 函数中,我们使用 try/except 块来捕获命令执行错误。如果命令执行失败,我们会打印一条错误消息。
这样,当脚本连接到某个主机并执行命令时,如果遇到错误,脚本不会终止运行,而是会继续连接到下一个主机并执行命令。