# -*- coding: utf-8 -*-
import requests
import json
import os
from pathlib import Path

from handle_ssh_multi import SShMulti

base_dir = str(Path(__file__).parent)
with open(base_dir + '/yunlifang.json') as f:
    ecs_list  = json.loads(f.read())

def after_call(request, ppp_ip):
    req = request.args[0]
    if isinstance(ppp_ip, str):
        ppp_ip = ppp_ip.strip()
    else:
        print('hostname: %s - result: %s - resp: %s' % (req['hostname'], str(ppp_ip)))
        return

    cmd = 'curl --max-time 5 -o /dev/null -s -w "%{http_code}\n" -x http://ylf2018pxy:2w6XeXA*@' + ppp_ip + ':8016 --proxy-anyauth https://www.jd.com/robots.txt'
    http_code = os.popen(cmd).read()
    print('hostname: %s - result: %s - httpCode: %s' % (req['hostname'], str(ppp_ip), http_code))


if __name__ == "__main__":
    ssh2 = SShMulti()
    cmd = 'cat /proc/loadavg'
    cmd = 'ip -4  addr show ppp0 |  grep -oP \'(?<=inet\s)\d+(\.\d+){3}\''
    cmd = 'ifconfig'

    #cmd = 'cd ~ && cat pppoe/hostname &&  curl  -m 10 -o /dev/null -s -w "%{http_code}\n" https://www.baidu.com/robots.txt'
    ecs_list2 = []
    for ecs in ecs_list:
        if ecs['ip'] == "":
            print(ecs['hostname'])
            continue
        
        ip, port = str(ecs['ip']).split(':')
        if 'ylfk' in ecs['hostname']:
            pwd = 'FJnldx001'
            cmd = 'wget -qO- https://ae-rt.oss-cn-beijing.aliyuncs.com/proxy/install3.sh | bash -s ' + ecs['hostname']
        else:
            pwd = 'FJnldx002'
            cmd = 'wget -qO- https://ae-rt.oss-cn-beijing.aliyuncs.com/proxy/install_ms.sh | bash -s ' + ecs['hostname']

        ##cmd = 'echo dns_nameservers 114.114.114.114 223.5.5.5>>/etc/squid/squid.conf && systemctl restart squid'
        ##cmd = 'ip route get 8.8.8.8 | awk \'{ print $NF; exit }\''
        #cmd = 'ifconfig'
        ecs['user'] = 'root'
        ecs['password'] = pwd
        ecs['cmd'] = cmd
        ecs['ip'] = ip
        ecs['port'] = port
        #ret = ssh2.exec_ssh_cmd(ecs)
        #print("=====================")
        #print(ret)
        #print('%s - %s' % (ecs['hostname'], str(ret)))


        ecs_list2.append(ecs)
        
        """ status_code = ssh2.proxy_ping({
            'username': 'ylf2018pxy',
            'passwd': '2w6XeXA*',
            'ip': ip,
            'port': '8016'
        })
        print('%s - ip %s - code %s' % (ecs['hostname'], ip, status_code)) """

    print(ecs_list2)
    ssh2.mutil_exec(ecs_list2)