Skip to content
This repository has been archived by the owner on Jul 11, 2018. It is now read-only.

w3m 这。。。 #2

Open
pypykim opened this issue Jun 6, 2014 · 11 comments
Open

w3m 这。。。 #2

pypykim opened this issue Jun 6, 2014 · 11 comments

Comments

@pypykim
Copy link

pypykim commented Jun 6, 2014

telnet ip 443/80
tcping ip 443/80
楼主试试这个?等我看你代码改下试试哈

@pypykim
Copy link
Author

pypykim commented Jun 9, 2014

准备依赖requests或者httplib做域名识别

@pypykim
Copy link
Author

pypykim commented Jun 10, 2014

try:
    import requests
except Exception as e:
    print 'Please "pip install requests"'


try:
    requests.get('https://1.179.253.22')
except Exception, e:
    nameList = str(e).split("', '")
    nameList[0] = nameList[0].split("'")[-1]
    nameList[-1] = nameList[-1].split("'")[0]
    print nameList

@gshmu
Copy link
Owner

gshmu commented Jun 10, 2014

方法不错,获得的hosts比之前的更全面。
抽时间我试试,这个之后,往Windows迁移的难度就剩下ping时候微软弱智的中文。。。
不过主要是改正则匹配。

@pypykim
Copy link
Author

pypykim commented Jun 10, 2014

我这边也有python ping 不依赖系统的

import os
import select
import signal
import socket
import struct
import sys
import time
if sys.platform.startswith('win32'):
    default_timer = time.clock
else:
    default_timer = time.time
ICMP_ECHOREPLY = 0
ICMP_ECHO = 8
ICMP_MAX_RECV = 2048
MAX_SLEEP = 1000

def calculate_checksum(source_string):
    """
    A port of the functionality of in_cksum() from ping.c
    Ideally this would act on the string as a series of 16-bit ints (host
    packed), but this works.
    Network data is big-endian, hosts are typically little-endian
    """
    countTo = int(len(source_string) / 2) * 2
    sum = 0
    count = 0
    loByte = 0
    hiByte = 0
    while count < countTo:
        if sys.byteorder == 'little':
            loByte = source_string[count]
            hiByte = source_string[count + 1]
        else:
            loByte = source_string[count + 1]
            hiByte = source_string[count]
        sum = sum + (ord(hiByte) * 256 + ord(loByte))
        count += 2

    if countTo < len(source_string):
        loByte = source_string[len(source_string) - 1]
        sum += ord(loByte)
    sum &= 4294967295L
    sum = (sum >> 16) + (sum & 65535)
    sum += sum >> 16
    answer = ~sum & 65535
    answer = socket.htons(answer)
    return answer


def is_valid_ip4_address(addr):
    parts = addr.split('.')
    if not len(parts) == 4:
        return False
    for part in parts:
        try:
            number = int(part)
        except ValueError:
            return False

        if number > 255:
            return False

    return True


def to_ip(addr):
    if is_valid_ip4_address(addr):
        return addr
    return socket.gethostbyname(addr)


class Response(object):

    def __init__(self):
        self.max_rtt = None
        self.min_rtt = None
        self.avg_rtt = None
        self.packet_lost = None
        self.ret_code = None
        self.output = []
        self.packet_size = None
        self.timeout = None
        self.destination = None
        self.destination_ip = None
        return


