找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 1687|回复: 1

[求助] 函数里面的try,except异常

4

主题

8

帖子

8

积分

贫民

积分
8
测测 发表于 2019-9-15 00:56:26 | 显示全部楼层 |阅读模式
import paramiko
import time

def cisco(ip="10.10.10.5",username="qq",password="huawei",enable="huawei"):
    try:
       ssh_client = paramiko.SSHClient()
       ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh_client.connect(hostname=ip,username=username,password=password)
       print ("Successfully connect to", ip)
       remote_connection = ssh_client.invoke_shell()
       remote_connection.send("enable\n")
       remote_connection.send(enable + "\n")
       command = open("command.txt", 'r')
       remote_connection.send(command.read())
       command.seek(0)
       time.sleep(60)
       log = open(ip+".txt","a")
       log.write(remote_connection.recv(100000).decode('ascii'))
    except:
        error = open("error.txt","a")
        error.write(ip+"\n")

cisco()

10.10.10.5这个host是存在,但用户名和密码是错误的,会出发异常处理,但我看了下。只执行了“error = open("error.txt","a")”这条语句,并没有执行“error.write(ip+"\n")”
回复

使用道具 举报

4

主题

8

帖子

8

积分

贫民

积分
8
测测  楼主| 发表于 2019-9-15 00:59:35 | 显示全部楼层

import paramiko
import time

def cisco(ip="10.10.10.5",username="qq",password="huawei",enable="huawei"):
    error = open("error.txt","a")
    try:
       ssh_client = paramiko.SSHClient()
       ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
       ssh_client.connect(hostname=ip,username=username,password=password)
       print ("Successfully connect to", ip)
       remote_connection = ssh_client.invoke_shell()
       remote_connection.send("enable\n")
       remote_connection.send(enable + "\n")
       command = open("command.txt", 'r')
       remote_connection.send(command.read())
       command.seek(0)
       time.sleep(60)
       log = open(ip+".txt","a")
       log.write(remote_connection.recv(100000).decode('ascii'))
    except:
        error.write(ip+"\n")

cisco()
如果写成这样,就能执行“error.write(ip+"\n")”
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表