Skip to content

Instantly share code, notes, and snippets.

@comalex
Last active August 9, 2017 14:34
Show Gist options
  • Save comalex/5d49364814fa23f9c3bb06e9bcfca8c6 to your computer and use it in GitHub Desktop.
Save comalex/5d49364814fa23f9c3bb06e9bcfca8c6 to your computer and use it in GitHub Desktop.
Ping google use all available ips on the current machine
"""
Eсть сервер с несколькими айпи на линукс. у сервера 4 айпи. надо написать скрипт на питон 3,
который устанавливает в 4х потоках (каждый поток использует отдельный айпи), соединение с гугл.ком
"""
"""
pip3 install -r requirements.txt
"""
import logging
import socket
import threading
import queue
import ipaddress
import netifaces
logger = logging.getLogger(__name__)
class ProxyPool(queue.Queue):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for p in self.get_system_ips():
self.put(p)
def get_system_ips(self):
ips = []
interfaces = netifaces.interfaces()
for i in interfaces:
if i == 'lo':
continue
iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
addr = j['addr']
if not ipaddress.ip_address(addr).is_loopback and not ipaddress.ip_address(addr).is_private:
ips.append(addr)
return set(ips)
def connect(proxy_ip, port=0):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
logger.info("proxy_ip: %s", proxy_ip)
try:
s.bind((proxy_ip, port))
host = 'www.google.com'
remote_ip = socket.gethostbyname(host)
s.settimeout(10)
s.connect((remote_ip, 80))
logger.info('Socket Connected to %s through %s', host, "%s:%s" % (proxy_ip, port))
except (socket.gaierror, socket.timeout) as e:
logger.error("%s, used: [%s:%s]" % (str(e), proxy_ip, port))
finally:
s.close()
def main(proxy_pool, q):
proxy_ip = proxy_pool.get()
connect(proxy_ip)
current_tread_name = threading.current_thread().name
logger.info("%s got `%s`", current_tread_name, q.get())
q.put("Random data from `%s`" % current_tread_name)
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)s:%(funcName)s():%(threadName)s:%(lineno)s - %(message)s')
q = queue.Queue()
q.put("Initial data")
proxy_pool = ProxyPool()
# Number of treads depends on count of available ips
tread_pool = [threading.Thread(target=main, args=(proxy_pool, q)) for _ in range(proxy_pool.qsize())]
for t in tread_pool:
t.start()
for thread in tread_pool:
thread.join()
netifaces==0.10.4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment