1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418
|
#!/usr/bin/python
import base64, getopt, urllib, httplib, os, re, sys, stat, string, time, telnetlib, socket, binascii
try:
import syslog
except: # for platforms without syslog that try to use --syslog option
class fake_syslog:
def openlog(self,foo):
raise Exception("Syslog not supported on this platform")
def syslog(self,foo):
raise Exception("Syslog not supported on this platform")
syslog = fake_syslog()
try:
from pysnmp import session
from pysnmp import error
except:
class fake_session:
class session:
def __init__(self, a, c):
raise Exception("Pysnmp missing, note you need version 1.x series of Pysnmp")
session = fake_session()
Version = "0.225"
#
# ipcheck.py
#
# Copyright GNU GENERAL PUBLIC LICENSE Version 2
# http://www.gnu.org/copyleft/gpl.html
#
# Author : Kal <kal@users.sourceforge.net>
#
# Acknowledgements
# ================
#
# dyndns crew -a great service, reliable and professional
# Bobby Griggs -ls_dyndns.py client
# Vincent Zweije -HTTP Date header idea for wuHHMM codes
# Todd Rose -Various suggestions and Linksys support
# Yaron Minsky -syslog patch and RT311 support
# Karen Chancellor -RT311 tests
# Johannes Maslowski -Draytek Vigor support
# Ulf Axelsson -option -d fixes
# Del Hodge -Netopia R9100 support
# Jan Bjorvik -Cisco DSL support
# Robert Towster -SMC barricade
# Onno Kortmann -acctfile security suggestion
# Greg Bentz -Linksys firmware 1.37, BSD Default route
# Erwin Burgstaller -Cisco ISDN support
# Allen Eastwood -HawkingTech support
# JP Szikora -ZyXEL Prestige support
# Remi Zara -NetBSD info
# Thomas Deselaers -Debian package manpage
# Steve Warner -SNMP support
# John Radimecky -Watchguard SOHO support
# Mark Anderson -router global var bug, time, testrun, docs
# Justin Kuo -Nexland ISB2LAN
# Mark Lederer -MacOS X
# Mark Aufflick -Compex Netpassage 15
# Ken Frank -UgatePlus, BSD 4.3 info
# Michel Bouissou -Cayman DSL support
# Jan Carlson -Gnet ADSL router model BB0040 support
# Tony Scicchitano -BeOS local ip detection
# Bas Heijermans -OS/2 tips and code
# Jeff Senn (jas) -DLink DI701 w/PPPOE, Win32 Default Route
# Jim Richardson -RT314 tests
# Andrew Gillham -NetBSD route detection
# K Scott -Netgear logout page
# Neal Probert -custom dns bug
# Dave Burris -sco openserver support
# Jerome Sautret -Eicon modem support
# Daryl Boyd -Nortel Instant Internet modem support
# John Ruttenberg -Nexland Pro800Turbo support, and auth fixes
# Tony Scicchitano -New SMC Barricade with password
# Michael O'Quinn -searching syslog option for IP
# Lucas Bruand -Check datfile for "w" mode
# Jon Hart -Pointing out 255 can be used in dotted quad
# Cedric Moreau -Alcatel Speed Touch Pro
# Frank Adcock -DLink DI804 patch
# Darren Tucker -tracking down 404 handling error
# Tristan Hill -snmpget option
# Victor Ng -platform strings case insensitive
# David Jordan -Netgear338 support
# Juha Ylitalo -code cleanup patches
# Larry Kluger -DLink DI713P support
# Douglas Henke -Siemens SpeedStream 2620 with password
# Paul Andreassen -add port forwarding for Alcatel Speed Touch Pro
# J.D. Bronson -upper opts typo, netgear 3114 fixes, zywall 10
# Adam Jenkins -Barricade 7004VWBR patch see --VWBR
# Stephan Allene -DLink DSL504 support
# Stephan Allene -Correct bug with DLink DSL504 support
# Carl John Nobile -badauth bug fix
# Cobe Higginbottom -DI704 no password patch
# Marc Tanner -DI614+ notes
# For CISCO IOS: Hansjoerg G.Henker BitH@GMX.DE - www.c-bit.org
# Brad Crittenden -VT1000v patch
# Mark Keisler -default route detection fix
# Jason Anderson -Linksys RT31P2 patch
# Tuan Hoang -SMC Barricade logout fix
# Robert Holland -Adtran Netvanta support
#
# global constants
#
Updatehost = "members.dyndns.org"
Updatepage = "/nic/update"
Useragent = "ipcheck/" + Version
Touchage = 25 # days after which to force an update
# Touchage = 0 means don't ever force
Linuxip = "/sbin/ifconfig"
Win32ip = "ipconfig /all"
Sunip = "/usr/sbin/ifconfig"
BSDip = "/sbin/ifconfig"
Macip = "/sbin/ifconfig"
Beosip = "netstat"
Os2ip = "ifconfig"
scoip = "/etc/ifconfig"
Otherip = "/sbin/ifconfig"
Linuxrt = "/sbin/route -n"
Win32rt = "route print"
Sunrt = "/bin/netstat -irn"
BSDrt = "/sbin/route -n get default"
Macrt = "/usr/sbin/netstat -r"
Beosrt = "netstat"
Os2rt = "route -n get default"
scort = "/usr/bin/netstat -nr"
Otherrt = "/sbin/route -n show"
# regular expression for address
Addressgrep = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
def Usage():
print """
Make sure you can write to the current directory for data
files and that you always run from the same directory.
The first time you run the script, you will be asked to run
with the --makedat option in addition to any other options.
This will create the data files for the hostnames and options
your specify on the command line. You should only do this once.
Subsequent runs should be made without the --makedat option.
For help with different options: python ipcheck.py -h
For supported devices listing : python ipcheck.py --devices
For long detailed help text : python ipcheck.py --help
Example 1: the external IP is on eth0 of the current machine
python ipcheck.py -l -i eth0 username password hostnames
Example 2: you are using the Linksys routing device
python ipcheck.py -l -L linksyspassword username password hostnames
Example 3: you want to use web based ip detection
python ipcheck.py -l -r checkip.dyndns.org:8245 ...
where ... is your dyndns username password and hostnames.
Hostnames should be comma delimited if there are more than one.
"""
def Options():
print """
Usage : ipcheck.py [options] Username Password Hostnames
or ipcheck.py [options] --acctfile acct_info_file
Options: -a address manually specify the address
-r URL NAT router, use web IP detection
-A text scan syslog for an IP after text (Unix only)
-F filename guess the WAN IP from a firewall log
-b backup mx option ON (default OFF)
-c custom dns option (default dynamic)
-d dir directory for data files (default current)
-e script execute script after a successful update
-f force update regardless of current state
-g NAT router, let dyndns guess your IP
(do not use this in a cronjob, try -r)
-h print this help text
--help print all available help text
-i interface interface for local address (default ppp0)
-j disable https
-l log debugging text to ipcheck.log file
--syslog log debugging text to syslog (Unix only)
-m mxhost mx host (default NOCHG)
-o set dyndns offline mode
-p proxy bypass on port 8245
-q quiet mode (unless there is an error)
-s static dns option (default dynamic)
-t test run, do not send the update
-v verbose mode
-w wildcard mode ON (default OFF)
--makedat create the ipcheck.dat file by dns lookup
--devices print router options (Linksys, Netgear, etc)
-n ip the router IP address on the internal lan
For help with different options: python ipcheck.py -h
For supported devices listing : python ipcheck.py --devices
For long detailed help text : python ipcheck.py --help
"""
def Devices():
print """
The script will locate the address of your router automatically by
looking at the default route of the machine you are running on.
Then it will read the status page for the external IP address
and use that for updates. You need to specify the admin password
with the appropriate option."""
# remember -A already used above
print """
--pfile device password below is actually a filename
-B password New Barricade with password on port 88
--VWBR Use with -B to indicate 7004VWBR Router
-C password Cisco (667i) DSL router password
-D password Draytek (Vigor2000) NAT router password
-E Eicon Diva (no password needed)
-G UgatePlus (no password needed)"""
# remember -F already used above
print """
-H password HawkingTech router password
-I password Cisco (700 series) ISDN router password
-J password ZyXEL prestige 642ME router password
-K password Compex NetPassage 15
-L password Linksys (BEFSR41) NAT router password
-M password MacSense password
-N password Netgear RT311 NAT router password
-O password Netopia (R9100) NAT router password
-P port[,password]
Nexland Pro800Turbo, WAN port, port==any use the
first connected port; port=[01] use the port'th port
if available, else any; port=-[01] use port'th port
if available, else fail. Specify password if
required. For example, -P any,123 says to use the
first port and password 123. -P 1 says prefer port
#1 and no password is required. -P -0,xyz forces
port 0 and uses password xyz.
-Q pword,iface password and interface for Instant Internet
-R password Netgear FR3114 password
-S SMC Barricade (no password needed)
--WBR password Use with -S if 2404WBR with password
-T password Alcatel Speed Touch Pro password
(you can also try -r 10.0.0.138/cgi/router/)
-V password Eicon Diva (see -E for no password)
-W password Watchguard SOHO NAT firewall password
-X Nexland router (no password set)
-Y password Cayman DSL 3220H NAT router password
-Z password ZyXEL 642R and Zywall 10 router password
-1 password DLink DSL504 password
-2 password Siemens SpeedStream 2620 router password
-3 password Netgear RT338 ISDN router
-4 password Gnet model BB0040 ADSL router password
-5 DLink DI704 with no password
-6 password DLink DI704 password
-7 password DLink DI701 password
-8 password DLink DI804/DI614+ password
-9 password DLink DI713P password
--VT1000v Motorola VT1000v VoIP voice terminal (no password needed)
--Netvanta=password
Adtran Netvanta series routers,
both telnet and 'enable' passwords
must be configured to be same value
You can change the default username for the above devices with:
-U username override the default NAT router username
leave this option out to use the default
For Cisco IOS devices and any others that understand SNMP, you
can also use --snmp to detect the external IP.
--snmp snmp_agent,community,numeric_objectid
You will need the v1.x pysnmp module from http://pysnmp.sourceforge.net/
The snmp code does not work with v2.x or 3.x of pysnmp
You also need to know the agent, community and numeric objectid:
python ipcheck.py --snmp 172.62.254.254,public,.1.3.5.2.1.2.10.2.5.4 ...
where ... = username password hostnames
Alternate/Generic SNMP retrieval
--snmpget snmp_agent,community,numeric_objectid
You will need the v1.x pysnmp module from http://pysnmp.sourceforge.net/
The snmp code does not work with v2.x or 3.x of pysnmp
You also need to know the agent(hostname or ip), community and
numeric objectid:
python ipcheck.py --snmpget router,public,.1.3.6.1.4.1.343.6.23.1.12.1.2.3 ...
where ... = username password hostnames
This option will do a snmp get to the specified objectid which needs to be
that of the ip to be used in the update
--forward port[/protocol],...
Ports to be forward from your router to this machine.
Defaults to tcp protocol. Stay set until router turned off.
example: -T password --forward=80,time/udp,21/6
"""
def HelpText():
print """
Start ipcheck.py with no arguments to get some quick examples.
The script creates data files in the current working directory.
Make sure you have write permission and that you run the script
from the same directory each time. You can use the -d option
to specify an alternate directory for data files.
The first time you run the script, you will be asked to run
with the --makedat option. This will create the data files
and complete the update. You should only do this once.
Subsequent runs should be made without the --makedat option.
If -f is set, all hosts will be updated regardless of the
current error, wait or IP state. You should never need this.
You can place your username password and hostnames in a file
(all on the first line) and use the --acctfile option if you do
not wish your password to show up on a ps.
The best way to run ipcheck is in the /etc/ppp/ip-up.local file
or the BSD ppp.linkup file (you will need to sleep 30 before
running the script since ppp.linkup runs before the link is up.)
The script will also run from a cronjob. Just make sure the
hostnames are the same in each execution. You should make sure
it is using the same directory each time for data files. The -d
option can be used to specify where data files go.
The file ipcheck.dat contains the IP address and hostnames
used in the last update. If the ipcheck.dat file is older
than """ + `Touchage` + """ days, an update will be made to touch the hostnames.
The file ipcheck.wait is created if dyndns requests a wait
before retrying. This file will be automatically removed when
the wait is no longer in effect.
The file ipcheck.err is created if the response is an error.
It will not try to update again until this error is resolved.
You must remove the file yourself once the problem is fixed.
If your ISP has a badly behaved transparent proxy on port 80
traffic, you can try the -p option to use port 8245.
If a http message is sent to dyndns.org, the response will be
saved in the ipcheck.html file.
Custom domains can be specified with the -c option. You must
first complete the create database step on the Dyndns web page.
Suppose you have the domain ipcheck.org defined as an A record
and your nodes aliased to ipcheck.org with CNAME records. Use:
python ipcheck.py -c username password ipcheck.org
Note that if you intended to maintain both a custom domain and
a dyndns domain (ie. ipcheck.dyndns.org) you should be using
the -d option to keep the data files in separate directories.
The custom domains are not compatible with the mx, backmx and
wildcard options. Setup your database accordingly.
The script can find your public IP address in one of several ways:
1) interface IP detection is the default method and appropriate
if the machine you are running on has an interface with the public
IP addressed assigned. The script knows how to query various
operating systems for the address of an interface specified
with the -i option (default ppp0). Note on Win32 systems
specify the MAC address device after -i and on BeOS systems
specify the interface number after -i (eg. -i 1).
2) router IP detection is used if you have a routing device
such as a Netgear RT311. Use the --devices option to get a
help on specific devices. This method is used by the script
if you specify one of the device-related options.
3) web IP detection may be used if your device is not supported
python ipcheck.py -r checkip.dyndns.org:8245 ...
where ... = username password hostnames
This method is used if you specify the -r option.
IMPORTANT: Do not run web based IP detection more often
than once every 15 minutes. It is costing dyndns bandwidth.
4) you can explicitly set the desired IP address with -a
5) when -g is used, the script will not send any IP address
at all (even ones detected by the previous options). Only
the account information will be sent to the dyndns server.
The dyndns server will assign the hostnames to the source
IP address of the request. The assigned address is saved in
the ipcheck.dat file. IMPORTANT: Do not run this from a cronjob
unless you know the address saved in the ipcheck.dat file
matches locally detected public IP to prevent unnecessary updates.
If your have an unsupported device and are willing to help with
some testing, email me.
The ipcheck homepage can be found at:
http://ipcheck.sourceforge.net/
Client development information can be found at:
http://support.dyndns.org/dyndns/clients/devel/
Please include the ipcheck.log file if you email me with a problem.
kal@users.sourceforge.net
"""
class Logger:
#
# open a new log file in the target dir if logging
# a race condition if there are tons of scripts
# starting at the same time and should really use locking
# but that would be overkill for this app
#
def __init__(self, logname = "ipcheck.log", verbose = 0, logging = 0, use_syslog = 0):
self.logname = logname
self.verbose = verbose
self.logging = logging
self.syslog = use_syslog
self.prefix = "ipcheck.py: "
asctime = time.asctime(time.localtime(time.time()))
if self.syslog:
syslog.openlog("ipcheck")
if self.logging:
self.logfp = open(self.logname, "w")
self.logfp.write(Useragent + "\n")
self.logfp.write(self.prefix + asctime + "\n")
self.logfp.write(self.prefix + "logging to " + self.logname + "\n")
self.logfp.close()
if self.verbose:
print Useragent
print self.prefix + asctime
# normal logging message
def logit(self, logline):
if self.verbose:
print self.prefix + logline
if self.syslog:
syslog.syslog(logline)
if self.logging:
self.logfp = open(self.logname, "a")
self.logfp.write(self.prefix + logline + "\n")
self.logfp.close()
# logging message that gets printed even if not verbose
def logexit(self, logline):
print self.prefix + logline
if self.logging:
self.logfp = open(self.logname, "a")
self.logfp.write(self.prefix + logline + "\n")
self.logfp.close()
if self.syslog:
syslog.syslog(logline)
def DefaultRoute(logger, Tempfile):
logger.logit("Searching default route on sys.platform = " + sys.platform)
iphost = ""
platform = string.lower(sys.platform)
if string.find(platform, "win32") != -1:
logger.logit("WIN32 default route detection for router.")
os.system (Win32rt + " > " + Tempfile)
fp = open(Tempfile, "r")
try:
while 1:
fileline = fp.readline()
if not fileline:
break
# jas:
# the code that was here did not work at all for the output
# of 'route print' on my win98 box.
# Here is a very simple version that works well...
tst = string.split(fileline)
if len(tst) > 2 and tst[0] == "0.0.0.0":
iphost = tst[2]
break
finally:
fp.close()
elif string.find(platform, "linux") != -1:
logger.logit("Linux default route detection for router.")
fp = os.popen(Linuxrt, "r")
lines = string.split(fp.read(), "\n")
fp.close()
for fileline in lines:
if string.find(fileline, "UG") != -1:
if string.find(fileline, "0.0.0.0") != -1:
ipmatch = Addressgrep.search(fileline)
ip1 = ipmatch.group()
p1 = string.find(fileline, ip1) + len(ip1)
ipmatch = Addressgrep.search(fileline, p1)
iphost = ipmatch.group()
break
elif string.find(platform, "sunos") != -1:
logger.logit("Sunos default route detection for router.")
fp = os.popen(Sunrt, "r")
content = fp.read()
fp.close()
p1 = string.find(content, "default")
if p1 != -1:
ipmatch = Addressgrep.search(content, p1+8)
iphost = ipmatch.group()
elif string.find(platform, "darwin") != -1:
logger.logit("Darwin default route detection for router.")
fp = os.popen(Macrt, "r")
content = fp.read()
fp.close()
p1 = string.find(content, "default")
if p1 != -1:
ipmatch = Addressgrep.search(content, p1+8)
iphost = ipmatch.group()
elif string.find(platform, "netbsd") != -1:
logger.logit("NetBSD default route detection for router.")
fp = os.popen(BSDrt, "r")
content = fp.read()
fp.close()
p1 = string.find(content, "gateway")
if p1 != -1:
ipmatch = Addressgrep.search(content, p1+8)
iphost = ipmatch.group()
elif string.find(platform, "freebsd") != -1:
logger.logit("Freebsd default route detection for router.")
fp = os.popen(BSDrt, "r")
content = fp.read()
fp.close()
p1 = string.find(content, "gateway")
if p1 != -1:
ipmatch = Addressgrep.search(content, p1+8)
iphost = ipmatch.group()
elif string.find(platform, "os2") != -1:
logger.logit("OS2 default route detection for router.")
os.system (Os2rt + " > " + Tempfile)
fp = open(Tempfile, "r")
while 1:
fileline = fp.readline()
if not fileline:
break
p1 = string.find(fileline, "default")
if p1 != -1:
ipmatch = Addressgrep.search(fileline, p1+8)
iphost = ipmatch.group()
break
fp.close()
elif string.find(platform, "sco") != -1:
logger.logit("SCO default route detection for router.")
os.system (Scort + " > " + Tempfile)
fp = open(Tempfile, "r")
while 1:
fileline = fp.readline()
if not fileline:
break
p1 = string.find(fileline, "default")
if p1 != -1:
ipmatch = Addressgrep.search(fileline, p1+8)
iphost = ipmatch.group()
break
fp.close()
elif string.find(platform, "beos") != -1:
logger.logexit("BeOS default route detection via network settings file.")
fp = open("/boot/home/config/settings/network", "r")
while 1:
fileline = fp.readline()
if not fileline:
break
p1 = string.find(fileline, "ROUTER")
if p1 != -1:
ipmatch = Addressgrep.search(fileline, p1+8)
iphost = ipmatch.group()
break
fp.close()
else:
logger.logit("Unknown platform default route detection for router.")
os.system (Otherrt + " > " + Tempfile)
fp = open(Tempfile, "r")
while 1:
fileline = fp.readline()
if not fileline:
break
p1 = string.find(fileline, "default")
if p1 != -1:
ipmatch = Addressgrep.search(fileline, p1+8)
iphost = ipmatch.group()
break
fp.close()
return iphost
def BasicAuth(logger, iphost, page, user, passwd, outfile):
ipdata = ""
try:
logger.logit("Basic authentication page: " + page)
h1 = httplib.HTTP(iphost)
h1.putrequest("GET", page)
fakeagent = "Mozilla/4.76 [en] (X11; U; Linux 2.4.1-0.1.9 i586)"
h1.putheader("USER-AGENT", fakeagent)
authstring = base64.encodestring(user + ":" + passwd)
authstring = string.replace(authstring, "\012", "")
h1.putheader("AUTHORIZATION", "Basic " + authstring)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "Failed connecting to router at " + iphost
logger.logexit(logline)
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
# create an output file of the response
fp = open(outfile, "w")
fp.write(ipdata)
fp.close()
logger.logit(outfile + " file created")
return ipdata
#
# taken directly from the examples directory in pysnmp distribution
# http://pysnmp.sourceforge.net/
#
# results of run are stored in retval and returned
#
class snmptable (session.session):
"""Retrieve a table from remote SNMP process
"""
def __init__ (self, agent, community):
"""Explicitly call superclass's constructor as it gets overloaded
by this class constructor and pass a few arguments alone.
"""
session.session.__init__ (self, agent, community)
def run (self, objids):
"""Query SNMP agent for one or more Object IDs. The objid
argument should be a list of strings where each string
represents an Object ID in dotted numbers notation
(e.g. ['.1.3.6.1.4.1.307.3.2.1.1.1.4.1']).
"""
# clear the retval
retval = []
# Convert string type Object ID's into numeric representation
numeric_objids = map (self.str2nums, objids)
# BER encode SNMP Object ID's to query
encoded_objids = map (self.encode_oid, numeric_objids)
# Since we are going to _query_ SNMP agent for Object ID's
# associated value, there will be no variable values passed to
# SNMP agent.
encoded_values = []
# Remember the beginning of the table
head_encoded_objid = encoded_objids[0]
# Traverse the agent's MIB
while 1:
# Build a complete SNMP message of type 'GETNEXTREQUEST', pass it
# a list BER encoded Object ID's to query and an empty list of values
# associated with these Object ID's (empty list as there is no point
# to pass any variables values along the SNMP GETNEXT request)
question = self.encode_request ('GETNEXTREQUEST', encoded_objids, encoded_values)
# Try to send SNMP message to SNMP agent and receive a response.
answer = self.send_and_receive (question)
# Catch SNMP exceptions
try:
# As we get a response from SNMP agent, try to disassemble SNMP reply
# and extract two lists of BER encoded SNMP Object ID's and
# associated values).
(encoded_objids, encoded_values) = self.decode_response (answer)
# SNMP agent reports 'no such name' when table is over
except error.SNMPError, why:
# If NoSuchName
if why.status == 2:
# Return as we are done
return retval
else:
raise error.SNMPError(why.status, why.index)
# Stop at the end of the table
if not self.oid_prefix_check (head_encoded_objid, encoded_objids[0]):
# Return as we are done
return retval
# Decode BER encoded Object ID.
objids = map (self.decode_value, encoded_objids)
# Decode BER encoded values associated with Object ID's.
values = map (self.decode_value, encoded_values)
# Convert two lists into a list of tuples for easier printing
results = map (None, objids, values)
# Just print them out
# for (objid, value) in results:
# print objid + ' ---> ' + str(value)
retval = retval + results
def getrow (self, objid):
"""Query SNMP agent for one Object ID. The objid argument
should be a string representing a Object ID in dotted
numbers notation
(e.g. '.1.3.6.1.4.1.307.3.2.1.1.1.4.1').
"""
# Convert string type Object IDs into numeric representation
numeric_objid = self.str2nums(objid)
# BER encode SNMP Object IDs to query
encoded_objid = self.encode_oid(numeric_objid)
# Build a complete SNMP message
question = self.encode_request ('GETREQUEST', [encoded_objid], [])
# Try to send SNMP message to SNMP agent and receive a response.
answer = self.send_and_receive (question)
# As we get a response from SNMP agent, try to disassemble SNMP reply
# and extract two lists of BER encoded SNMP Object IDs and
# associated values).
(_encoded_objids, encoded_values) = self.decode_response (answer)
# Decode BER encoded value.
return self.decode_value(encoded_values[0])
###########################################################################
# Ipcheckfile is common baseclass for Datfile and Errorfile
class Ipcheckfile:
# Constructor
# You can give filename in here or leave it later.
def __init__(self, fname=None):
self.fname = fname
# getFilename
# Return: Filename (just matter of courtesy to make method for it)
def getFilename(self):
return self.fname
# setFilename (just matter of courtesy to make method for it)
def setFilename(self, fname):
self.fname = fname
# exists
# Return: 1, file exists
# 0, file doesn't exist
# Note: this doesn't say that you can necessarily read it.
def exists(self):
exists = 0
if "access" in os.__dict__.keys():
exists = os.access (self.fname, os.F_OK)
else:
try:
fp = open (self.fname, "r")
fp.close()
exists = 1
except:
pass
return exists
###########################################################################
# Datfile handles reading and writing of datfile.
# Format:
# IPaddress
# hostname1
# hostname2
# hostname3
# ...
# Variables:
# - fname - name of datfile
# - ip - our public IP address
# - hostnames - list of hostnames related to the IP address on first line.
class Datfile(Ipcheckfile):
#
# Constructor
def __init__(self, fname = None):
Ipcheckfile.__init__(self, fname)
self.ip = None
#
# Age of file based on difference between current time and the time,
# when it was last modified.
# Return: time difference in seconds.
def getAge(self):
currtime = time.time()
mtime = os.stat(self.fname)[stat.ST_MTIME]
fileage = (currtime - mtime) / (60*60*24)
return fileage
#
# read
# Read content of file and return tuple, where first variable is
# your public IP and second is list of hostnames assosiated to it.
# Return: (ip,list of hostnames)
def read(self):
fp = open(self.fname, "r")
lines = string.split(fp.read(), "\n")
fp.close()
ip = lines[0]
hosts = []
for line in lines[1:]:
if line:
hosts.append(line)
assert hosts
return (ip,hosts)
# setIP
# setIP for write() that will happen later.
def setIP(self, ip):
self.ip = ip
# write
# Write valid datfile based on ip and hostnames information.
# If caller has not given them, use the values that have been
# stored into instance variables.
def write(self, ip = None, hostnames = None):
if not ip:
ip = self.ip
assert ip and hostnames
fp = open(self.fname, "w")
fp.write(ip + "\n")
for host in hostnames:
fp.write(host + "\n")
fp.close()
###########################################################################
# Errorfile handles reading, writing and analyzing of errfile.
class Errorfile(Ipcheckfile):
#
# Constructor
# You can give filename in here or leave it later.
def __init__(self, logger, fname = None):
self.logger = logger
Ipcheckfile.__init__(self, fname)
# analyze
# analyze content of existing errorfile.
# Parameters:
# - username that user would like to use.
# - password that user would like to use.
# - hostnames that user would like to update.
# Return:
# 1 - if fatal errors were encountered
# 0 - if its OK to continue
def analyze(self, username, password, hostnames):
# generic_cases always print same message"
generic_cases = {
"badagent" : ["Badagent contact author at kal@users.sourceforge.net."],
"dnserr" : ["Contact support@dyndns.org about dnserr error.",
"Attach the ipcheck.html file for details.",
"Erase the ipcheck.err file when the problem is fixed."],
"numhost" : ["Contact support@dyndns.org about numhost error.",
"Attach the ipcheck.html file for details.",
"Erase the ipcheck.err file when the problem is fixed."],
"shutdown" : ["Service shutdown from dyndns.org",
"Check http://www.dyndns.org/status.shtml",
"Erase the ipcheck.err file when shutdown is over."]
}
# one_param cases add first argument to the end of first line.
one_param = {
"badsys" : ["system error",
"Erase the ipcheck.err file if this is correct now."],
"!donator" : ["!donator",
"Erase the ipcheck.err file when this problem is fixed."],
}
# hostname cases are shown only if first argument in error matches with
# one of the hostnames that we would like to update.
# Problematic hostname is shown at the end of first line.
hostname_cases = {
"abuse" : ["abuse lockout",
"Use the form at http://support.dyndns.org/dyndns/abuse.shtml",
"Erase the ipcheck.err file when dyndns notifies you (by email)." ],
"!active" : ["!active",
"You need to activate your Custom domain first.",
"Dyndns may require it to be properly delegated.",
"Erase the ipcheck.err file when the problem is fixed."],
"nohost" : ["nohost",
"You may be trying -s for a dynamic host or vice versa.",
"Erase the ipcheck.err if file this host is now created."],
"notfqdn" : ["notfqdn",
"Erase the ipcheck.err file if this is really correct."],
"!yours" : ["!yours",
"Erase the ipcheck.err file when the problem is fixed."],
}
self.logger.logit("Handling errors in ipcheck.err file.")
errors = []
fatal = 0
if self.exists():
fp = open(self.fname, "r")
errors = string.split(fp.read(), "\n")
fp.close()
for err in errors:
fatal = 1
errlist = string.split(err, " ")
if err[:7] == "badauth":
self.logger.logit("badauth found.")
if errlist[1] == username and errlist[2] == password:
self.logger.logexit("Previous authorization error encountered for")
self.logger.logexit("Username:" + username)
self.logger.logexit("Password:" + password)
self.logger.logexit("Erase the ipcheck.err file if this is correct now.")
else:
self.logger.logit("trying new username or password.")
self.logger.logit("ipcheck.err file removed and continuing.")
os.unlink(self.fname)
fatal = 0
elif errlist[0] in generic_cases.keys():
self.logger.logit(errlist[0] + " found.")
for line in generic_cases[errlist[0]]:
self.logger.logexit(line)
elif errlist[0] in one_param.keys():
self.logger.logit(errlist[0] + " found.")
self.logger.logexit("Previous " + one_param[errlist[0]][0] + " encountered for " + errlist[1])
for line in one_param[errlist[0]][1:]:
self.logger.logexit(line)
elif errlist[0] in hostname_cases.keys():
self.logger.logit(errlist[0] + " found.")
if errlist[1] in hostnames:
self.logger.logexit("Previous " + hostname_cases[errlist[0]][0] + " encountered for host: " + errlist[1])
for line in hostname_cases[errlist[0]][1:]:
self.logger.logexit(line)
else:
fatal = 0
elif err:
self.logger.logexit("Unrecognized error in ipcheck.err file.")
self.logger.logexit("Erase the ipcheck.err if there is no problem.")
else:
fatal = 0
if fatal:
break
return fatal
def write(self, description, fatal=None):
if fatal:
mode = "w"
else:
mode = "a"
old = self.exists()
fp = open(self.fname, mode)
fp.write(description + "\n" )
fp.close()
if not old:
self.logger.logit("ipcheck.err FILE CREATED.")
# acctfile has account information about your dyndns account.
# Format: username password hostname1,hostname2,hostname3
# Parameters:
# - acctfile - filename for account information
# - logger - instance of Logger for logging
# Return: ["username", "password", "hostname1,hostname2,hostname3"]
# Exception:
# - sys.exit(-1) in all problems.
def read_acctfile(fname, logger):
try:
fp = open (fname, "r")
data = fp.read()
fp.close()
except:
logger.logexit("Bad acctfile: " + fname)
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
fields = string.split(data)
if len(fields) != 3:
logline = "File does not contain 3 arguments: " + fname
logger.logexit(logline)
sys.exit(-1)
return fields
def read_pfile(fname, logger):
if string.find(fname, "--pfile") != -1:
logger.logexit("Bad usage. Try: --pfile -X filename")
logger.logexit("where X is the option letter for your device.")
logger.logexit("Do not put the filename right after the --pfile option.")
sys.exit(-1)
try:
fp = open (fname, "r")
data = fp.read()
fp.close()
except:
logger.logexit("Bad pfile: " + fname)
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
# strip training CRLF
if data[-1] == '\n' or data[-1] == '\r':
data = data[:-1]
if data[-1] == '\n' or data[-1] == '\r':
data = data[:-1]
return data
# check_ip verifies that ip address, which we are planning
# to send to dyndns.org is really valid.
# Parameters:
# - localip - ip that we are planning to send
# Return:
# - None, if its valid
# - string, which explains why its not valid.
def check_ip(localip):
logline = None
if not localip:
# check if the router elif's found no address
logline = "No address found on router."
elif localip == "0.0.0.0":
# check if detected ip is not valid
logline = "The router has external IP 0.0.0.0 assigned. "
elif string.count(localip, ".") != 3:
# check the IP to make sure it is sensible
logline = "Invalid local address " + localip
else:
octets = string.split(localip, ".")
ip = [0,0,0,0]
try:
for i in range(4):
ip[i] = int(octets[i])
except:
ip = [0,0,0,0]
# 0-255 in first three allowed, 1-255 in last also
if ip[0] < 0 or ip[0] > 255 \
or ip[1] < 0 or ip[1] > 255 \
or ip[2] < 0 or ip[2] > 255 \
or ip[3] < 0 or ip[3] > 255:
logline = "Invalid local address " + localip
return logline
# check_public_ip verifies that given ip address does not belong to
# one of those private ip address spaces, which are reserved for
# intranet use.
# Parameters:
# - localip - ip that needs checking
# Return:
# - None, if its private address
# - string, if its valid address
def check_public_ip(localip):
if localip[:4] != "127." \
and localip[:8] != "192.168." \
and localip[:3] != "10." \
and localip[:4] != "172." \
and localip[:2] != "0." \
and string.find(localip, "255") == -1:
return localip
return None
def _main(argv):
#
# ROUTER SUPPORT GLOBALS
#
# leave Linksys_host = "" to autodetect via the default route
# enter an ip here to skip the autodetect, this goes for all
# the xxxx_host variables below
#
routerIP = ""
#
# Linksys router support details from bgriggs@pobox.com
#
Linksys_user = " "
Linksys_page = "/Status.htm"
Macsense_user = " "
Macsense_page = "/Status.htm"
#
# Motorola VT1000v
MotorolaVT1000v_page = "/startupdata.html"
#username and password are not needed
#
# Netgear router support
#
Netgear_user = "admin"
Netgear_page = "/mtenSysStatus.html"
Netgear314_page1 = "/rpMten.html"
Netgear314_page2 = "/mtenSysStatus.html"
NetgearFR_page = "/auth.html"
Netgear_logout = "/Logout.html"
Netgear3114_user = "admin"
Netgear3114_page1 = "/"
Netgear3114_page2 = "/st_dhcp.htm"
Netgear3114_page3 = "/logout.htm"
#
# DLink DI-804/DI-614+ router support
#
DI804_user = "admin"
DI804_page = "/doc/m3.htm"
DI614_page = "/st_devic.html"
#
# DLink DI-713P router support
#
DI713P_user = "root"
DI713P_page = "/cgi-bin/logi"
#
# DLink DI-704 router with no password support
#
DInop_user = "admin"
DInop_page = "status.htm"
#
# DLink DI-704 router support
#
DI704_user = "root"
DI704_page = "/cgi-bin/logi"
#
# DLink DSL-504 router support
#
DSL504_user = "admin"
DSL504_page = "/sum/RoutingTable_ntpr.html"
#
# Draytek Vigor2000 router support
#
Draytek_user = "admin"
Draytek_page = "/doc/digisdn.sht"
#
# Netopia R9100 router support
#
Netopia_user = ""
Netopia_page = "/WanEvtLog"
#
# Cisco routers (667 and 770)
# uses telnet with no user name
#
#
# Adtran Netvanta routers
# uses telnet with no user name
#
#
# SMC Barricade
#
SMC_page = "/status.HTM"
#username and password are not needed
#
# HawkingTech router support
#
Hawking_user = "admin"
Hawking_page = "/Monitor.htm"
#
# ZyXEL router support, uses telnet
#
#
# DI701 router support, uses telnet
#
#
# Watchguard SOHO firewall/router support
#
Watchguard_user = "admin"
Watchguard_page = "/sysstat.htm"
Watchguard_page2 = "/external.htm"
#
# Nexland (but see Pro800Turbo, below)
#
Nexland_page = "/status.htm"
#username and password are not needed
#
# Nexland Pro800Turbo
#
Pro800Turbo_page = "/status.html"
Pro800Turbo_port = "any"
Pro800Turbo_port_number = 0
#username and password are not needed
#
# UgatePlus
#
Ugate_page = "/st_dhcp.htm"
#username and password are not needed
#
# Eicon Diva 2430 SE ADSL Modem
#
Eicon_page = "/Status.htm"
#username and password are not needed
#
# Eicon Diva with password
#
Veicon_user = ""
Veicon_page = "/login.htm"
# Instant Internet router
#
# Compex NetPassage 15
# uses telnet with no username
#
#
# Cayman DSL 3220-H
# uses telnet
#
Cayman_user = "admin"
#
# Gnet model BB0040 ADSL router
# uses telnet
#
Gnet_user = ""
#
# Netgear RT338 ISDN router
# uses telnet
#
Netgear338_user = ""
#
# Newer SMC Barricade with password on port 88
#
Barricade_user = "admin"
Barricade_page = "/status.HTM"
#
# Siemens SpeedStream 2620 with password on port 88
#
Siemens2620_page = "/MAIN.HTM"
#
# Alcatel Speed Touch Pro uses telnet
#
# username is not needed
Alcatel_user = " "
#
# default options
#
opt_address = ""
opt_force = 0
opt_logging = 0
opt_syslog = 0
opt_verbose = 0
opt_hostnames = ""
opt_interface = "ppp0"
opt_username = ""
opt_password = ""
opt_static = 0
opt_wildcard = 0
opt_backupmx = 0
opt_mxhost = "NOCHG"
opt_proxy = 0
opt_router = ""
opt_guess = 0
opt_quiet = 0
opt_offline = 0
opt_execute = ""
opt_directory = ""
opt_acctfile = ""
opt_pfile = 0
opt_natuser = ""
opt_forward = []
opt_Linksys_password = ""
opt_Linksys_router = 0
opt_Netgear_password = ""
opt_Netgear3114_password = ""
opt_Draytek_password = ""
opt_Netopia_password = ""
opt_Cisco_password = ""
opt_SMC_router = 0
opt_Nexland_router = 0
opt_Pro800Turbo_router = 0
opt_ISDNCisco_password = ""
opt_Hawking_password = ""
opt_Zyxel_password = ""
opt_Zyxel_ME_password = ""
opt_Watchguard_password = ""
opt_DInop_router = 0
opt_DI704_password = ""
opt_DI701_password = ""
opt_DI713P_password = ""
opt_DI804_password = ""
opt_DSL504_password = ""
opt_snmp_agent = ""
opt_snmp_community = ""
opt_snmp_objectid = ""
opt_snmp_agent_prefix = ""
opt_custom = 0
opt_testrun = 0
opt_makedat = 0
opt_Compex_password = ""
opt_Cayman_password = ""
opt_Gnet_password = ""
opt_Ugate_router = 0
opt_II_password = ""
opt_II_interface = ""
opt_Eicon_router = 0
opt_Veicon_password = ""
opt_Barricade_password = ""
opt_7004VWBR = 0
opt_WBR = ""
opt_Siemens2620_password = ""
opt_after_syslog = ""
opt_firewall_log = ""
opt_Macsense_password = ""
opt_MotorolaVT1000v_router = 0
opt_AlcatelSTP_password = ""
opt_no_https = 0
opt_Netgear338_password = ""
opt_Netvanta_password = ""
#
# parse the command line options
#
if len(argv) == 1:
Usage()
sys.exit(0)
try:
loweropts = "a:bcd:e:fghi:jlm:n:opqr:stvw"
upperopts = "A:B:C:D:EF:GH:I:J:K:L:M:N:O:P:Q:R:ST:U:V:W:XY:Z:1:2:3:4:56:7:8:9:"
wordopts = ["syslog", "pfile", "acctfile=", "help", "devices", "snmp=", "makedat", "snmpget=", "forward=", "VWBR", "WBR=", "VT1000v", "Netvanta="]
opts, args = getopt.getopt(argv[1:], loweropts+upperopts, wordopts)
except getopt.error, reason:
print reason
sys.exit(-1)
#
# PYTHON GURU NEEDED
#
# Is there any way in python to set argv to hide the command line?
# ala the perl $0 = "orcus [accepting connections]";
#
# http://theoryx5.uwinnipeg.ca/CPAN/perl/pod/perlfaq8/Is_there_a_way_to_hide_perl_s_command_line_from_programs_such_as_ps_.html
#
#
# check verbose, logging and detailed help options first
# check directory to place logging file
#
for opt in opts:
(lopt, ropt) = opt
if lopt == "-l":
opt_logging = 1
elif lopt == "--syslog":
opt_syslog = 1
elif lopt == "-v":
opt_verbose = 1
elif lopt == "--devices":
Devices()
sys.exit(0)
elif lopt == "--help":
Usage()
Options()
Devices()
HelpText()
sys.exit(0)
elif lopt == "-h":
Options()
sys.exit(0)
elif lopt == "-d":
if os.path.isdir(ropt):
opt_directory = ropt
else:
print "bad directory option"
sys.exit()
# fix the dir name to end in slash
if opt_directory[-1:] != "/":
opt_directory = opt_directory + "/"
#
# create the logger object
#
if opt_directory:
logger = Logger(opt_directory + "ipcheck.log", opt_verbose, opt_logging, opt_syslog)
logline = "opt_directory set to " + opt_directory
logger.logit(logline)
else:
logger = Logger("ipcheck.log", opt_verbose, opt_logging, opt_syslog)
#
# check acctfile option
#
for opt in opts:
(lopt, ropt) = opt
if lopt == "--acctfile":
opt_acctfile = ropt
logline = "opt_acctfile set to " + opt_acctfile
logger.logit(logline)
#
# check pfile option
#
for opt in opts:
(lopt, ropt) = opt
if lopt == "--pfile":
opt_pfile = 1
logline = "opt_pfile set"
logger.logit(logline)
if len(args) != 3 and not opt_acctfile:
Usage()
sys.exit(0)
#
# okay now parse rest of the options and log as needed
#
for opt in opts:
(lopt, ropt) = opt
if lopt == "-a":
opt_address = ropt
logline = "opt_address set to " + opt_address
logger.logit(logline)
elif lopt == "-i":
opt_interface = ropt
logline = "opt_interface set to " + opt_interface
logger.logit(logline)
elif lopt == "-f":
opt_force = 1
logline = "opt_force set "
logger.logit(logline)
elif lopt == "-j":
opt_no_https = 1
logline = "opt_no_https set "
logger.logit(logline)
elif lopt == "-w":
opt_wildcard = 1
logline = "opt_wildcard set "
logger.logit(logline)
elif lopt == "-s":
opt_static = 1
logline = "opt_static set "
logger.logit(logline)
elif lopt == "-c":
opt_custom = 1
logline = "opt_custom set "
logger.logit(logline)
elif lopt == "-b":
opt_backupmx = 1
logline = "opt_backupmx set "
logger.logit(logline)
elif lopt == "-p":
opt_proxy = 1
logline = "opt_proxy set "
logger.logit(logline)
elif lopt == "-m":
opt_mxhost = ropt
logline = "opt_mxhost set to " + opt_mxhost
logger.logit(logline)
elif lopt == "-r":
opt_router = ropt
logline = "opt_router set to " + opt_router
logger.logit(logline)
elif lopt == "-g":
opt_guess = 1
logline = "opt_guess set "
logger.logit(logline)
elif lopt == "-t":
opt_testrun = 1
logline = "opt_testrun set "
logger.logit(logline)
elif lopt == "--makedat":
opt_makedat = 1
logline = "opt_makedat set "
logger.logit(logline)
elif lopt == "-q":
opt_quiet = 1
logline = "opt_quiet set "
logger.logit(logline)
elif lopt == "-o":
opt_offline = 1
logline = "opt_offline set "
logger.logit(logline)
elif lopt == "-e":
opt_execute = ropt
logline = "opt_execute set to " + opt_execute
logger.logit(logline)
elif lopt == "-U":
opt_natuser = ropt
logline = "opt_natuser set to " + opt_natuser
logger.logit(logline)
Linksys_user = opt_natuser
Macsense_user = opt_natuser
Netgear_user = opt_natuser
Netgear3114_user = opt_natuser
Draytek_user = opt_natuser
Netopia_user = opt_natuser
Hawking_user = opt_natuser
Watchguard_user = opt_natuser
Veicon_user = opt_natuser
Cayman_user = opt_natuser
Gnet_user = opt_natuser
Barricade_user = opt_natuser
DI804_user = opt_natuser
Alcatel_user = opt_natuser
elif lopt == "--VT1000v":
opt_MotorolaVT1000v_router = 1
logline = "opt_MotorolaVT1000v_router set "
logger.logit(logline)
elif lopt == "-M":
if opt_pfile == 1:
opt_Macsense_password = read_pfile(ropt, logger)
logger.logit("opt_Macsense_password from file")
else:
opt_Macsense_password = ropt
logger.logit("opt_Macsense_password from command line")
logger.logit("*" * len(opt_Macsense_password))
elif lopt == "-L":
opt_Linksys_router = 1
if opt_pfile == 1:
opt_Linksys_password = read_pfile(ropt, logger)
logger.logit("opt_Linksys_password from file")
else:
opt_Linksys_password = ropt
logger.logit("opt_Linksys_password from command line")
logger.logit("*" * len(opt_Linksys_password))
elif lopt == "-N":
if opt_pfile == 1:
opt_Netgear_password = read_pfile(ropt, logger)
logger.logit("opt_Netgear_password from file")
else:
opt_Netgear_password = ropt
logger.logit("opt_Netgear_password from command line")
logger.logit("*" * len(opt_Netgear_password))
elif lopt == "-R":
if opt_pfile == 1:
opt_Netgear3114_password = read_pfile(ropt, logger)
logger.logit("opt_Netgear3114_password from file")
else:
opt_Netgear3114_password = ropt
logger.logit("opt_Netgear3114_password from command line")
logger.logit("*" * len(opt_Netgear3114_password))
elif lopt == "-D":
if opt_pfile == 1:
opt_Draytek_password = read_pfile(ropt, logger)
logger.logit("opt_Draytek_password from file")
else:
opt_Draytek_password = ropt
logger.logit("opt_Draytek_password from command line")
logger.logit("*" * len(opt_Draytek_password))
elif lopt == "-O":
if opt_pfile == 1:
opt_Netopia_password = read_pfile(ropt, logger)
logger.logit("opt_Netopia_password from file")
else:
opt_Netopia_password = ropt
logger.logit("opt_Netopia_password from command line")
logger.logit("*" * len(opt_Netopia_password))
elif lopt == "-C":
if opt_pfile == 1:
opt_Cisco_password = read_pfile(ropt, logger)
logger.logit("opt_Cisco_password from file")
else:
opt_Cisco_password = ropt
logger.logit("opt_Cisco_password from command line")
logger.logit("*" * len(opt_Cisco_password))
elif lopt == "-S":
opt_SMC_router = 1
logline = "opt_SMC_router set "
logger.logit(logline)
elif lopt == "-G":
opt_Ugate_router = 1
logline = "opt_Ugate_router set "
logger.logit(logline)
elif lopt == "-E":
opt_Eicon_router = 1
logline = "opt_Eicon_router set "
logger.logit(logline)
elif lopt == "-V":
if opt_pfile == 1:
opt_Veicon_password = read_pfile(ropt, logger)
logger.logit("opt_Veicon_password from file")
else:
opt_Veicon_password = ropt
logger.logit("opt_Veicon_password from command line")
logger.logit("*" * len(opt_Veicon_password))
elif lopt == "-B":
if opt_pfile == 1:
opt_Barricade_password = read_pfile(ropt, logger)
logger.logit("opt_Barricade_password from file")
else:
opt_Barricade_password = ropt
logger.logit("opt_Barricade_password from command line")
logger.logit("*" * len(opt_Barricade_password))
elif lopt == "--VWBR":
opt_7004VWBR = 1
elif lopt == "--WBR":
opt_WBR = ropt
elif lopt == "-Q":
Qopts = string.split(ropt, ",")
if len(Qopts) != 2:
logline = "Bad -Q option: " + ropt
logger.logexit(logline)
sys.exit(-1)
logger.logit(logline)
if opt_pfile == 1:
opt_II_password = read_pfile(Qopts[0], logger)
logger.logit("opt_II_password from file")
else:
opt_II_password = Qopts[0]
logger.logit("opt_II_password from command line")
logger.logit("*" * len(opt_II_password))
opt_II_interface = Qopts[1]
logline = "opt_II_interface = " + opt_II_interface
elif lopt == "-X":
opt_Nexland_router = 1
logline = "opt_Nexland_router set "
logger.logit(logline)
elif lopt == "-P":
opt_Pro800Turbo_router = 1
ropt_save = ropt
cindex = string.find(ropt,",")
if cindex == -1:
ropt_port = ropt
Pro800Turbo_password = None
else:
ropt_port = ropt[:cindex]
Pro800Turbo_password = ropt[cindex+1:]
if ropt_port == 'any':
Pro800Turbo_port = 'any'
else:
if ropt_port[0] == '-':
Pro800Turbo_port = 'force'
ropt_port = ropt_port[1:]
else:
Pro800Turbo_port = 'prefer'
try:
ropt_int = int(ropt_port)
if ropt_int < -1 or ropt_int > 1:
raise ValueError("invalid port value %s" % (ropt_save))
Pro800Turbo_port_number = ropt_int
except:
logline = "Bad -P option %s" % (ropt_save)
logger.logexit(logline)
sys.exit(-1)
logline = "opt_Pro800Turbo port %s %d" % (Pro800Turbo_port,
Pro800Turbo_port_number)
logger.logit(logline)
elif lopt == "--forward":
opt_forward_ports = string.split(ropt, ",")
if len(opt_forward_ports)==0:
logger.logexit("Not ports specified to forward")
sys.exit(-1)
for opt_forward_port in opt_forward_ports:
opt_forward_portprotocol=string.split(opt_forward_port,"/")
if len(opt_forward_portprotocol)==1:
opt_forward_portprotocol=opt_forward_portprotocol+["tcp"]
if len(opt_forward_portprotocol)!=2:
logline = "Bad -forward option %s" % opt_forward_port
logger.logexit(logline)
sys.exit(-1)
opt_forward=opt_forward+[ opt_forward_portprotocol ]
logline = "opt_forward %s" % str(opt_forward)
logger.logit(logline)
elif lopt == "-I":
if opt_pfile == 1:
opt_ISDNCisco_password = read_pfile(ropt, logger)
logger.logit("opt_ISDNCisco_password from file")
else:
opt_ISDNCisco_password = ropt
logger.logit("opt_ISDNCisco_password from command line")
logger.logit("*" * len(opt_ISDNCisco_password))
elif lopt == "-H":
if opt_pfile == 1:
opt_Hawking_password = read_pfile(ropt, logger)
logger.logit("opt_Hawking_password from file")
else:
opt_Hawking_password = ropt
logger.logit("opt_Hawking_password from command line")
logger.logit("*" * len(opt_Hawking_password))
elif lopt == "-J":
if opt_pfile == 1:
opt_Zyxel_ME_password = read_pfile(ropt, logger)
logger.logit("opt_Zyxel_ME_password from file")
else:
opt_Zyxel_ME_password = ropt
logger.logit("opt_Zyxel_ME_password from command line")
logger.logit("*" * len(opt_Zyxel_ME_password))
elif lopt == "-Z":
if opt_pfile == 1:
opt_Zyxel_password = read_pfile(ropt, logger)
logger.logit("opt_Zyxel_password from file")
else:
opt_Zyxel_password = ropt
logger.logit("opt_Zyxel_password from command line")
logger.logit("*" * len(opt_Zyxel_password))
elif lopt == "-2":
if opt_pfile == 1:
opt_Siemens2620_password = read_pfile(ropt, logger)
logger.logit("opt_Siemens2620_password from file")
else:
opt_Siemens2620_password = ropt
logger.logit("opt_Siemens2620_password from command line")
logger.logit("*" * len(opt_Siemens2620_password))
elif lopt == "-3":
if opt_pfile == 1:
opt_Netgear338_password = read_pfile(ropt, logger)
logger.logit("opt_Netgear338_password from file")
else:
opt_Netgear338_password = ropt
logger.logit("opt_Netgear338_password from command line")
logger.logit("*" * len(opt_Netgear338_password))
elif lopt == "-4":
if opt_pfile == 1:
opt_Gnet_password = read_pfile(ropt, logger)
logger.logit("opt_Gnet_password from file")
else:
opt_Gnet_password = ropt
logger.logit("opt_Gnet_password from command line")
logger.logit("*" * len(opt_Gnet_password))
elif lopt == "-5":
opt_DInop_router = 1
elif lopt == "-6":
if opt_pfile == 1:
opt_DI704_password = read_pfile(ropt, logger)
logger.logit("opt_DI704_password from file")
else:
opt_DI704_password = ropt
logger.logit("opt_DI704_password from command line")
logger.logit("*" * len(opt_DI704_password))
elif lopt == "-7":
if opt_pfile == 1:
opt_DI701_password = read_pfile(ropt, logger)
logger.logit("opt_DI701_password from file")
else:
opt_DI701_password = ropt
logger.logit("opt_DI701_password from command line")
logger.logit("*" * len(opt_DI701_password))
elif lopt == "-8":
if opt_pfile == 1:
opt_DI804_password = read_pfile(ropt, logger)
logger.logit("opt_DI804_password from file")
else:
opt_DI804_password = ropt
logger.logit("opt_DI804_password from command line")
logger.logit("*" * len(opt_DI804_password))
elif lopt == "-9":
if opt_pfile == 1:
opt_DI713P_password = read_pfile(ropt, logger)
logger.logit("opt_DI713P_password from file")
else:
opt_DI713P_password = ropt
logger.logit("opt_DI713P_password from command line")
logger.logit("*" * len(opt_DI713P_password))
elif lopt == "-1":
if opt_pfile == 1:
opt_DSL504_password = read_pfile(ropt, logger)
logger.logit("opt_DSL504_password from file")
else:
opt_DSL504_password = ropt
logger.logit("opt_DSL504_password from command line")
logger.logit("*" * len(opt_DSL504_password))
elif lopt == "-W":
if opt_pfile == 1:
opt_Watchguard_password = read_pfile(ropt, logger)
logger.logit("opt_Watchguard_password from file")
else:
opt_Watchguard_password = ropt
logger.logit("opt_Watchguard_password from command line")
logger.logit("*" * len(opt_Watchguard_password))
elif lopt == "-K":
if opt_pfile == 1:
opt_Compex_password = read_pfile(ropt, logger)
logger.logit("opt_Compex_password from file")
else:
opt_Compex_password = ropt
logger.logit("opt_Compex_password from command line")
logger.logit("*" * len(opt_Compex_password))
elif lopt == "-A":
opt_after_syslog = ropt
logline = "opt_after_syslog = " + ropt
logger.logit(logline)
elif lopt == "-F":
opt_firewall_log = ropt
logline = "opt_firewall_log = " + ropt
logger.logit(logline)
elif lopt == "-Y":
if opt_pfile == 1:
opt_Cayman_password = read_pfile(ropt, logger)
logger.logit("opt_Cayman_password from file")
else:
opt_Cayman_password = ropt
logger.logit("opt_Cayman_password from command line")
logger.logit("*" * len(opt_Cayman_password))
elif lopt == "-T":
if opt_pfile == 1:
opt_AlcatelSTP_password = read_pfile(ropt, logger)
logger.logit("opt_AlcatelSTP_password from file")
else:
opt_AlcatelSTP_password = ropt
logger.logit("opt_AlcatelSTP_password from command line")
logger.logit("*" * len(opt_AlcatelSTP_password))
elif lopt == "-n":
routerIP = ropt
logline = "opt_router_ip = " + ropt
logger.logit(logline)
elif lopt == "--snmp":
snmpopts = string.split(ropt, ",")
if len(snmpopts) != 3:
logline = "Bad --snmp option: " + ropt
logger.logexit(logline)
sys.exit(-1)
#
# check snmp agent is an IP address
#
opt_snmp_agent = snmpopts[0]
if string.count(opt_snmp, ".") != 3:
logline = opt_snmp_agent + " bad snmp agent, IP address required"
logger.logexit(logline)
sys.exit(-1)
opt_snmp_agent_prefix = string.join(string.split(opt_snmp_agent, ".", 3)[:2], ".")
#
# community can be anything
#
opt_snmp_community = snmpopts[1]
#
# check the objectid is numeric
#
opt_snmp_objectid = snmpopts[2]
#objid_s = string.split(opt_snmp_objectid, '.')
#objid_s = filter(lambda x: len(x), objid_s)
#try:
# objid_n = map(lambda x: string.atol(x), objid_s)
#except:
# logline = opt_snmp_objectid + " bad snmp objectid, numeric id required"
# logger.logexit(logline)
# sys.exit(-1)
logger.logit("opt_snmp_agent = " + opt_snmp_agent)
logger.logit("opt_snmp_agent_prefix = " + opt_snmp_agent_prefix)
logger.logit("opt_snmp_community = " + opt_snmp_community)
logger.logit("opt_snmp_objectid = " + opt_snmp_objectid)
elif lopt == "--snmpget":
try:
(opt_snmp_agent, opt_snmp_community, opt_snmp_objectid) = string.split(ropt, ',')
except:
logger.logexit("Bad --snmpget option: " + ropt)
sys.exit(-1)
# Check for a half reasonable numeric object id
if re.search("^\.([0-9]+\.)+[0-9]+$",opt_snmp_objectid) == None:
logger.logexit("Bad Object ID: " + opt_snmp_objectid)
sys.exit(-1)
logger.logit("opt_snmp_agent = " + opt_snmp_agent)
logger.logit("opt_snmp_community = " + opt_snmp_community)
logger.logit("opt_snmp_objectid = " + opt_snmp_objectid)
elif lopt == "--Netvanta":
opt_Netvanta_password = ropt
logger.logit("opt_Netvanta_password from command line")
logger.logit("*" * len(opt_Netvanta_password))
#
# handle the username, password, hostnames part
#
if opt_acctfile:
args = read_acctfile(opt_acctfile, logger)
opt_username = args[0]
logline = "opt_username = " + opt_username
logger.logit(logline)
opt_password = args[1]
logger.logit("opt_password = " + "*" * len(opt_password))
opt_hostnames = args[2]
logline = "opt_hostnames = " + opt_hostnames
logger.logit(logline)
hostnames = string.split(opt_hostnames, ",")
#
# taint check, make sure each hostname is a dotted fqdn
#
for host in hostnames:
if not "." in host:
logline = "Bad hostname: " + host
logger.logexit(logline)
sys.exit(-1)
#
# check if hostname is a custom domain
#
domains = [ \
"ath.cx", \
"blogdns.com", \
"blogdns.net", \
"blogdns.org", \
"dnsalias.com", \
"dnsalias.net", \
"dnsalias.org", \
"dynalias.com", \
"dynalias.net", \
"dynalias.org", \
"dyndns.biz", \
"dyndns.info", \
"dyndns.org", \
"dyndns.tv", \
"dyndns.ws", \
"game-host.org", \
"game-server.cc", \
"gotdns.com", \
"gotdns.org", \
"ham-radio-op.net", \
"homedns.org", \
"homeftp.net", \
"homeftp.org", \
"homeip.net", \
"homelinux.com", \
"homelinux.net", \
"homelinux.org", \
"homeunix.com", \
"homeunix.net", \
"homeunix.org", \
"is-a-geek.com", \
"is-a-geek.net", \
"is-a-geek.org", \
"isa-geek.com", \
"isa-geek.net", \
"isa-geek.org", \
"kicks-ass.net", \
"kicks-ass.org", \
"merseine.nu", \
"mine.nu", \
"myphotos.cc", \
"serveftp.net", \
"serveftp.org", \
"servegame.org", \
"shacknet.nu" \
]
if not opt_custom:
for host in hostnames:
h = string.lower(host)
known = 0
for dom in domains:
if dom == h[-len(dom):]:
known = 1
break
if not known:
logline = "WARNING Unknown domain: " + host
logger.logexit(logline)
logger.logexit("If the domain is listed at http://www.dyndns.org/services/dyndns/domains.html")
logger.logexit("then email kal@users.sourceforge.net to add the domain.")
logger.logexit("Otherwise, you should be using -c for custom domains.")
#
# taint check the mx host
#
if opt_mxhost:
if string.find(opt_mxhost, "NOCHG") != -1:
opt_mxhost = "NOCHG"
elif not "." in opt_mxhost:
logline = "Bad mxhost: " + opt_mxhost
logger.logexit(logline)
sys.exit(-1)
#
# log the pwd
#
if os.environ.has_key("PWD"):
logger.logit("PWD = " + os.environ["PWD"])
#
# create the full path names
#
datfile = Datfile("ipcheck.dat")
if opt_directory:
datfile.setFilename(opt_directory + datfile.getFilename())
logger.logit("Datfile = " + datfile.getFilename())
errfile = Errorfile(logger, "ipcheck.err")
if opt_directory:
errfile.setFilename(opt_directory + errfile.getFilename())
logger.logit("Errfile = " + errfile.getFilename())
Waitfile = "ipcheck.wait"
if opt_directory:
Waitfile = opt_directory + Waitfile
logger.logit("Waitfile = " + Waitfile)
Htmlfile = "ipcheck.html"
if opt_directory:
Htmlfile = opt_directory + Htmlfile
logger.logit("Htmlfile = " + Htmlfile)
Tempfile = "ipcheck.tmp"
if opt_directory:
Tempfile = opt_directory + Tempfile
logger.logit("Tempfile = " + Tempfile)
#
# determine the local machine's ip
#
localip = ""
iphost = ""
if opt_address:
logger.logit("Manually setting localip with -a")
localip = opt_address
elif opt_after_syslog:
logger.logit("Scanning /var/log/messages for last occurance of " + opt_after_syslog)
fp = open("/var/log/messages", "r")
ipdata = fp.read()
fp.close()
p1 = string.rfind(ipdata, opt_after_syslog)
if p1 != -1:
ipmatch = Addressgrep.search(ipdata[p1:])
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
fp.close()
elif opt_firewall_log:
logger.logit("Scanning " + opt_firewall_log)
lines = []
fp = open(opt_firewall_log, "r")
while 1:
l = fp.readline()
if not l:
break
lines.append(l)
fp.close()
lcnt = len(lines)
localip = ""
for x in xrange(lcnt-1, 0, -1):
l = lines[x]
if l[:3] == "NAT":
ipmatch = Addressgrep.findall(l)
if len(l) == 2:
localip = check_public_ip(l[1])
else:
localip = check_public_ip(l[0])
if localip:
break
logger.logit("IP matched " + localip)
elif opt_snmp_agent_prefix:
logger.logit("Trying snmp localip detection")
# Create an instance of snmptable class
instance = snmptable (opt_snmp_agent, opt_snmp_community)
# Run snmptable against passed Object ID's
retval = []
try:
retval = instance.run([opt_snmp_objectid])
except:
logline = "Snmp session failed."
logger.logexit(logline)
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
agentlen = len(opt_snmp_agent_prefix)
objectlen = len(opt_snmp_objectid) + 1
for (objid, value) in retval:
logger.logit(objid + ' ---> ' + str(value))
objval = objid[objectlen:]
if objval[:agentlen] != opt_snmp_agent_prefix:
localip = objval
logger.logit("IP matched: " + localip)
# match the last one so all options are printed in the log
#break
elif opt_snmp_agent:
mysnmptable = snmptable(opt_snmp_agent, opt_snmp_community)
try:
value = mysnmptable.getrow(opt_snmp_objectid)
except:
logger.logexit("Snmp session failed.")
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
logger.logit(opt_snmp_objectid + ' ---> ' + str(value))
localip = value
logger.logit("IP from snmpget is: " + localip)
elif opt_Cayman_password:
#
# Cayman DSL 3220H router ip detection
#
# This code was written for and tested on Device Firmware
# GatorSurf version 5.6.2 (build R0)
# with PPP / NAT
#
# determine the router host address
#
if routerIP:
logger.logit("Cayman_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.254")
iphost = "192.168.1.254"
# connect to the router's admin console interface
try:
logger.logit("Trying Cayman DSL 3220H")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("ogin:")
logger.logit("Login prompt found")
tn.write(Cayman_user + "\r\n")
logger.logit("Cayman_user sent")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Cayman_password + "\r\n")
logger.logit("opt_Cayman_password sent")
tn.read_until(">")
tn.write("show ip interface\r\n")
logger.logit("show ip interface command sent")
ipdata = tn.read_until(">", 2000)
tn.write("exit\r\n")
logger.logit("exit command sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "cayman.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("cayman.out file created")
# look for the WAN device in ipdata
p1 = string.rfind(ipdata, "PPP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1+1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Netgear338_password:
#
# Netgear RT338 ISDN router
#
# determine the router host address
#
if routerIP:
logger.logit("Netgear338_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
# connect to the router's admin webpage
try:
logger.logit("Trying Netgear RT338")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Netgear338_password + "\r\n")
logger.logit("opt_Netgear338_password sent")
tn.read_until("Number:")
tn.write("24\r\n")
logger.logit("menu number 24 sent")
tn.read_until("Number:")
tn.write("8\r\n")
logger.logit("menu number 8 sent")
ip1 = tn.read_until("router>", 2000)
tn.write("ip ifconfig\r\n")
logger.logit("ip ifconfig sent")
ipdata = tn.read_until("router>", 2000)
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "netgear338.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("netgear338.out file created")
# look for the last wanif0 device in the log
p1 = string.rfind(ipdata, "wanif0")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
p1 = string.rfind(ipdata, "enif1")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Gnet_password:
#
# Gnet ADSL Router
#
# This code was written for and tested on
# Gnet model BB0040 ADSL Router version 2.A3.2.03 (Build 011207.A)
# running ADSL/PPPOE/NAT in the device
#
# determine the router host address
#
if routerIP:
logger.logit("Gnet_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.254")
iphost = "192.168.1.254"
# connect to the router's admin console interface
try:
logger.logit("Trying Gnet model BB0040 ADSL router")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Gnet_password + "\r\n")
logger.logit("opt_Gnet_password sent")
tn.read_until(">")
tn.write("ip subnet\r\n")
logger.logit("ip subnet command sent")
ipdata = tn.read_until(">", 2000)
tn.write("@close\r\n")
logger.logit("@close command sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "gnet.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("gnet.out file created")
# look for the WAN device in ipdata
p1 = string.rfind(ipdata, "subnet ppp_device")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1+1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Compex_password:
#
# Compex NetPassage 15 router ip detection
#
# This code was written for and tested on Device Firmware
# version "2.67 Build 1005, Mar 5 2001"
#
# determine the router host address
#
if routerIP:
logger.logit("Compex_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.168.1")
iphost = "192.168.168.1"
# connect to the router's admin console interface
try:
logger.logit("Trying Compex NetPassage 15")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Compex_password + "\r\n")
logger.logit("opt_Compex_password sent")
tn.read_until("ommand>")
tn.write("show ip\r\n")
logger.logit("show ip command sent")
ipdata = tn.read_until("ommand>", 2000)
tn.write("exit\r\n")
logger.logit("exit command sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "compex.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("compex.out file created")
# look for the WAN device in ipdata
p1 = string.rfind(ipdata, "WAN")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Zyxel_ME_password:
#
# ZyXEL Prestige 642ME router ip detection
#
#
# determine the router host address
#
if routerIP:
logger.logit("Zyxel_ME_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying ZyXEL Prestige 642ME")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Zyxel_ME_password + "\r\n")
logger.logit("opt_Zyxel_ME_password sent")
tn.read_until(">")
tn.write("ip ifconfig\r\n")
logger.logit("ip ifconfig sent")
ipdata = tn.read_until(">", 2000)
logger.logit("ipdata read")
tn.write("exit\r\n")
logger.logit("exit sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "zyxelme.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("zyxelme.out file created")
# look for the last wanif0 device in the log
p1 = string.rfind(ipdata, "wanif0")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
p1 = string.rfind(ipdata, "enif1")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Zyxel_password:
#
# ZyXEL 642R router ip detection
#
#
# determine the router host address
#
if routerIP:
logger.logit("Zyxel_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
ipdata = ""
ip1 = ""
ip2 = ""
# connect to the router's admin webpage
try:
logger.logit("Trying ZyXEL Prestige 642R and 310")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Zyxel_password + "\r\n")
logger.logit("opt_Zyxel_password sent")
#tn.read_until("Menu Selection Number:")
tn.write("24\r\n")
logger.logit("menu number 24 sent")
#tn.read_until("Menu Selection Number:")
tn.write("8\r\n")
logger.logit("menu number 8 sent")
tn.write("ip ifconfig\r\n")
logger.logit("ip ifconfig sent")
ip1 = tn.read_until(">", 2000)
ip2 = tn.read_until(">", 2000)
logger.logit("ip1 and ip2 read")
tn.write("exit\r\n")
logger.logit("exit sent")
tn.write("99\r\n")
logger.logit("menu number 99 sent")
except:
logger.logit("may not have gotten second prompt")
tn.write("exit\r\n")
logger.logit("exit sent")
tn.write("99\r\n")
logger.logit("menu number 99 sent")
ipdata = ip1 + ip2
# create an output file of the response
filename = "zyxel.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("zyxel.out file created")
# look for the last wanif0 device in the log
p1 = string.rfind(ipdata, "wanif0")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
p1 = string.rfind(ipdata, "enif1")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Netgear3114_password:
if routerIP:
logger.logit("Netgear3114_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.100.1")
iphost = "192.168.100.1"
logger.logit("Trying Netgear3114")
logger.logit("Authenticating with home page")
filename = "netgear3114p1.out"
if opt_directory:
filename = opt_directory + filename
logindata = BasicAuth(logger, iphost, Netgear3114_page1, Netgear3114_user, opt_Netgear3114_password, filename)
logger.logit("Getting status page")
filename = "netgear3114p2.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, Netgear3114_page2, Netgear3114_user, opt_Netgear3114_password, filename)
p1 = string.find(ipdata, "IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
logger.logit("Logging out")
filename = "netgear3114p3.out"
if opt_directory:
filename = opt_directory + filename
logoutdata = BasicAuth(logger, iphost, Netgear3114_page3, Netgear3114_user, opt_Netgear3114_password, filename)
elif opt_Hawking_password:
#
# Hawking router ip detection
#
ipdir = Hawking_page
#
# determine the router host address
#
if routerIP:
logger.logit("Hawking_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.10.10")
iphost = "192.168.10.10"
logger.logit("Trying HawkingTech")
filename = "hawking.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, ipdir, Hawking_user, opt_Hawking_password, filename)
# look for local ip in the log
p1 = string.find(ipdata, "WAN")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Ugate_router:
#
# UgatePlus router ip detection
#
ipdir = Ugate_page
#
# determine the router host address
#
if routerIP:
logger.logit("Ugate_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
# connect to the router's admin webpage
try:
logger.logit("Trying UgatePlus")
ipurl = "http://" + iphost + Ugate_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "ugate.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("ugate.out file created")
# look for the last Default gateway
p1 = string.rfind(ipdata, "I.P. Address")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Veicon_password:
#
# Eicon Diva 2430 SE ADSL Modem with password
#
ipdir = Veicon_page
#
# determine the router host address
#
if routerIP:
logger.logit("Veicon_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Eicon with password")
params = urllib.urlencode({'password': opt_Veicon_password})
ipurl = "http://" + iphost + Veicon_page
urlfp = urllib.urlopen(ipurl, params)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "veicon.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("veicon.out file created")
# look for the last Default gateway
p1 = string.rfind(ipdata, "WAN IP address")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Barricade_password:
#
# Newer SMC Barricade with passwords on port 88
#
ipdir = Barricade_page
#
# determine the router host address
#
if routerIP:
logger.logit("Barricade_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.2.1")
iphost = "192.168.2.1"
logger.logit("Trying new Barricade with password")
if opt_7004VWBR:
ipport = "80"
loginaction = "/cgi-bin/login.exe"
logoutaction = "/cgi-bin/logout.exe"
statuspage = "/status_main.stm"
ipprefix = "var wan_ip="
else:
ipport = "88"
loginaction = "/login.htm"
logoutaction = "/logout.htm"
statuspage = "/status.HTM"
ipprefix = "WAN IP"
try:
ipurl = "http://" + iphost + ":" + ipport + "/login.htm"
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
logger.logit("filename = login.out")
filename = "login.out"
if opt_directory:
filename = opt_directory + filename
logger.logit("file open")
fp = open(filename, "w")
logger.logit("write data")
fp.write(ipdata)
logger.logit("file close")
fp.close()
logger.logit("login.out file created")
except:
logline = "Failed to get login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Try to post to form")
params = urllib.urlencode({'pws': opt_Barricade_password})
ipurl = "http://" + iphost + ":" + ipport + loginaction
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl, params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
if string.find(ipdata, "not found") != -1:
logger.logit("Trying to with page=login&")
params = urllib.urlencode({'pws': opt_Barricade_password})
ipurl = "http://" + iphost + ":" + ipport + loginaction
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl, "page=login&" + params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
filename = "post.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("post.out file created")
except:
logline = "Failed to post password to login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Now try to access " + statuspage + " on port " + ipport)
ipurl = "http://" + iphost + ":" + ipport + statuspage
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "barricade.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("barricade.out file created")
except:
logline = "Failed accessing status page "
logger.logexit(logline)
sys.exit(-1)
# look for the last Default gateway
p1 = string.rfind(ipdata, ipprefix)
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
# logout so other users can login to the Barricade
try:
logger.logit("Try to post to logout form")
ipurl = "http://" + iphost + ":" + ipport + logoutaction
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
filename = "logout.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("logout.out file created")
except:
logline = "Failed to post to logout form"
logger.logexit(logline)
sys.exit(-1)
elif opt_Siemens2620_password:
#
# Siemens SpeedStream 2620 with passwords on port 88
# (This is just like the SMC Barricade entry just above, save that
# some of the URLs are slightly different. Is the Siemens unit just
# a rebadged SMC or vice-versa?)
#
ipdir = Siemens2620_page
#
# determine the router host address
#
if routerIP:
logger.logit("Siemens2620_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.254.254")
iphost = "192.168.254.254"
logger.logit("Trying Siemens SpeedStream 2620 with password")
try:
ipurl = "http://" + iphost + ":88/"
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
logger.logit("filename = login.out")
filename = "login.out"
if opt_directory:
filename = opt_directory + filename
logger.logit("file open")
fp = open(filename, "w")
logger.logit("write data")
fp.write(ipdata)
logger.logit("file close")
fp.close()
logger.logit("login.out file created")
except:
logline = "Failed to get login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Try to post to form")
params = urllib.urlencode({'pws': opt_Siemens2620_password})
ipurl = "http://" + iphost + ":88/LOGIN.HTM"
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl, params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
if string.find(ipdata, "not found") != -1:
logger.logit("Trying to with page=login&")
params = urllib.urlencode({'pws': opt_Siemens2620_password})
ipurl = "http://" + iphost + ":88/LOGIN.HTM"
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl, "page=login&" + params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
filename = "post.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("post.out file created")
except:
logline = "Failed to post password to login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Now try to access status.HTM on port 88")
ipurl = "http://" + iphost + ":88/MAIN.HTM"
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "siemens.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("siemens.out file created")
except:
logline = "Failed accessing status page "
logger.logexit(logline)
sys.exit(-1)
# look for the last Default gateway
p1 = string.rfind(ipdata, "WAN IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Eicon_router:
#
# Eicon Diva 2430 SE ADSL Modem ip detection
#
ipdir = Eicon_page
#
# determine the router host address
#
if routerIP:
logger.logit("Eicon_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Eicon")
ipurl = "http://" + iphost + Eicon_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "eicon.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("eicon.out file created")
# look for the last Default gateway
p1 = string.rfind(ipdata, "WAN IP address")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_II_password:
#
# Instant Internet router ip detection
#
#
# determine the router host address
#
if routerIP:
logger.logit("II_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Instant Internet ")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_II_password + "\r\n")
logger.logit("opt_II_password sent")
tn.write("ppp " + opt_II_interface + "\r\n")
logger.logit("ppp " + opt_II_interface + " sent")
ip1 = tn.read_until("state:", 2000)
logger.logit("ip read")
tn.write("exit\r\n")
logger.logit("exit sent")
ipdata = ip1
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "II.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("II.out file created")
# look for the last ipadr device in the log
p1 = string.rfind(ipdata, "ipadr local:")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Nexland_router:
#
# Nexland router ip detection
#
ipdir = Nexland_page
#
# determine the router host address
#
if routerIP:
logger.logit("Nexland_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Nexland")
ipurl = "http://" + iphost + Nexland_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "nexland.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("nexland.out file created")
# look for the last Default gateway
p1 = string.rfind(ipdata, "Default gateway")
if p1 == -1:
p1 = string.find(ipdata, "IP Address<")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Pro800Turbo_router:
#
# Nexland Pro800Turbo router ip detection
#
ipdir = Pro800Turbo_page
#
# determine the router host address
#
if routerIP:
logger.logit("Pro800Turbo_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Pro800Turbo")
h1 = httplib.HTTP(iphost)
h1.putrequest('GET',Pro800Turbo_page)
if Pro800Turbo_password:
authstring = base64.encodestring("admin:" + Pro800Turbo_password)
h1.putheader('Authorization', 'Basic ' + authstring)
# print ipdir
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
# print errcode
# print errmsg
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "pro800turbo.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("pro800turbo.out file created")
p1 = 0
local_ips = []
connected = []
while 1:
p2 = string.find(ipdata[p1:], ">Connection Status<")
if p2 == -1:
break
p1 = p1 + p2 + 1
cmatch = re.search(">([^>]+)</td>",ipdata[p1:])
if cmatch == None:
break
connected.append(cmatch.group(1))
p2 = string.find(ipdata[p1:], "IP Address<")
if p2 == -1:
break
p1 = p1 + p2
if p1 == -1:
break
ipmatch = Addressgrep.search(ipdata, p1)
p1 = p1 + len("IP Address<")
if ipmatch == None:
local_ips.append(None)
else:
local_ips.append(ipmatch.group())
if Pro800Turbo_port == 'force':
if local_ips[Pro800Turbo_port_number] != '0.0.0.0':
# if forced, don't even check connection. We might as well use
# the IP we get, even it it isn't currently working.
localip = local_ips[Pro800Turbo_port_number]
else:
if local_ips[Pro800Turbo_port_number] != '0.0.0.0' \
and connected[Pro800Turbo_port_number] == 'Connected':
localip = local_ips[Pro800Turbo_port_number]
else:
for i in range(len(local_ips)):
if local_ips[i] != '0.0.0.0':
localip = local_ips[i]
if connected[i] == 'Connected':
break
# Else keep looking for one that is "Connected". If we don't find
# one, might as well use the an ip address, even if not
# "Connected". I've had situations where that was still usable.
if localip:
logger.logit("IP matched: " + localip)
elif opt_SMC_router:
#
# SMC barricade router ip detection
#
ipdir = SMC_page
#
# determine the router host address
#
if routerIP:
logger.logit("SMC_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.254")
iphost = "192.168.0.254"
# connect to the router's admin webpage
try:
if opt_WBR != "":
logger.logit("Trying SMC WBR with password")
if opt_7004VWBR:
# 2005-02-15 djlauk@users.sourceforge.net:
# quick hack for SMC7004VWBRV.2
logger.logit("Trying DJ's hack for model SMC7004VWBRV.2")
SMC_page = "/login.htm?pws=" + opt_WBR
else:
SMC_page = "/login.cgi?pws=" + opt_WBR
ipurl = "http://" + iphost + SMC_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
SMC_page = "/status_main.htm"
ipurl = "http://" + iphost + SMC_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
else:
logger.logit("Trying SMC")
ipurl = "http://" + iphost + SMC_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "smc.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("smc.out file created")
# grab first thing that looks like an IP address
ipmatch = Addressgrep.search(ipdata)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Netvanta_password != "":
#
# Adtran Netvanta router ip detection
#
#
# determine the router host address
#
iphost = ""
if routerIP:
logger.logit("Netvanta_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost == "":
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
else:
logline = "Trying router at " + iphost
logger.logit(logline)
# connect to the router's telnet interface
# first try to talk to a Netvanta Series router
try:
logger.logit("Trying Netvanta router (AOS!)")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Netvanta_password + "\r\n")
logger.logit("Netvanta password sent")
tn.write("enable\r\n")
tn.read_until("assword:")
logger.logit("enable Password prompt found")
tn.write(opt_Netvanta_password + "\r\n")
logger.logit("Netvanta password sent")
tn.write("show interface ethernet 0/1\r\n")
logger.logit("show interface command sent")
ipdata = tn.read_until(", netmask", 1000)
ipdata = string.replace(ipdata, ", netmask", "")
logger.logit("ipdata read")
tn.write("logo\r\n")
logger.logit("logoff sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "netvanta.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("netvanta.out file created")
# look for the last (rfind) negotiated IP in the log
p1 = string.rfind(ipdata, "Internet address is ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Cisco_password != "":
#
# Cisco router ip detection
#
#
# determine the router host address
#
iphost = ""
if routerIP:
logger.logit("Cisco_host set explicitly.")
iphost = Cisco_host
else:
iphost = DefaultRoute(logger, Tempfile)
iphost = DefaultRoute(logger, Tempfile)
if iphost == "":
logger.logit("No router ip detected. Assuming 192.168.10.5")
iphost = "192.168.10.5"
else:
logline = "Trying router at " + iphost
logger.logit(logline)
# connect to the router's admin webpage
# first try to talk to a Cisco 800-series
try:
logger.logit("Trying Cisco DSL 800 series (IOS!)")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_Cisco_password + "\r\n")
logger.logit("Cisco password sent")
tn.write("show ip interface | incl /32\r\n")
logger.logit("show ip interface command sent")
ipdata = tn.read_until("/32", 1000)
logger.logit("unwanted stuff read")
ipdata = tn.read_until("/32", 1000)
ipdata = string.replace(ipdata, "/32", "")
logger.logit("ipdata read")
tn.write("logo\r\n")
logger.logit("logoff sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "cisco.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("cisco.out file created")
# look for the last (rfind) negotiated IP in the log
p1 = string.rfind(ipdata, "Internet address is ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_ISDNCisco_password:
#
# ISDNCisco router ip detection
#
#
# determine the router host address
#
if routerIP:
logger.logit("ISDNCisco_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.10.5")
iphost = "192.168.10.5"
# connect to the router's admin webpage
# first try to talk to a Cisco 667i
try:
logger.logit("Trying Cisco ISDN 700 series")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword:")
logger.logit("Password prompt found")
tn.write(opt_ISDNCisco_password + "\r\n")
logger.logit("opt_ISDNCisco_password sent")
tn.write("show ip co\r\n")
logger.logit("show ip co sent")
ipdata = tn.read_until("Profile PAT", 1000)
logger.logit("ipdata read")
tn.write("bye\r\n")
logger.logit("bye sent")
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "cisco.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("cisco.out file created")
# look for the last negotiated IP in the log
# you may have to change this to a user defined profile
p1 = string.rfind(ipdata, "RemoteNet")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Netopia_password:
#
# Netopia router ip detection
#
ipdir = Netopia_page
#
# determine the router host address
#
if routerIP:
logger.logit("Netopia_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
logger.logit("Trying Netopia")
filename = "netopia.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, Netopia_page, Netopia_user, opt_Netopia_password, filename)
# look for local ip in the log
p1 = string.find(ipdata, "local")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Draytek_password:
#
# Draytek router ip detection
#
ipdir = Draytek_page
#
# determine the router host address
#
if routerIP:
logger.logit("Draytek_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
logger.logit("Trying Draytek")
filename = "draytek.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, Draytek_page, Draytek_user, opt_Draytek_password, filename)
# grab first thing that looks like an IP address
ipmatch = Addressgrep.search(ipdata)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_MotorolaVT1000v_router:
#
# Motorola VT1000v router ip detection
#
ipdir = MotorolaVT1000v_page
#
# determine the router host address
#
if routerIP:
logger.logit("MotorolaVT1000v_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Motorola VT1000v")
ipurl = "http://" + iphost + MotorolaVT1000v_page
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "motorolaVT1000v.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("%s file created" % filename)
# look for the last Default gateway
ipre = re.compile ('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
routerip = ipre.findall(ipdata)
if len(routerip) > 0:
localip = routerip[0]
logger.logit("IP matched: " + localip)
elif opt_Macsense_password:
#
# MacSense router ip detection
#
ipdir = Macsense_page
#
# determine the router host address
#
if routerIP:
logger.logit("Macsense_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying MacSense XRouter Pro router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying MacSense")
h1 = httplib.HTTP(iphost)
authstring = base64.encodestring(Macsense_user + ":" + opt_Macsense_password)
authstring = string.replace(authstring, "\012", "")
ipdir = Macsense_page + ' \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the linksys response
filename = "macsense.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("macsense.out file created")
p1 = string.find(ipdata, "Public IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_Netgear_password:
#
# Netgear router ip detection
#
ipdir = Netgear_page
#
# determine the router host address
#
if routerIP:
logger.logit("Netgear_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
logger.logit("Trying Netgear")
filename = "netgear.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, Netgear_page, Netgear_user, opt_Netgear_password, filename)
# look for the last WAN Port in the log
p1 = string.rfind(ipdata, "WAN")
if p1 == -1:
ipdata = BasicAuth(logger, iphost, Netgear314_page1, Netgear_user, opt_Netgear_password, filename)
p1 = string.rfind(ipdata, "WAN")
if p1 == -1:
ipdata = BasicAuth(logger, iphost, Netgear314_page2, Netgear_user, opt_Netgear_password, filename)
p1 = string.rfind(ipdata, "WAN")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
logger.logit("Logging out on Netgear")
# hit the logout page
filename = "logout.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, Netgear_logout, Netgear_user, opt_Netgear_password, filename)
elif opt_DInop_router == 1:
#
# DI704 router ip detection
#
ipdir = DI704_page
#
# determine the router host address
#
if routerIP:
logger.logit("DI704_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
logger.logit("Trying DI704 no password")
try:
logger.logit("Retrieving menu.htm...")
ipurl = "http://" + iphost + "/menu.htm?RC=@"
urlfp = urllib.urlopen(ipurl)
menudata = urlfp.read()
urlfp.close()
filename = "di704_menu.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(menudata)
fp.close()
logger.logit("di704menu.out file created")
except:
logline = "Failed while fetching menu.htm page "
logger.logexit(logline)
sys.exit(-1)
logline = "Parsing menu... "
logger.logit("Parsing menu")
menud = {}
p1 = 0;
p2 = 0;
while 1:
p1 = string.find(menudata, "VALUE=", p2)
p2 = string.find(menudata, "NAME=", p1)
if p1 == -1 or p2 == -1:
break
p3 = string.find(menudata, '"', p1)
p4 = string.find(menudata, '"', p3 + 1)
p5 = string.find(menudata, '>', p2)
if p3 == -1 or p4 == -1 or p5 == -1:
break
rhs = menudata[p3+1:p4]
lhs = menudata[p2+6:p5]
logline = lhs + " = " + rhs
logger.logit(logline)
menud[lhs] = rhs
logger.logit("Adding password")
menud["URL"] = opt_DI704_password
try:
logger.logit("Now try to access status.htm now")
ipurl = "http://" + iphost + "/status.htm"
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "di704.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("di704.out file created")
except:
logline = "Failed accessing status page "
logger.logexit(logline)
sys.exit(-1)
# look for the first WAN Port in the log
p1 = string.find(ipdata, "WAN")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_DI704_password:
#
# DI704 router ip detection
#
ipdir = DI704_page
#
# determine the router host address
#
if routerIP:
logger.logit("DI704_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
logger.logit("Trying DI704")
try:
logger.logit("Retrieving menu.htm...")
ipurl = "http://" + iphost + "/menu.htm?RC=@"
urlfp = urllib.urlopen(ipurl)
menudata = urlfp.read()
urlfp.close()
filename = "di704_menu.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(menudata)
fp.close()
logger.logit("di704menu.out file created")
except:
logline = "Failed while fetching menu.htm page "
logger.logexit(logline)
sys.exit(-1)
logline = "Parsing menu... "
logger.logit("Parsing menu")
menud = {}
p1 = 0;
p2 = 0;
while 1:
p1 = string.find(menudata, "VALUE=", p2)
p2 = string.find(menudata, "NAME=", p1)
if p1 == -1 or p2 == -1:
break
p3 = string.find(menudata, '"', p1)
p4 = string.find(menudata, '"', p3 + 1)
p5 = string.find(menudata, '>', p2)
if p3 == -1 or p4 == -1 or p5 == -1:
break
rhs = menudata[p3+1:p4]
lhs = menudata[p2+6:p5]
logline = lhs + " = " + rhs
logger.logit(logline)
menud[lhs] = rhs
logger.logit("Adding password")
menud["URL"] = opt_DI704_password
try:
logger.logit("Try to post to form")
params = urllib.urlencode( menud )
ipurl = "http://" + iphost + "/cgi-bin/logi"
logger.logit("urlopen " + ipurl)
urlfp = urllib.urlopen(ipurl, params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
filename = "post.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("post.out file created")
except:
logline = "Failed to post password to login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Now try to access status.htm now")
ipurl = "http://" + iphost + "/status.htm"
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "di704.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("di704.out file created")
except:
logline = "Failed accessing status page "
logger.logexit(logline)
sys.exit(-1)
# look for the first WAN Port in the log
p1 = string.find(ipdata, "IP Address")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_DI713P_password != "":
#
# DI713P router ip detection
#
# Tested with DI713P firmware 2.57 build 3a1
# Based on DI704 code. The router appears to expect certain
# values for the hidden variables {PSWD, KEY, htm} on the login page.
# So we first get the values from the login page (menu.htm) then
# feed them back via the POST
ipdir = DI713P_page
#
# determine the router host address
#
if routerIP:
logger.logit("DI713P_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost == "":
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
else:
logline = "Trying router at " + iphost
logger.logit(logline)
logger.logit("Trying DI713P")
# fetch the menu page and retrieve the hidden values
try:
logger.logit("Retrieving menu.htm...")
ipurl = "http://" + iphost + "/menu.htm"
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "di713P_menu.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("di713P_menu.out file created")
except:
logline = "Failed while fetching menu.htm page "
logger.logexit(logline)
sys.exit(-1)
# match for values of KEY, PSWD, htm
di713P_logged_in = False # default
try:
search_result = re.search('(")([^"]*)(") NAME=KEY', ipdata)
if search_result == None: # If KEY not present then we are
# already logged in. Don't do further string searching
di713P_logged_in = True
else:
di713P_key = search_result.group(2)
# logger.logit("KEY = " + di713P_key)
search_result = re.search('(")([^"]*)(") NAME=PSWD', ipdata)
di713P_pswd = search_result.group(2)
# logger.logit("PSWD = " + di713P_pswd)
search_result = re.search('(")([^"]*)(") NAME=htm', ipdata)
di713P_htm = search_result.group(2)
# logger.logit("htm = " + di713P_htm)
except:
logline = "Failed while matching for KEY, PSWD, htm page "
logger.logexit(logline)
sys.exit(-1)
if di713P_logged_in:
logger.logit("Already logged in to the DLink gateway")
else:
try:
logger.logit("POSTing to login form")
# params = urllib.urlencode({'RC': '@D', 'ACCT': "root", 'PSWD': di713P_pswd, 'URL': opt_DI713P_password, 'KEY': di713P_key, 'htm': di713P_htm })
# The device seems to want the POST parameters in a specific
# order. Unfortunately the order in the urlencode statement is
# NOT carried through to the data packet (despite documentation to
# the contrary. Sigh.) So we build up the data string a piece
# at a time...
params = urllib.urlencode({'RC':'@D'})
params = params + "&" + urllib.urlencode({'ACCT':"root"})
params = params + "&" + urllib.urlencode({'PSWD':di713P_pswd})
params = params + "&" + urllib.urlencode({'URL':opt_DI713P_password})
params = params + "&" + urllib.urlencode({'KEY':di713P_key})
params = params + "&" + urllib.urlencode({'htm': di713P_htm})
ipurl = "http://" + iphost + "/cgi-bin/logi"
# logger.logit("urlopen " + ipurl + " ["+params+"]")
urlfp = urllib.urlopen(ipurl, params)
logger.logit("urlfp.read")
ipdata = urlfp.read()
logger.logit("urlfp.close")
urlfp.close()
filename = "di713P_post.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("di713P_post.out file created")
except:
logline = "Failed to post password to login form"
logger.logexit(logline)
sys.exit(-1)
try:
logger.logit("Fetching status.htm...")
ipurl = "http://" + iphost + "/status.htm"
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
filename = "di713P_status.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("di713P_status.out file created")
except:
logline = "Failed to get status page "
logger.logexit(logline)
sys.exit(-1)
# look for the first WAN Port in the log
p1 = string.find(ipdata, "IP Address")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("Success! Found IP address " + localip)
elif opt_DI804_password:
#
# DI804/DI-614+ router ip detection
#
ipdir = DI804_page
#
# determine the router host address
#
if routerIP:
logger.logit("DI804_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
logger.logit("Trying DI804/DI-614+")
filename = "di804.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, DI804_page, DI804_user, opt_DI804_password, filename)
# look for the first WAN Port in the log
p1 = string.find(ipdata, "Current IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
logger.logit("Trying DI614+")
filename = "di614.out"
if opt_directory:
filename = opt_directory + filename
ipdata = BasicAuth(logger, iphost, DI614_page, DI804_user, opt_DI804_password, filename)
p1 = string.find(ipdata, "PPPoE")
if p1 == -1:
p1 = string.find(ipdata, "WAN")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_DSL504_password:
#
# DSL504 router ip detection
#
ipdir = DSL504_page
#
# determine the router host address
#
if routerIP:
logger.logit("DSL504_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.0.1")
iphost = "192.168.0.1"
# connect to the router's admin webpage
try:
logger.logit("Trying DLink DSL504")
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword: ")
#logger.logit("Password prompt found")
tn.write(opt_DSL504_password + "\r")
logger.logit("opt_DSL504_password sent")
tn.read_until(">")
tn.write("home\r\n")
logger.logit("home command sent sent")
tn.read_until(">")
tn.write("nat interfaces\r\n")
logger.logit("nat interfaces command sent")
tn.read_until("ppp_device Enabled ", 2000)
ip2 = tn.read_until(" ",2000)
logger.logit("ip read")
tn.write("@close\r\n")
logger.logit("@close command sent")
ipdata = ip2[:-1]
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "dsl504.out"
if opt_directory:
filename = opt_directory + filename
open(filename, "w").write(ipdata)
logger.logit("dsl504.out file created")
localip = ipdata
logger.logit("IP matched: " + localip)
elif opt_Linksys_router != 0:
#
# Linksys router ip detection
#
ipdir = Linksys_page
#
# determine the linksys router host address
#
iphost = ""
if routerIP:
logger.logit("Linksys_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost == "":
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
else:
logline = "Trying linksys router at " + iphost
logger.logit(logline)
# connect to the router's admin webpage
try:
logger.logit("Trying Linksys")
h1 = httplib.HTTP(iphost)
#
# Hack from Bobby Griggs for authorization.
#
# For some reason the router won't authenticate when
# using standard headers for authorization. Like this:
#
#h1.putrequest('GET', ipdir)
#authstring = base64.encodestring(Linksys_user + ":" + opt_Linksys_password)
#h1.putheader("Authorization", "Basic " + authstring)
#
# It may be looking for lines that end with just \n not \r\n.
#
# Note: Modified by Greg Bentz.
# Linksys firmware 1.37, doesn't like the trailing \n on the authstring.
# Also requires "\r\n".
# My theory concerning the standard headers is that the Linksys header
# parsing requires all the header info to appear in one packet.
# Use of an extra putheader() call puts the authorization information into
# a second packet which is not read by the Linksys device.
#
authstring = base64.encodestring(Linksys_user + ":" + opt_Linksys_password)
authstring = string.replace(authstring, "\012", "")
ipdir = Linksys_page + ' HTTP/1.1 \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
#
# replacing findall to support older python 1.5.1 sites
#
#ipmatch = Addressgrep.findall(ipdata)
#if ipmatch != None:
# if len(ipmatch) > 2:
# localip = ipmatch[2]
p1 = string.find(ipdata, "WAN")
if p1 != -1:
p2 = string.find(ipdata, "IP", p1)
if p2 != -1:
ipmatch = Addressgrep.search(ipdata, p2)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
if localip == "":
try:
logger.logit("Trying Linksys")
h1 = httplib.HTTP(iphost)
authstring = base64.encodestring(Linksys_user + ":" + opt_Linksys_password)
authstring = string.replace(authstring, "\012", "")
ipdir = "/Status_Router.htm" + ' HTTP/1.1 \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
p1 = string.find(ipdata, "Internet IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
# Support for Linksys RT31P2 Vonage VoIP Gateway Router
# Default IP is 192.168.15.1. Could support that later.
if localip == "":
try:
logger.logit("Trying Linksys RT31P2")
h1 = httplib.HTTP(iphost)
authstring = base64.encodestring(Linksys_user + ":" + opt_Linksys_password)
authstring = string.replace(authstring, "\012", "")
ipdir = "/RouterStatus.htm" + ' HTTP/1.1 \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
p1 = string.find(ipdata, "Internet IP")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
# create an output file of the linksys response
filename = "linksys.out"
if opt_directory != "":
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("linksys.out file created")
elif opt_Watchguard_password:
#
# Watchguard firewall/router ip detection
#
ipdir = Watchguard_page
#
# determine the watchguard soho router host address
#
if routerIP:
logger.logit("Watchguard_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying Watchguard SOHO firewall at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.111.1")
iphost = "192.168.111.1"
# connect to the router's admin webpage
try:
logger.logit("Trying Watchguard")
h1 = httplib.HTTP(iphost)
authstring = base64.encodestring(Watchguard_user + ":" + opt_Watchguard_password)
authstring = string.replace(authstring, "\012", "")
ipdir = Watchguard_page + ' \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.putheader("AUTHORIZATION", "Basic " + authstring)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
ipmatch = Addressgrep.search(ipdata)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
logger.logit("Trying Watchguard new firmware")
h1 = httplib.HTTP(iphost)
authstring = base64.encodestring(Watchguard_user + ":" + opt_Watchguard_password)
authstring = string.replace(authstring, "\012", "")
ipdir = Watchguard_page2 + ' \r\n' \
+ 'Authorization: Basic ' \
+ authstring + '\r\n'
h1.putrequest('GET', ipdir)
h1.putheader("AUTHORIZATION", "Basic " + authstring)
h1.endheaders()
errcode, errmsg, headers = h1.getreply()
fp = h1.getfile()
ipdata = fp.read()
fp.close()
# create an output file of the watchguard response
filename = "watchguard.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("watchguard.out file created")
ipmatch = Addressgrep.search(ipdata)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif opt_DI701_password:
#
# determine the router host address
#
if routerIP:
logger.logit("DI701_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 192.168.1.1")
iphost = "192.168.1.1"
# connect to the router's admin webpage
try:
logger.logit("Trying DLink DI701")
tn = telnetlib.Telnet(iphost,333)
logger.logit("Creating telnetlib obj done")
tn.read_until("assword : ")
logger.logit("Password prompt found")
tn.write(opt_DI701_password + "\r")
logger.logit("opt_DI701_password sent")
tn.read_until("command>")
tn.write("show\r")
logger.logit("show command sent")
tn.read_until("address of global port : [", 2000)
ip2 = tn.read_until("]", 2000)
logger.logit("ip read")
#tn.write("exit\r\n")
#logger.logit("exit sent")
ipdata = ip2[:-1]
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "di701.out"
if opt_directory:
filename = opt_directory + filename
open(filename, "w").write(ipdata)
logger.logit("di701.out file created")
localip = ipdata
logger.logit("IP matched: " + localip)
elif opt_AlcatelSTP_password:
#
# determine the router host address
#
if routerIP:
logger.logit("AlcatelSTP_host set explicitly.")
iphost = routerIP
else:
iphost = DefaultRoute(logger, Tempfile)
if iphost:
logline = "Trying router at " + iphost
logger.logit(logline)
else:
logger.logit("No router ip detected. Assuming 10.0.0.138")
iphost = "10.0.0.138"
# connect to the router's admin webpage
try:
logger.logit("Trying Alcatel STP")
# disables negotiation to prevent the connection being dropped
telnetlib.IAC="\021"
tn = telnetlib.Telnet(iphost)
logger.logit("Creating telnetlib obj done")
tn.read_until(" : ")
logger.logit("User prompt found")
tn.write(Alcatel_user + "\r")
tn.write(opt_AlcatelSTP_password + "\r")
logger.logit("opt_AlcatelSTP_password sent")
tn.read_until("=>")
tn.write("ip aplist\r")
logger.logit("ip aplist sent")
ret=tn.read_until("SERIAL",5)
if string.find(ret,"SERIAL")==-1:
raise "not connected"
tn.read_until("addr:")
ip2 = tn.read_until(" ")
logger.logit("ip read")
ipdata = ip2[:-1]
if len(opt_forward) != 0:
for opt_forwardportprotocol in opt_forward:
tn.read_until("=>")
logline="nat create protocol=%s inside_addr=%s inside_port=%s outside_addr=%s outside_port=%s "
logline=logline % ( opt_forwardportprotocol[1], tn.sock.getsockname()[0],
opt_forwardportprotocol[0], ipdata, opt_forwardportprotocol[0] )
tn.write(logline+"\r")
logger.logit(logline)
tn.read_until(logline)
tn.read_until("=>")
# no exit needed
tn.close()
except:
logline = "No address found on router at " + iphost
logger.logexit(logline)
sys.exit(-1)
# create an output file of the response
filename = "alcatel_stp.out"
if opt_directory:
filename = opt_directory + filename
open(filename, "w").write(ipdata)
logger.logit("alcatel_stp.out file created")
localip = ipdata
logger.logit("IP matched: " + localip)
elif opt_router:
logger.logit("web based ip detection for localip")
ipurl = ""
# check for deprecated url
if string.find(opt_router, "cgi-bin/check_ip.cgi") != -1:
logger.logexit("You should be using -r checkip.dyndns.org ")
logger.logexit("Continuing with new URL.")
opt_router = "checkip.dyndns.org:8245"
# strip off the http part, if any
if opt_router[:7] == "HTTP://" or opt_router[:7] == "http://":
ipurl = opt_router[7:]
else:
ipurl = opt_router
# stick it back on for urllib usage
ipurl = "http://" + ipurl
# grab the data
try:
logger.logit("Trying URL " + ipurl)
urlfp = urllib.urlopen(ipurl)
ipdata = urlfp.read()
urlfp.close()
except:
logline = "Unable to open url " + ipurl
logger.logexit(logline)
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
# create an output file of the ip detection response
filename = "webip.out"
if opt_directory:
filename = opt_directory + filename
fp = open(filename, "w")
fp.write(ipdata)
fp.close()
logger.logit("webip.out file created")
# grab first thing that looks like an IP address
ipmatch = Addressgrep.search(ipdata)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("webip detected = " + localip)
else:
logger.logit("Interface ip detection on sys.platform = " + sys.platform)
if sys.platform == "win32":
logger.logit("win32 interface ip detection for localip")
getip = Win32ip
os.system (getip + " > " + Tempfile)
fp = open(Tempfile, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the interface
p1 = string.find(ipdata, opt_interface)
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "sunos") != -1:
logger.logit("Sunos interface ip detection for localip (untested)")
fp = os.popen(Sunip + " " + opt_interface, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the interface
p1 = string.find(ipdata, opt_interface)
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "linux") != -1:
logger.logit("linux interface ip detection for localip")
fp = os.popen(Linuxip + " " + opt_interface, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the interface
p1 = string.find(ipdata, opt_interface)
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "Darwin") != -1:
logger.logit("Darwin interface ip detection for localip")
fp = os.popen(Macip + " " + opt_interface , "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the LAST inet (to avoid dead routes)
p1 = string.rfind(ipdata, "inet ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "os2") != -1:
logger.logit("OS2 interface ip detection for localip")
getip = Os2ip + " " + opt_interface
os.system (getip + " > " + Tempfile)
fp = open(Tempfile, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the LAST inet (to avoid dead routes)
p1 = string.rfind(ipdata, "inet ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "beos") != -1:
logger.logit("BeOS interface ip detection for localip")
getip = Beosip
os.system (getip + " > " + Tempfile)
fp = open(Tempfile, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after interface text
p1 = string.rfind(ipdata, opt_interface + ":")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "bsd") != -1:
logger.logit("*BSD* interface ip detection for localip")
fp = os.popen(BSDip + " " + opt_interface + " | grep -v 192.168 ", "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the LAST inet (to avoid dead routes)
p1 = string.rfind(ipdata, "inet ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
elif string.find(sys.platform, "sco_") != -1:
logger.logit("SCO interface ip detection for localip")
getip = Scoip + " " + opt_interface
os.system (getip + " > " + Tempfile)
fp = open(Tempfile, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the LAST inet (to avoid dead routes)
p1 = string.rfind(ipdata, "inet ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
else:
logger.logit("Default interface ip detection for localip (untested)")
getip = Otherip + " " + opt_interface
os.system (getip + " > " + Tempfile)
fp = open(Tempfile, "r")
ipdata = fp.read()
fp.close()
# grab the first dotted quad after the LAST inet (to avoid dead routes)
p1 = string.rfind(ipdata, "inet ")
if p1 != -1:
ipmatch = Addressgrep.search(ipdata, p1)
if ipmatch != None:
localip = ipmatch.group()
logger.logit("IP matched: " + localip)
# check if we have a localip from all the above elifs
if not localip:
logline = "No address found on interface " + opt_interface + " use -i"
logger.logexit(logline)
sys.exit(-1)
# end of all determining localip cases
logline = check_ip(localip)
if logline:
logger.logexit(logline)
sys.exit(-1)
#
# create the dat file from dns lookup if specified
#
if opt_makedat:
logger.logit("DNS lookups to create data file.")
if datfile.exists():
logger.logexit("There is already an ipcheck.dat file existing.")
logger.logexit("Remove this file first before running --makedat")
sys.exit(0)
else:
logger.logit("Good, no ipcheck.dat file found.")
ip1 = ""
ip2 = ""
h = ""
try:
for h in hostnames:
if not ip1:
logger.logexit("ip1 looking up " + h)
(a, b, c) = socket.gethostbyname_ex(h)
line = `a` + `b` + `c`
logger.logexit("result: " + line)
ip1 = c[0]
logger.logit("ip1 = " + ip1)
ip2 = ip1
else:
logger.logexit("ip2 looking up " + h)
(a, b, c) = socket.gethostbyname_ex(h)
line = `a` + `b` + `c`
logger.logexit("result: " + line)
ip2 = c[0]
logger.logit("ip2 = " + ip2)
# check if not same
if ip1 != ip2:
logger.logexit("WARNING: hostnames have different ips.")
logger.logexit("I'm going to set the force option so all hosts")
logger.logexit("will be synchronized to the same IP address.")
opt_force = 1
except:
logger.logexit("Problems looking up hostname " + h)
logger.logexit("Make sure the hostname is correct, is setup at Dyndns,")
logger.logexit("and that local DNS lookups are working fine.")
logger.logexit("Exception: " + `sys.exc_info()[0]`)
sys.exit(-1)
logger.logit("Writing the new dat file.")
datfile.write(ip1, hostnames)
#
# read the data from file of last update, if any
#
if datfile.exists():
(fileip, filehosts) = datfile.read()
fileage = datfile.getAge()
else:
# do not create the file automatically cause people could get
# into loops and use up a lot of bandwidth doing dns lookup
logger.logexit("No ipcheck.dat file found.")
logger.logexit("Use same command+options ONCE with --makedat to create from DNS lookup.")
sys.exit(0)
#
# check filehosts list versus hostnames list
#
mismatch = 0
for h in filehosts:
if h not in hostnames:
mismatch = 1
for h in hostnames:
if h not in filehosts:
mismatch = 1
if not mismatch:
logger.logit("Good, filehosts and hostnames are the same.")
else:
# do not create the file automatically cause people could get
# into loops and use up a lot of bandwidth doing dns lookup
logger.logexit("The hostnames listed do not match the ipcheck.dat file.")
logger.logexit("Remove the dat file and use same command ONCE with --makedat.")
logger.logexit("Note that if you are maintaining both a custom domain and")
logger.logexit("a dyndns domain, you should be using the -d option and")
logger.logexit("keeing the data files in separate directories.")
sys.exit(0)
#
# read the data from error file, if any
#
if not errfile.exists():
logger.logit("Good, no ipcheck.err file.")
elif not opt_force:
logger.logit("Handling errors in ipcheck.err file.")
fatal = errfile.analyze(opt_username,opt_password,hostnames)
if fatal:
sys.exit(-1)
#
# read the data from wait file, if any
#
waitcode = ""
waitdate = ""
try:
fp = open (Waitfile, "r")
waitcode = fp.readline()
if waitcode[-1] == "\n":
waitcode = waitcode[:-1]
waitdate = fp.readline()
if waitdate[-1] == "\n":
waitdate = waitdate[:-1]
fp.close()
except:
logger.logit("Good, no ipcheck.wait file.")
if waitcode and not opt_force:
logger.logit("Found wait entry.")
logger.logit(waitcode)
logger.logit(waitdate)
#
# first line is the code
# second line is time.time() when the code was received
# now determine whether we should continue or abort
# remove the file if the wait is no longer needed
#
try:
waitnum = float(waitdate)
except:
waitnum = 0.0
if waitnum == 0.0:
logger.logit("Invalid wait date in ipcheck.wait file.")
logger.logit("ipcheck.wait file removed and continuing.")
os.unlink (Waitfile)
elif waitcode[0] == 'u':
# wait until GMT
logger.logit("Decoding wait until entry in ipcheck.wait file.")
# First we check the age of the file.
currtime = time.time()
mtime = os.stat(Waitfile)[stat.ST_MTIME]
if (currtime - mtime) / (60*60) > 24:
# the file is older than 24 hours and should be ignored
logger.logit("Stale ipcheck.wait file removed and continuing.")
os.unlink (Waitfile)
elif (currtime - waitnum) / (60*60) > 24:
# the code is older than 24 hours and should be ignored
logger.logit("Stale code in file removed and continuing.")
os.unlink (Waitfile)
else:
try:
waitsec = int(waitcode[2:])
except:
waitsec = 0
currtime = time.time()
if currtime > waitnum + waitsec:
logger.logit("until wait entry expired.")
logger.logit("ipcheck.wait file removed and continuing.")
os.unlink (Waitfile)
else:
logger.logit("until wait entry in effect: quietly aborting.")
sys.exit(-1)
else:
# wait h, m or s
logger.logit("Decoding hms entry in ipcheck.wait file.")
try:
waitsec = int(waitcode[1:3])
if waitcode[3] == 'h' or waitcode[3] == 'H':
waitsec = waitsec * 60 * 60
elif waitcode[3] == 'm' or waitcode[3] == 'M':
waitsec = waitsec * 60
except:
waitsec = 0
currtime = time.time()
if currtime > waitnum + waitsec:
logger.logit("hms wait entry expired.")
logger.logit("ipcheck.wait file removed and continuing.")
os.unlink (Waitfile)
else:
logger.logit("hms wait entry in effect: quietly aborting.")
sys.exit(-1)
#
# determine whether and which hosts need updating
#
updatehosts = []
# if opt_force is set then update all hosts
# or offline mode selected
if opt_force or opt_offline:
logger.logit("Updates forced by -f option.")
for host in hostnames:
updatehosts.append(host)
# else if file age is older than update all hosts
# Touchage == 0 means don't update
elif fileage > Touchage and Touchage > 0:
logger.logit("Updates required by stale ipcheck.dat file.")
for host in hostnames:
updatehosts.append(host)
# else check the address used in last update
elif localip != fileip:
logger.logit("Updates required by ipcheck.dat address mismatch.")
for host in hostnames:
updatehosts.append(host)
# This case is probably deprecated but will leave it in
# case I missed something. When reading the dat file,
# I'm going to now only proceed if hostnames == filehosts.
# Otherwise, a message will be printed out and an option
# to create a dat file from dns lookups will be recommended.
else:
logger.logit("Checking hosts in file vs command line.")
updateflag = 0
for host in hostnames:
if host not in filehosts:
updateflag = 1
# If anyone of the hosts on the command line needs updating,
# put them all in the updatehosts list so they will get the
# same last updated timestamp at dyndns. This way they all
# won't need to be touched again for Touchage days, instead
# of having multiple touches for different last updated dates.
if updateflag:
for host in hostnames:
updatehosts.append(host)
if updatehosts == []:
# Quietly log this message then exit too.
logger.logit("The database matches local address. No hosts update.")
sys.exit(0)
#
# build the query strings
#
updateprefix = Updatepage
if opt_static:
updateprefix = updateprefix + "?system=statdns&hostname="
elif opt_custom:
updateprefix = updateprefix + "?system=custom&hostname="
else:
updateprefix = updateprefix + "?system=dyndns&hostname="
hostlist = ""
for host in updatehosts:
hostlist = hostlist + host + ","
logger.logit(host + " needs updating")
if len(hostlist) > 0:
hostlist = hostlist[:-1]
if opt_offline:
if opt_static:
logger.logexit("offline and static mode not allowed together.")
sys.exit(-1)
updatesuffix = ""
if opt_offline:
#updatesuffix = updatesuffix + "&myip=1.0.0.0"
updatesuffix = updatesuffix + "&offline=YES"
else:
# only do these other things if not setting offline mode
if opt_guess:
logger.logit("Letting dyndns guess the IP.")
localip = ""
else:
updatesuffix = updatesuffix + "&myip=" + localip
# custom domains do not have wildcard or mx records
if not opt_custom:
if opt_wildcard:
updatesuffix = updatesuffix + "&wildcard=ON"
else:
updatesuffix = updatesuffix + "&wildcard=OFF"
if opt_backupmx:
updatesuffix = updatesuffix + "&backmx=YES"
else:
updatesuffix = updatesuffix + "&backmx=NO"
if opt_mxhost:
updatesuffix = updatesuffix + "&mx=" + opt_mxhost
logger.logit("Prefix = " + updateprefix)
logger.logit("Hosts = " + hostlist)
logger.logit("Suffix = " + updatesuffix)
if opt_testrun:
logger.logit("test run exits here")
sys.exit()
#
# check which version of python we are using
#
python2 = string.find(sys.version, "2.3")
if python2 == 0:
#
# apache2 ssl returns EOF too soon for python2's ssl library
# and causes an exception. apache1 with mod_ssl worked fine.
# Python 1.5.x works fine also.
#
logger.logit("Using python 2.3, https disabled")
opt_no_https = 1
python2 = string.find(sys.version, "2.2")
if python2 == 0:
#
# apache2 ssl returns EOF too soon for python2's ssl library
# and causes an exception. apache1 with mod_ssl worked fine.
# Python 1.5.x works fine also.
#
logger.logit("Using python 2.2, https disabled")
opt_no_https = 1
python2 = string.find(sys.version, "2.1")
if python2 == 0:
#
# apache2 ssl returns EOF too soon for python2's ssl library
# and causes an exception. apache1 with mod_ssl worked fine.
# Python 1.5.x works fine also.
#
logger.logit("Using python 2.1, https disabled")
opt_no_https = 1
#
# update those hosts
#
if not opt_no_https:
logline = "trying to open HTTPS connection"
logger.logit(logline)
try:
if not opt_proxy:
h2 = httplib.HTTPS(Updatehost)
logline = "HTTPS connection successful"
logger.logit(logline)
else:
h2 = httplib.HTTPS(Updatehost, 8245)
logline = "HTTPS connection successful"
logger.logit(logline)
except:
logline = "trying to open normal HTTP connection"
logger.logit(logline)
if not opt_proxy:
h2 = httplib.HTTP(Updatehost)
logline = "normal HTTP connection successful"
logger.logit(logline)
else:
h2 = httplib.HTTP(Updatehost, 8245)
logline = "normal HTTP connection successful"
logger.logit(logline)
else:
logline = "trying to open normal HTTP connection"
logger.logit(logline)
if not opt_proxy:
h2 = httplib.HTTP(Updatehost)
logline = "normal HTTP connection successful"
logger.logit(logline)
else:
h2 = httplib.HTTP(Updatehost, 8245)
logline = "normal HTTP connection successful"
logger.logit(logline)
h2.putrequest("GET", updateprefix + hostlist + updatesuffix)
h2.putheader("HOST", Updatehost)
h2.putheader("USER-AGENT", Useragent)
authstring = base64.encodestring(opt_username + ":" + opt_password)
authstring = string.replace(authstring, "\012", "")
h2.putheader("AUTHORIZATION", "Basic " + authstring)
h2.endheaders()
errcode, errmsg, headers = h2.getreply()
# log the result
logline = "http code = " + `errcode`
logger.logit(logline)
logline = "http msg = " + errmsg
logger.logit(logline)
# try to get the html text
try:
fp = h2.getfile()
httpdata = fp.read()
fp.close()
except:
httpdata = "No output from http request."
# explicitly close
fp.close()
logline = "fd closed"
logger.logit(logline)
# create the output file
fp = open (Htmlfile, "w")
fp.write(httpdata)
fp.close()
logger.logit("ipcheck.html file created for headers")
logger.logit(`headers.getplist()`)
#
# check the result for fatal errors
#
# badauth may appear anywhere when errcode is 401
if string.find(httpdata, "badauth") != -1 and errcode == 401:
logline = "Invalid username and password specified on command line."
logger.logexit(logline)
#
# save the error to an ipcheck.err file
#
errfile.write("badauth " + opt_username + " " + opt_password, fatal=1)
sys.exit(-1)
elif errcode == 404:
logger.logexit("404 Not Found returned by dyndns server.")
logger.logexit("Please try again in a few minutes.")
sys.exit(-1)
# badsys must begin the resulting text and errcode is 200
elif httpdata[:6] == "badsys" and errcode == 200:
logline = "Bad system parameter specified (not dyndns or statdns)."
logger.logexit(logline)
#
# save the error to an ipcheck.err file
#
if opt_static:
errfile.write("badsys statdns", fatal=1)
elif opt_custom:
errfile.write("badsys custom", fatal=1)
else:
errfile.write("badsys dyndns", fatal=1)
sys.exit(-1)
# badagent must begin the resulting text and errcode is 200
elif httpdata[:8] == "badagent" and errcode == 200:
logger.logexit("Badagent contact author at kal@users.sourceforge.net.")
errfile.write("badagent", fatal=1)
sys.exit(-1)
# 911 may appear anywhere when errcode is 500
elif string.find(httpdata, "911") != -1 and errcode == 500:
logline = "Dyndns 911 result. Dyndns emergency shutdown."
logger.logexit(logline)
errfile.write("shutdown", fatal=1)
sys.exit(-1)
# 999 may appear anywhere when errcode is 500
elif string.find(httpdata, "999") != -1 and errcode == 500:
logline = "Dyndns 999 result. Dyndns emergency shutdown."
logger.logexit(logline)
errfile.write("shutdown", fatal=1)
sys.exit(-1)
#
# don't really know what codes go with numhost, dnserr and wxxxx
# probably errcode 200 but no need to assume this instead
# assume they will be sent at the beginning of a line
# we check those codes below
#
elif errcode == 200:
# build the results list
results = []
fp = open (Htmlfile, "r")
for host in hostnames:
resultline = fp.readline()
if resultline[-1:] == "\n":
resultline = resultline[:-1]
results.append(resultline)
fp.close()
# check if we have one result per updatehosts
if len(results) == len(updatehosts):
idx = 0
success = 0
for host in updatehosts:
#
# use logexit to generate output (email if ran from a cronjob)
#
if results[idx][:4] == "good":
logline = host + " " + results[idx] + " -update successful"
if opt_quiet:
logger.logit(logline)
else:
logger.logexit(logline)
# update the localip dyndns found if guess was used
if opt_guess and not localip:
p1 = string.find(results[idx], " ")
localip = string.rstrip(results[idx][p1+1:])
logger.logit("Dyndns guessed IP: " + localip)
# set the success update flag
success = 1
elif results[idx][:5] == "nochg":
logline = host + " " + results[idx] + " -abusive if continually repeated"
logger.logexit(logline)
# update the localip dyndns found if guess was used
if opt_guess and not localip:
p1 = string.find(results[idx], " ")
localip = string.rstrip(results[idx][p1+1:])
logger.logit("Dyndns guessed IP: " + `localip`)
elif results[idx][:7] == "!active":
logline = host + " " + results[idx] + " -zone not active yet"
logger.logexit(logline)
logger.logexit("Try again in an hour")
# clear localip to remove ipcheck.dat file
localip = ""
elif results[idx][:5] == "abuse":
logline = host + " " + results[idx] + " -hostname blocked for abuse"
logger.logexit(logline)
logger.logexit("Use the form at http://support.dyndns.org/dyndns/abuse.shtml")
logger.logexit("Erase the ipcheck.err file when dyndns notifies you (by email).")
# update the localip dyndns found if guess was used
if opt_guess and not localip:
p1 = string.find(results[idx], " ")
localip = string.rstrip(results[idx][p1+1:])
logger.logit("Dyndns guessed IP: " + `localip`)
#
# save the error to an ipcheck.err file
#
errfile.write("abuse " + host)
elif results[idx][:7] == "notfqdn":
logline = host + " " + results[idx] + " -FQDN hostnames needed"
logger.logexit(logline)
errfile.write("notfqdn " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:6] == "nohost":
logline = host + " " + results[idx] + " -hostname not found"
logger.logexit(logline)
errfile.write("nohost " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:7] == "!active":
logline = host + " " + results[idx] + " -hostname not activated yet"
logger.logexit(logline)
errfile.write("!active " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:6] == "!yours":
logline = host + " " + results[idx] + " -hostname not yours"
logger.logexit(logline)
errfile.write("!yours " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:7] == "numhost":
logline = host + " " + results[idx] + " -send ipcheck.html to support@dyndns.org"
logger.logexit(logline)
errfile.write("numhost " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:6] == "dnserr":
logline = host + " " + results[idx] + " -send ipcheck.html to support@dyndns.org"
logger.logexit(logline)
errfile.write("dnserr " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:2] == "wu":
logline = host + " " + results[idx] + " -wait until entry created"
logger.logexit(logline)
# get the wait code HH MM
try:
codeHH = int(results[idx][2:4])
codeMM = int(results[idx][4:6])
except:
codeHH = 0
codeMM = 0
codeHHMM = codeHH * 100 + codeMM
# try to get the current time from the HTTP headers at dyndns
datetuple = headers.getdate("Date")
if datetuple == None:
logger.logit("Date header not found. Using local clock.")
datetuple = gmtime(time.time())
currHH = datetuple[3]
currMM = datetuple[4]
currHHMM = currHH * 100 + currMM
# compute the HHMM we need to wait
if (codeHHMM <= currHHMM):
# The codeHHMM is smaller than GMT of when we received the code.
# Example: NIC returned 02:30 (codeHHMM) when we tried to update
# at 21:30 (currHHMM). So we should be waiting 21:30 to 24:00
# plus 00:00 to 02:30 seconds.
waitHH = (23 - currHH) + codeHH
waitMM = (60 - currMM) + codeMM
logger.logit("Wraparound calculation.")
else:
waitHH = codeHH - currHH
waitMM = codeMM - currMM
logger.logit("Normal calculation.")
# convert to seconds
waitval = (waitHH * 60 + waitMM) * 60
logger.logit("currHHMM = " + `currHHMM`)
logger.logit("codeHHMM = " + `codeHHMM`)
logger.logit("waitval = " + `waitval`)
# convert back to seconds
#
# save the until calculation to an ipcheck.wait file
#
fp = open (Waitfile, "a")
fp.write("u " + `waitval` + "\n")
currtime = time.time()
fp.write(`time.time()` + "\n")
fp.close()
logger.logit("ipcheck.wait file created.")
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][0] == "w":
logline = host + " " + results[idx] + " -wait entry created"
logger.logexit(logline)
#
# save the waitcode to an ipcheck.wait file
#
fp = open (Waitfile, "a")
fp.write(results[idx] + "\n")
currtime = time.time()
fp.write(`time.time()` + "\n")
fp.close()
logger.logit("ipcheck.wait file created.")
# set the localip so next update will be made
localip = "0.0.0.0"
elif results[idx][:8] == "!donator":
logline = host + " " + results[idx] + " -trying donator only feature"
logger.logexit(logline)
errfile.write("!donator " + host)
# set the localip so next update will be made
localip = "0.0.0.0"
# looks like the homeip.net domain gives blank lines sometimes???
elif results[idx]:
logline = host + " " + results[idx] + " -unknown result line"
logger.logexit(logline)
else:
logger.logexit("BLANK RESULT LINE! Please forward the following output")
logger.logexit("(and logfile if you have one) to kal@users.sourceforge.net:")
logger.logexit("updatehosts:")
logger.logexit(`updatehosts`)
logger.logexit("results:")
logger.logexit(`results`)
continue
idx = idx + 1
if success and opt_execute:
os.system (opt_execute)
else:
logger.logexit("Unrecognized result page in ipcheck.html.")
#
# write the update data to file
#
if localip:
if opt_offline:
datfile.setIP("1.0.0.0")
else:
datfile.setIP(localip)
# hostnames == updatehosts in the current version
# but that may change in future versions of the client
datfile.write(hostnames = hostnames)
logger.logit("ipcheck.dat file updated.")
elif errcode == 302:
logger.logexit("302 Temporarily Moved result. Something is wrong.")
logger.logexit("Please send the ipcheck.html file and this message to")
logger.logexit("kal@users.sourceforge.net")
logger.logexit("=== 302 debug headers ===")
logger.logexit(`headers.getplist()`)
sys.exit(-1)
else:
logger.logexit("Unrecognized errcode returned by dyndns server.")
logger.logexit("Please send me the ipcheck.html file.")
logger.logexit("kal@users.sourceforge.net")
sys.exit(-1)
if __name__=="__main__":
_main(sys.argv)
|