class Ping(object):

    def __init__(self, destination, timeout = 1000, packet_size = 55, own_id = None, quiet_output = True, udp = False):
        self.quiet_output = quiet_output
        if quiet_output:
            self.response = Response()
            self.response.destination = destination
            self.response.timeout = timeout
            self.response.packet_size = packet_size
        self.destination = destination
        self.timeout = timeout
        self.packet_size = packet_size
        self.udp = udp
        self.pingPass = True
        if own_id is None:
            self.own_id = os.getpid() & 65535
        else:
            self.own_id = own_id
        try:
            self.dest_ip = to_ip(self.destination)
            if quiet_output:
                self.response.destination_ip = self.dest_ip
        except socket.gaierror as e:
            self.print_unknown_host(e)
        else:
            self.print_start()

        self.seq_number = 0
        self.send_count = 0
        self.receive_count = 0
        self.min_time = 999999999
        self.max_time = 0.0
        self.total_time = 0.0
        return

    def print_start(self):
        msg = 'PYTHON-PING %s (%s): %d data bytes' % (self.destination, self.dest_ip, self.packet_size)
        if self.quiet_output:
            self.response.output.append(msg)
        else:
            print msg

    def print_unknown_host(self, e):
        msg = '\nPYTHON-PING: Unknown host: %s (%s)\n' % (self.destination, e.args[1])
        if self.quiet_output:
            self.response.output.append(msg)
            self.response.ret_code = 1
        else:
            print msg
        sys.exit(-1)

    def print_success(self, delay, ip, packet_size, ip_header, icmp_header):
        if ip == self.destination:
            from_info = ip
        else:
            from_info = '%s (%s)' % (self.destination, ip)
        msg = '%d bytes from %s: icmp_seq=%d ttl=%d time=%.1f ms' % (packet_size,
         from_info,
         icmp_header['seq_number'],
         ip_header['ttl'],
         delay)
        if self.quiet_output:
            self.response.output.append(msg)
            self.response.ret_code = 0
        else:
            print msg

    def print_failed(self):
        msg = 'Request timed out.'
        self.pingPass = False
        if self.quiet_output:
            self.response.output.append(msg)
            self.response.ret_code = 1
        else:
            print msg

    def print_exit(self):
        msg = '----%s PYTHON PING Statistics----' % self.destination
        if self.quiet_output:
            self.response.output.append(msg)
        else:
            print msg
        lost_count = self.send_count - self.receive_count
        lost_rate = float(lost_count) / self.send_count * 100.0
        msg = '%d packets transmitted, %d packets received, %0.1f%% packet loss' % (self.send_count, self.receive_count, lost_rate)
        if self.quiet_output:
            self.response.output.append(msg)
            self.response.packet_lost = lost_count
        else:
            print msg
        if self.receive_count > 0:
            msg = 'round-trip (ms)  min/avg/max = %0.3f/%0.3f/%0.3f' % (self.min_time, self.total_time / self.receive_count, self.max_time)
            if self.quiet_output:
                self.response.min_rtt = '%.3f' % self.min_time
                self.response.avg_rtt = '%.3f' % (self.total_time / self.receive_count)
                self.response.max_rtt = '%.3f' % self.max_time
                self.response.output.append(msg)
            else:
                print msg
        if self.quiet_output:
            self.response.output.append('\n')
        else:
            pass

    def signal_handler(self, signum, frame):
        """
        Handle print_exit via signals
        """
        self.print_exit()
        msg = '\n(Terminated with signal %d)\n' % signum
        if self.quiet_output:
            self.response.output.append(msg)
            self.response.ret_code = 0
        else:
            print msg
        sys.exit(0)

    def setup_signal_handler(self):
        signal.signal(signal.SIGINT, self.signal_handler)
        if hasattr(signal, 'SIGBREAK'):
            signal.signal(signal.SIGBREAK, self.signal_handler)

    def header2dict(self, names, struct_format, data):
        """ unpack the raw received IP and ICMP header informations to a dict """
        unpacked_data = struct.unpack(struct_format, data)
        return dict(zip(names, unpacked_data))

    def run(self, count = None, deadline = None):
        """
        send and receive pings in a loop. Stop if count or until deadline.
        """
        if not self.quiet_output:
            self.setup_signal_handler()
        while True:
            delay = self.do()
            self.seq_number += 1
            if count and self.seq_number >= count:
                break
            if deadline and self.total_time >= deadline:
                break
            if delay == None:
                delay = 0
            if MAX_SLEEP > delay:
                time.sleep((MAX_SLEEP - delay) / 1000.0)

        self.print_exit()
        if self.quiet_output:
            return self.response
        else:
            return

    def do(self):
        """
        Send one ICMP ECHO_REQUEST and receive the response until self.timeout
        """
        try:
            if self.udp:
                current_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.getprotobyname('icmp'))
            else:
                current_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
        except socket.error as (errno, msg):
            if errno == 1:
                etype, evalue, etb = sys.exc_info()
                evalue = etype('%s - Note that ICMP messages can only be send from processes running as root.' % evalue)
                raise etype, evalue, etb
            raise

        send_time = self.send_one_ping(current_socket)
        if send_time == None:
            return
        else:
            self.send_count += 1
            receive_time, packet_size, ip, ip_header, icmp_header = self.receive_one_ping(current_socket)
            current_socket.close()
            if receive_time:
                self.receive_count += 1
                delay = (receive_time - send_time) * 1000.0
                self.total_time += delay
                if self.min_time > delay:
                    self.min_time = delay
                if self.max_time < delay:
                    self.max_time = delay
                self.print_success(delay, ip, packet_size, ip_header, icmp_header)
                return delay
            self.print_failed()
            return

    def send_one_ping(self, current_socket):
        """
        Send one ICMP ECHO_REQUEST
        """
        checksum = 0
        header = struct.pack('!BBHHH', ICMP_ECHO, 0, checksum, self.own_id, self.seq_number)
        padBytes = []
        startVal = 66
        for i in range(startVal, startVal + self.packet_size):
            padBytes += [i & 255]

        data = bytes(padBytes)
        checksum = calculate_checksum(header + data)
        header = struct.pack('!BBHHH', ICMP_ECHO, 0, checksum, self.own_id, self.seq_number)
        packet = header + data
        send_time = default_timer()
        try:
            current_socket.sendto(packet, (self.destination, 1))
        except socket.error as e:
            self.response.output.append('General failure (%s)' % e.args[1])
            current_socket.close()
            return

        return send_time

    def receive_one_ping(self, current_socket):
        """
        Receive the ping from the socket. timeout = in ms
        """
        timeout = self.timeout / 1000.0
        while True:
            select_start = default_timer()
            inputready, outputready, exceptready = select.select([current_socket], [], [], timeout)
            select_duration = default_timer() - select_start
            if inputready == []:
                return (None, 0, 0, 0, 0)
            receive_time = default_timer()
            packet_data, address = current_socket.recvfrom(ICMP_MAX_RECV)
            icmp_header = self.header2dict(names=['type',
             'code',
             'checksum',
             'packet_id',
             'seq_number'], struct_format='!BBHHH', data=packet_data[20:28])
            if icmp_header['packet_id'] == self.own_id:
                ip_header = self.header2dict(names=['version',
                 'type',
                 'length',
                 'id',
                 'flags',
                 'ttl',
                 'protocol',
                 'checksum',
                 'src_ip',
                 'dest_ip'], struct_format='!BBHHHBBHII', data=packet_data[:20])
                packet_size = len(packet_data) - 28
                ip = socket.inet_ntoa(struct.pack('!I', ip_header['src_ip']))
                return (receive_time,
                 packet_size,
                 ip,
                 ip_header,
                 icmp_header)
            timeout = timeout - select_duration
            if timeout <= 0:
                return (None, 0, 0, 0, 0)

        return None

