예제 #1
0
"""ping sweep

usage: ping_sweep.py [-h] -n <netcidr>

options:
    -h, --help      show this help message and exit
    -n <netcidr>    ping_sweep target range (require) 

"""

from docopt import docopt
from netaddr import IPNetwork
import pings

if __name__ == '__main__':

    args = docopt(__doc__)

    for ip in IPNetwork(args["-n"]).iter_hosts():
        p = pings.Ping()
        res = p.ping(str(ip))

        if res.is_reached():
            print '%s' % ip

예제 #2
0
def set_unv_cloud():
    while True:
        try:
            a = int(input("Podsieć: 192.168."))
            x = int(input("Zakres hostów od: 192.168." + str(a) + "."))
            y = int(input("Zakres hostów do: 192.168." + str(a) + ".")) + 1
        except ValueError:
            print('Wprowadzona została niepoprawna wartość.')
            continue
        login = WordCompleter(['admin', 'admin1', 'user'])
        login = prompt('Podaj login: '******'admin123', 'admin', 'Niedzmin1'])
        passw = prompt('Podaj hasło: ', completer=passw)
        passw_ac = str(passw)

        http = "http://"
        ip_uniview = "192.168." + str(a) + "."
        static = "/LAPI/V1.0/"
        static2 = "/cgi-bin/main-cgi/"
        cloud_nvr_unv = "Network/Cloud"
        p = pings.Ping()
        for i in range(x, y):
            ip_rest = str(i)
            ping_ip = str(ip_uniview + ip_rest)
            response = p.ping(ping_ip)
            print(ping_ip)
            if (response.is_reached()):
                info_nvr_unv = "System/DeviceInfo"
                info_nvr_unv_x = requests.get(
                    http + ip_uniview + str(ip_rest) + str(static) +
                    info_nvr_unv,
                    auth=HTTPDigestAuth(login_ac, passw_ac))
                x = json.loads(info_nvr_unv_x.text)
                firmwareversion = (x['Response']['Data']['FirmwareVersion'])
                firmsubstr = int(firmwareversion[3:5])
                fw = "D" + str(firmsubstr)
                print("Wersja firmware: " + fw)
                if (firmsubstr > 22):
                    cloud_nvr_unv_x = requests.get(
                        http + ip_uniview + str(ip_rest) + str(static) +
                        cloud_nvr_unv,
                        auth=HTTPDigestAuth(login, passw))
                    cloudname = WordCompleter([
                        'p2pdevice.bcscctv.pl', 'p2p.bcscctv.pl', 'test', 'nic'
                    ])
                    prompt('Podaj adres chmury lub wybierz z listy: ',
                           completer=cloudname)
                    cloudname = str(cloudname)
                    cloudstatus = int(
                        input("Czy włączamy chmurę? 0 - NIE, 1 - TAK: "))
                    data = {
                        "Enabled": cloudstatus,
                        "Domain": "" + cloudname + "",
                        "DeviceName": "UNIVIEW"
                    }
                    r = requests.put(cloud_nvr_unv_x.url,
                                     auth=HTTPDigestAuth(login, passw),
                                     json=data)
                    if (r.status_code != 200):
                        print(
                            "Wystąpił nieznany problem, chmura niustawiona. Kod błędu: "
                            + r.status_code)
                    else:
                        print(
                            "Adres chmury zmieniony a status chmury ustawiony na "
                            + str(cloudstatus))
                else:

                    cloudname = WordCompleter([
                        'p2pdevice.bcscctv.pl', 'p2p.bcscctv.pl', 'test', 'nic'
                    ])
                    prompt('Podaj adres chmury lub wybierz z listy: ',
                           completer=cloudname)
                    cloudname = str(cloudname)
                    cloudstatus = str(
                        input("Czy włączamy chmurę? 0 - NIE, 1 - TAK: "))

                    # hashowanie hasła do MD5
                    passwencode = str(passw_ac).encode('utf-8')
                    md5pass = (hashlib.md5(passwencode).hexdigest())

                    datamd5 = {
                        'szUserName': str(login_ac),
                        'szUserLoginCert': md5pass
                    }

                    # zapis do pliku JSON z logowania

                    responsemd5 = requests.post(http + ping_ip + static2,
                                                data=datamd5)
                    filepath = "LOGIN/JSON_" + ping_ip + ".html"
                    os.makedirs(os.path.dirname(filepath), exist_ok=True)
                    with open(filepath, 'w', encoding='utf-8') as j:
                        JSON = re.compile('GLOBAL_INFO = ({.*?});', re.DOTALL)
                        matches = JSON.search(responsemd5.text)
                        completejson = matches.group(1)
                        jsonx = json.loads(completejson)
                        session_handler = jsonx['stUserInfo'][
                            'u32UserLoginHandle']
                        string_session_handler = str(session_handler)

                        data = '{"cmd":149,"bIsEnable":' + cloudstatus + ',"u8DdnsType":"0","szDdnsDomain":"' + cloudname + '","szDeviceName":"","szDdnsUserName":"","szDdnsPassword":"","szUserName":"******","u32UserLoginHandle":' + string_session_handler + '}'
                        response = requests.post(responsemd5.url, data=data)
                        if (response.status_code != 200):
                            print(
                                "Wystąpił nieznany problem, chmura nieustawiona. Kod błędu: "
                                + r.status_code)
                        else:
                            print(
                                "Adres chmury został zmieniony a status ustawiono na "
                                + str(cloudstatus))
            else:
                print("OFFLINE")
        break
def login(mid):
    # 外部との疎通が確認できた場合は何もしない
    p = pings.Ping()
    address00 = "35.196.128.215"  # 自分で用意したサーバ
    if p.ping(address00).is_reached():
        logger.info("[%s] 外部(%s)との疎通を確認しました" %
                    (datetime.datetime.now(), address00))
        return
    address01 = "8.8.8.8"
    if p.ping(address01).is_reached():
        logger.info("[%s] 外部(%s)との疎通を確認しました" %
                    (datetime.datetime.now(), address01))
        return
    address02 = "1.1.1.1"
    if p.ping(address02).is_reached():
        logger.info("[%s] 外部(%s)との疎通を確認しました" %
                    (datetime.datetime.now(), address02))
        return
    logger.info("[%s] 外部との疎通を確認することができませんでした" % (datetime.datetime.now()))

    if keyring.get_password('keyring_selenium', mid) is None:
        logger.error("Please store your login info!", )
        logger.error("Run script in terminal: pipenv python save_pass.py")
        return

    # WebDriverのパスを指定してChromeを起動
    os_name = platform.system()
    if os_name == "Darwin":
        driver_path = "bin/chromedriver_mac_v2_41"
    elif os_name == "Linux":
        driver_path = "bin/chromedriver_linux_v2_41"
    elif os_name == "Windows":
        driver_path = "bin/chromedriver_win32_v2_41.exe"
    else:
        logger.error("Unknown System. Please send Issue.")
        return
    driver = webdriver.Chrome(driver_path)

    # 宮大ネットワーク認証画面を開く
    miyadai_url = "http://midp.cc.miyazaki-u.ac.jp"
    driver.get(miyadai_url)
    logger.info(driver.current_url)
    try:
        WebDriverWait(
            driver, 10).until(lambda driver: driver.current_url != miyadai_url)
        login_url = driver.current_url
        logger.info(login_url)
        input_mid = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "login-username")))
        logger.info(driver.current_url)
    except TimeoutException:
        logger.error("Already login or don't connecting.")
        driver.quit()
        return

    input_mid.send_keys(mid)
    input_pass = driver.find_element_by_id("login-password")
    input_pass.send_keys(keyring.get_password('keyring_selenium', mid))

    # 検索ボタン要素の取得
    button_login = driver.find_element_by_id("btn-login")

    # 検索ボタンをクリックする
    button_login.click()

    try:
        WebDriverWait(driver,
                      10).until(lambda driver: driver.current_url != login_url)
        logger.info(driver.current_url)
    except TimeoutException:
        logger.error("Failed login. Please check MID or password.")
    driver.quit()
    logger.info("[%s] 自動ログインを終了します" % (datetime.datetime.now()))
    return
예제 #4
0
                elif (10 < x < 180):
                    servo = 1000
                elif (-180 < x < -10):
                    servo = 2000
                elif (180 <= x < 350):
                    servo = 2000
                else:
                    servo = 1500

            #距離threshold以下(到着判定)
            else:
                ecs = 1500
                servo = 1500

                #ネットワーク判定
                p = pings.Ping()  # Pingオブジェクト作成
                res = p.ping("www.yahoo.co.jp")  # yahoo.co.jpへPing

                #接続OK
                if res.is_reached():
                    pingres = 'OK'
                    #目標を1進める
                    writenumber = (int(number) + 1)
                    with open(locationpath + '/number.txt',
                              mode="w",
                              encoding='utf-8') as f:
                        f.write(str(writenumber))

                # 接続NG
                else:
                    pingres = 'NG'