如何忽略telnetlib错误并在python中继续For循环

时间:2017-03-23 22:58:29

标签: python ip-address telnet telnetlib

我想使用telnetlib和python来远程登录IP,所以我使用了这段代码

class Album: Object {
    dynamic var title = ""
    dynamic var isFavorite = false

    convenience init(json: [String: Any]) throws {
        self.init()

        guard let title = json["title"] as? String else {
            throw SerializationError.invalidJSON("Album")
        }

        self.title = title
    }
}

protocol AlbumCollectionViewCellDelegate: class {
    func didTapFavoriteButton(_ favoriteButton: UIButton, album: Album)
}

class AlbumCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var favoriteButton: UIButton!

    weak var delegate: AlbumCollectionViewCellDelegate?
    var album: Album!

    // HELP
    var notificationToken: NotificationToken? // Is this where I add the notification for Realm?

    @IBAction func didTapFavoriteButton(_ sender: UIButton) {
        delegate?.didTapFavoriteButton(sender, album: album)
    }

    func configure(with album: Album) {
        titleLabel.text = album.title
        favoriteButton.isSelected = album.isFavorite
        self.album = album
    }
}

class FavoritesListViewController: UIViewController, AlbumCollectionViewCellDelegate {

    // MARK: - AlbumCollectionViewCellDelegate
    func didTapFavoriteButton(_ favoriteButton: UIButton, album: Album) {
        favoriteButton.isSelected = album.isFavorite
    }
}

问题是当我执行该代码时,如果IP不可用,则显示此错误:

import ipaddress
import telnetlib
import time

def looping_ip() :
    for j in range(1, 50, 1):
        ip = "192.168.1.%d" % (j)
        connection = telnetlib.Telnet()
        connection.open(ip)
        connection.read_until("Password:")
        connection.write("admin"+"\n")
        connection.read_eager()
        return True

我想忽略任何错误并继续循环直到我停止它。 请你的回答应该是python而不是其他任何语言。

1 个答案:

答案 0 :(得分:0)

试试这个:

import ipaddress
import telnetlib
import time

def looping_ip() :
    for j in range(1, 50, 1):
        ip = "192.168.1.%d" % (j)
        try:
            connection = telnetlib.Telnet()
            connection.open(ip)
            connection.read_until("Password:")
            connection.write("admin"+"\n")
            connection.read_eager()
            return True
        except:
            continue