Mostrando entradas con la etiqueta Curl. Mostrar todas las entradas
Mostrando entradas con la etiqueta Curl. Mostrar todas las entradas

jueves, 25 de marzo de 2010

PHP, Curl, Tuenti, Login, Parser - Notificador de tuenti.



Bueno seguimos trabajando un poco en el proyecto y vamos sacando cosillas y corrigiendo fallos. Aquí os traigo la otra versión del tuenti.php.
El archivo clase_tuenti.php no será necesario para esta implementación.

Ya no será necesario la librería zenity ya que usaremos la notificación de señales de Ubuntu y GNOME, conocida como libnotify.
Para instalarla:
  • sudo apt-get install libnotify-bin
Repasamos pues todas las dependencias:
  • sudo apt-get install php5-cli
  • sudo apt-get install php5-curl
  • sudo apt-get install gnome-scheduler
  • sudo apt-get install libnotify-bin
Archivos necesarios:
Dentro de la carpeta que quieras # Recomendadio /home/usuario/Tuenti
ico.png # Icono con imagen del tuenti o lo que quieras.
tuenti.php
Como instalarlo:
Una vez tengas los 2 archivos, (recuerda modificar los capos en rojo en tuenti.php por tus datos del tuenti y la carpeta donde lo ejecutes), creamos una tarea programada que se ejecute cada minuto en Aplicaciones > Herramientas del sistema > Tareas programadas
El comando a ejecutar es php /home/tuusuario/Tuenti/tuenti.php
Si todo ha salido bien, cada vez que recibas una visita o tengas algún mensaje nuevo, te aparecerá un mensaje por pantalla informándote de todo.
<?php
/*
*      tuenti.php
*    
*      Copyright 2010 Eduardo Ramirez Martinez-Esparza <zeyt@ZeYt>
*    
*      This program is free software; you can redistribute it and/or modify
*      it under the terms of the GNU General Public License as published by
*      the Free Software Foundation; either version 2 of the License, or
*      (at your option) any later version.
*    
*      This program is distributed in the hope that it will be useful,
*      but WITHOUT ANY WARRANTY; without even the implied warranty of
*      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*      GNU General Public License for more details.
*    
*      You should have received a copy of the GNU General Public License
*      along with this program; if not, write to the Free Software
*      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
*      MA 02110-1301, USA.
*/

//CONFIG
    $usermail = "example@example.com";
    $password = "example";
    $ruta = "/home/tuusuario/Tuenti/";
    $archivo_visitas = "visitas.txt";
    $cookie = "cookie.txt";
    $opcion_mostrar_visitas = TRUE;
//CONFIG

   
    function login($usermail, $password, $tcookie){
        $ch= curl_init();
        curl_setopt ($ch, CURLOPT_URL, "https://www.tuenti.com/?m=login&func=do_login");
        curl_setopt ($ch, CURLOPT_POSTFIELDS, "email=$usermail&input_password=$password&timezone=1");
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_COOKIEFILE, $tcookie);
        curl_setopt ($ch, CURLOPT_COOKIEJAR, $tcookie);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; es-ES; rv:1.9.1.5) Gecko/20091105 Fedora/3.5.5-1.fc11 Firefox/3.5.5");
        $res=curl_exec ($ch);
        curl_close($ch);
        return $res;
    }

    function consult($url,$tcookie){
        $ch= curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_COOKIEFILE, $tcookie);
        curl_setopt ($ch, CURLOPT_COOKIEJAR, $tcookie);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (X11; U; Linux i686; es-ES; rv:1.9.1.5) Gecko/20091105 Fedora/3.5.5-1.fc11 Firefox/3.5.5");
        $res = curl_exec ($ch);
        curl_close($ch);
        return $res;
    }
  
    $resultado = consult("http://www.tuenti.com/?m=home&func=view_home",$cookie);
  
  if ((eregi("<h1>La sesión ha caducado",$resultado)) || (eregi("Por favor, introduce tu e-mail y contrase&ntilde;a de Tuenti para entrar.",$resultado))){
        $login=login($usermail, $password,$cookie);
        $resultado = consult("http://www.tuenti.com/?m=home&func=view_home",$cookie);
    }
  
    $info = explode("<ul>",$resultado);
    $info = explode("</ul>",$info[1]);
    $info = $info[0];
    $info = str_replace("</li>","</li>\n",$info);
  
    if (eregi('<div class="eventImage"',$info)){
            $info ="";
    }
    $info = strip_tags($info);
  
    if ($opcion_mostrar_visitas){
        $trozos = explode('<div class="views"><strong>',$resultado);
        $trozos = explode('</strong>',$trozos[1]);
        $visitas = $trozos[0];
        $visitas = str_replace(".","",$visitas);
       
        if (file_exists($archivo_visitas)){
            $f = fopen($archivo_visitas,"r");
            $visitas_old = fread($f,filesize($archivo_visitas));
            fclose($f);
        }else{
            $f = fopen($archivo_visitas,"w");
            fclose($f);
            $visitas_old = 0;
        }
       
        $mostrar_visitas = FALSE;
       
        if ($visitas>$visitas_old){
            $f = fopen($archivo_visitas,"w");
            fwrite($f,$visitas);
            fclose($f);
            $total = $visitas-$visitas_old;
            $mostrar_visitas = TRUE;
            $imprime_visitas = "Has tenido ". $total ." visitas nuevas. Totales: ".$visitas;
        }
    }
        $titulo = "Notificaciones tuenti:";
    if ($info != ""){
        exec('notify-send -t 2500 "'.$titulo.'" "'. $info .'" -i "'.$ruta.'ico.png" &');
    }
    if ($opcion_mostrar_visitas && $mostrar_visitas){
        exec('notify-send -t 2500 "'.$titulo.'" "'. $imprime_visitas .'" -i "'.$ruta.'ico.png" &');
    }
?>

lunes, 8 de febrero de 2010

PHP - Curl y Proxy (Vota Summercase Boadilla)

Hoy nos sentimos democráticos, por ello mismo, como creemos en las reglas del juego, crearemos un script que votará en una encuesta tantas veces como nuestro número de proxys tengamos.

Para ello mismo, he decidido apoyar a los poppers amigos de lo indie y su festival por excelencia en Madrid, el Summercase.

Resulta que el ayuntamiento de Boadilla (localidad donde se realiza el festival) esta haciendo una encuesta preguntando si se debe seguir realizando el festival y la verdad, no les va muy bien, ya que ganan por poco y seguramente como van las cosas no habrá festival.

Por ello mismo, quiero aportar mi granito de arena. Seguramente tanto voto negativo esté causado por algún vecino anti poperos, con un mínimo conocimiento de programación. A pesar de todo esto, nos valdrá como perfecto ejemplo de como no hacer en la vida una encuesta. Como errores destacan: no hay Captcha y la única medida de seguridad que aporta es 1 voto por IP por día. Pues ya está, PROXYs a cholón y listo.

Lo primero de todo que necesitaremos, será una lista de proxys, en internet hay muchísimas, yo os adjunto una que es un poco mala pero no importa. El único requisito que tiene que cumplir vuestra lista es el siguiente: ip:puerto, una proxy por cada línea y que el fichero se llame proxys.txt

Aquí os dejo un ejemplo:
proxys.txt
125.163.255.154:8080
95.56.230.12:80
92.61.240.22:80
95.104.116.82:8080
121.31.126.93:80
87.250.47.219:8080
89.31.6.24:8080
84.20.81.196:8080
125.160.162.16:8080
202.143.146.205:8080
119.6.253.31:8000
208.180.65.242:8080
121.14.158.75:80
201.48.212.166:80
117.25.177.242:8080
200.141.202.162:8080
119.2.42.163:8080
202.90.112.43:8080
187.5.91.82:8080
208.180.60.126:8080
200.226.251.217:80
221.1.223.10:808
220.178.47.253:8080
202.159.90.163:80
202.57.33.134:8008
115.31.64.12:8008
189.108.142.5:8080
124.82.221.194:8080
41.154.7.52:8080
203.172.138.211:8080
200.25.200.178:8080
190.203.34.86:8080
200.3.170.210:80
201.72.7.2:80
202.143.129.200:8080
212.184.79.66:80
201.2.110.84:8080
200.14.96.57:80
119.70.40.102:8080
41.243.216.27:8080
217.10.246.4:8080
87.98.249.24:80
202.152.59.235:80
186.56.68.6:8080
119.70.40.101:8080
200.91.248.82:80
189.41.69.151:80
219.90.91.69:8080
190.228.70.4:80
114.57.172.78:80
125.162.38.175:8080
74.206.98.202:8080
222.66.116.108:8080
121.14.158.76:80
84.20.81.196:80
Una vez guardado el fichero, procederemos a crear el script en php que está bastante comentado por lo que sólo tenéis que leerlos para enteraros de  que hace.
vota_summercase.php
<?php
/*
 *      vota_summercase.php
 *     
 *      Copyright 2010 Don ZeYt
 *     
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *     
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *     
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
//Abrimos archivos de proxy
$archivo = "proxys.txt";
$f = fopen($archivo, "r");
$datos = fread($f, filesize($archivo));
fclose($f);
//Creamos array de proxys
$datos = explode("\n",$datos);
//URL votacion
$URL ="http://www.aytoboadilla.com/opinion/encuesta.asp";
//Inicializamos contadores
$error=0;
$acierto=0;
$proxy_error=0;
//Bucle para todas las proxys
foreach($datos as $d){
    //Separamos puerto de IP
    $d= explode(":",$d);
    $ip=$d[0];
    $puerto=$d[1];
    //Usamos CURL
    $ch = curl_init();
    echo $ip." ".$puerto."\n";
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXY, $ip);
    curl_setopt($ch, CURLOPT_PROXYPORT, $puerto);
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, "respuesta=r1");
    curl_setopt ($ch,CURLOPT_CONNECTTIMEOUT, 5);
    $datos = curl_exec($ch);
    curl_close($ch);
    //Si no son vacios
    if ($datos != ""){
        if (!ereg("contabilizado",$datos)){
            $error++;
            echo "Error ".$error."\n";
        }else{
            $acierto++;
            echo "Acierto ".$acierto."\n";
        }
    }else{
        $proxy_error++;
        echo "Error Proxy ".$proxy_error."\n";
    }
}
echo "Aciertos: ".$acierto." Errores: ".$error." Errores de Proxy: ".$proxy_error;
?>
Una vez guardado, el único requisito es que estén los dos archivos en el mismo directorio. Ahora bien, para votar sólo habrá que ejecutar el script. Si es tu primera vez leyendo este blog, para poder ejecutarlo necesitarás GNU/Linux con geany , geany con php, php5 y curl. También es valido cualquier editor, incluso subir el script a un servidor.
¡Si usas otro sistema operativo búscate la vida!

viernes, 15 de enero de 2010

PHP y Curl - Curling the nation



Curl es una librería en PHP que emplearemos bastante en este blog para hacer peticiones a cualquier tipo de protocolo, entre ellos, FTP, FTPS, HTTP, HTTPS, TFTP, SCP, SFTP, Telnet, DICT, FILE y LDAP.

También soporta certificados HTTPS, HTTP POST, HTTP PUT, subidas FTP, Kerberos, subidas mediante formulario HTTP, proxies, cookies, autentificación mediante usuario+contraseña (Basic, DIgest, NTLM y Negotiate para HTTP y kerberos4 para FTP), continuación de transferencia de archivos, tunneling de proxy http y muchas otras prestaciones lo que lo convierte en la auténtica navaja suiza.

Nosotros usaremos Curl con PHP aunque se puede trabajar como programa en un terminal pero no cumple los requisitos que nosotros queremos ya que mediante PHP podremos limpiar el resultado y manejarlo a nuestro antojo.

INSTALACIÓN
Primero de todo tienes que tener php5 y php5-cli para programar, compilar y ejecutar. Esto quedó explicado en ediciones anteriores. En cualquier caso para instalar curl ejecutaremos en un terminal:
  • sudo apt-get install php5-curl
Una vez instalado abriremos nuestro IDE favorito, en nuestro caso Geany y procederemos a crear nuestro primer programa de prueba.
<?php
    $ch = curl_init('http://www.example.com');//Dirección
    //curl_setopt ($ch, CURLOPT_POST, 1);//Para Enviar POST
    //curl_setopt ($ch, CURLOPT_POSTFIELDS, "usuario=peter&contra=hola");//Define usuario y contraseña
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Para guardar en variable la salida
    $salida= curl_exec ($ch);//Guardamos la salida en una variable
    curl_close ($ch);//Cerramos conexión
    echo $salida;
?>
Muy bien, he comentado el código para que aprendáis el funcionamiento básico. Las opciónes de POST están comentadas pues no se usarán de momento pero es útil tenerlas a mano para cuando queramos intentar INYECCIONES.

El script abre la página example.com e imprime su código fuente. Si lo ejecutamos a través de servidor se verá la página y si lo ejecutamos a través del IDE se verá el código fuente.


DESCARGARSE TODA LA WIKIPEDIA


Conseguir la WikiPedia por la cara es un ejemplo bastante sencillo pero realmente muestra la potencia de esta librería por eso os lo enseñamos. Para ello crearemos un sencillo script para bajarnos la WikiPedia entera a modo de buscador primitivo mediante la función especial del la wiki aleatoria.
Para ello creamos una carpeta llamada Enciclopedia y guardamos nuestro copypaste.php que contendrá:
<?php
 /*
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *     
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *     
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
    while (true){//Bucle infinito!
        $ch = curl_init('http://es.wikipedia.org/wiki/Especial:Aleatoria');
        //curl_setopt ($ch, CURLOPT_POST, 1);
        //curl_setopt ($ch, CURLOPT_POSTFIELDS, "contraseña='OR 1=1");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//Para que siga las redirecciones.
        $salida = curl_exec ($ch);
        curl_close ($ch);
        //Cogemos el título con expresión regular
        preg_match("/(\<title>)(.)*(\<\/title>)/i", $salida, $resultados);
        //Limpiamos el titulo para guardarlo
        $nombre = $resultados[0];
        $nombre = str_replace("<title>", "",$nombre);
        $nombre = str_replace("- Wikipedia, la enciclopedia libre</title>", "",$nombre);
        $nombre = str_replace(" ","_",$nombre);
        $nombre = $nombre.".html";
        if (!file_exists($nombre)){//No existe el archivo
            //Quitamos gran parte de información basura
            $salida = explode('<div id="content">',$salida);
            $salida = '<div id="content">'.$salida[1];
            $salida = explode('<div class="printfooter">',$salida);
            $salida = $salida[0];
            //Guardamos
            $fp = fopen($nombre, 'w');
            //Cabeceras para que no aparezcan códigos raros
            fwrite($fp,'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es" dir="ltr">
            <head>
            <title>'. str_replace("_"," ",$nombre).'</title>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
            fwrite($fp, $salida);
            fwrite($fp,"</html>");
            fclose($fp);
        }
    }
?>
 Ejecutamos, lo dejamos días y se nos baja la wikipedia entera :)

DESCARGARSE TODO XKCD


XKCD es un WebComic muy popular, su construcción de URLS es muy sencilla por lo que nos puede resultar bastante sencillo. Para ello crearemos el archivo xkcd.php que contendrá:
<?php
 /*
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *    
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *    
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */
    for ($i=1; $i<=688; $i++){//Numero de comics
        $ch = curl_init('http://xkcd.com/'.$i);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//Para que siga las redirecciones.
        $salida = curl_exec ($ch);
        curl_close ($ch);
        preg_match("/(http:\/\/imgs.xkcd.com\/comics\/)(.)*(\")/i", $salida, $resultados);
        $imagen = $resultados[0];
        $imagen = explode('"',$imagen);
        $imagen = $imagen[0];
        $ch = curl_init($imagen);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//Para que siga las redirecciones.
        $salida = curl_exec ($ch);
        curl_close ($ch);
        $imagen = str_replace("http://imgs.xkcd.com/comics/","",$imagen);
        $fp = fopen($imagen, 'w');
        fwrite($fp, $salida);
        fclose($fp);
        echo "guardado ".$i."\n";
       
    }
?>

OTRAS OPCIONES
Curl tiene muchas opciones, hemos visto algunas de ellas, pero aquí tenéis el ARRAY completo con todas las opciones.
$options = array(
CURLOPT_RETURNTRANSFER => true, //Devuelve la transferencia a la variable
CURLOPT_HEADER => true, //Envia las cabeceras
CURLOPT_FOLLOWLOCATION => false, //Acepta redirecciones
CURLOPT_ENCODING => "", //Codificacion
CURLOPT_USERAGENT => "Mi Navegador; Mi Sistema Operativo!!)",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
CURLOPT_POST => 2,
CURLOPT_POSTFIELDS => "$postfields", // datos post
CURLOPT_COOKIEFILE => "cookies.txt", // de donde leer cookies anteriormente guardadas
CURLOPT_COOKIEJAR => "cookies.txt" // en donde guardar cookies
);

 Ya sabéis, esto tiene muchísimas aplicaciones. Podéis hacer desde un navegador en PHP ha un cliente FTP pasando por actividades más divertidas como búsqueda y explotación de fallos.