@gshmu
Copy link
Owner

gshmu commented Jun 10, 2014

看来有的加班了,看看issue#1那个问题,貌似已经不是问题。
好吧,话说你是不是都写好了呢? pull request。。。

@gshmu
Copy link
Owner

gshmu commented Jun 10, 2014

@gshmu
Copy link
Owner

gshmu commented Jun 11, 2014

请看ISSUE3 检查标准,很郁闷。
ping居然要用管理员权限,不是我风格! 搁置。

@pypykim
Copy link
Author

pypykim commented Jun 11, 2014

是的,这个是我在公司做的自动化测试脚本
2014年6月11日 下午8:33于 "gshmu" notifications@github.com写道:

请看ISSUE3 检查标准,很郁闷。
ping居然要用管理员权限,不是我风格! 搁置。


Reply to this email directly or view it on GitHub
#2 (comment).

@bysunexus
Copy link

java写了个小工具
git.oschina.net/kakotor/ggcip

@gshmu
Copy link
Owner

gshmu commented Jun 15, 2014

@kqz901002 看见你新改的了,加油。
看好你哦,我有一点表示奇怪的是,在我电脑上只能使用IDLE运行,其余的挂了。
或许在你那里已经不是问题了,应该是调用系统(ping/w3m)所致。

GCC应该是个笔误,GGC才是,Global Green Coordination(GGC)。

@gshmu
Copy link
Owner

gshmu commented Jun 15, 2014

@kqz901002 那个and or赋值被朋友否定了(说是反人类),你已经移除了哈哈。
不过建议加上lock,mutex。。。

========^== 表示一个数,是m2conf的生日。不过没有几个人能看懂。8^2或8**2。
或许我没有能力为他们做些什么,但我希望发现的人,能铭记他们。

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants