Интерфейсы к SOCKS5

anonymous-proxy-server

PHP

Используется cURL:

$ch=curl_init("http://www.fbi.gov");

   @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   // возвращаем результат, а не выводим его в печать
   @curl_setopt($ch, CURLOPT_VERBOSE, 0);
   //запрещаем выводить подробные сообщения о всех действиях
   @curl_setopt($ch, CURLOPT_HEADER, 0);
   // запрещаем Headers
   @curl_setopt($ch, CURLOPT_PROXY, "192.168.0.100:47047");
   //IP адрес и порт SOCKS5
   @curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); 
   //включаем использование SOCKS5
   $x=@curl_exec($ch);

curl_close($ch);

echo $x;
//выводим содержимое страницы в браузер

Python

Используем SocksiPy через wrapmodule()

1. Импортируем SocksiPy и другие модули
2. Запускаем setdefaultproxy() и передаем нужные данные
3. Загружаем целевой модуль внутри модуля wrapmodule()

# Импортируем нужные модули
import ftplib
import telnetlib
import urllib2

# Импортитуем SocksiPy
import socks

# Загружаем прокси
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 9050)

# Перенаправляем FTP-сессию через SOCKS прокси
socks.wrapmodule(ftplib)
ftp = ftplib.FTP('cdimage.ubuntu.com')
ftp.login('anonymous', 'chicago@ic.fbi.gov')
print ftp.dir('cdimage')
ftp.close()

# Перенаправляем соединение telnet через SOCKS прокси
socks.wrapmodule(telnetlib)
tn = telnetlib.Telnet('achaea.com')
print tn.read_very_eager()
tn.close()

# Перенаправляем HTTP-запросы через SOCKS прокси
socks.wrapmodule(urllib2)
print urllib2.urlopen('http://www.whatismyip.com/automation/n09230945.asp').read()

 

Используем SocksiPy через socksocket

1. Импортируем SocksiPy
2. Загружаем socks.socksocket, который возвращает несколько параметров для socket.socket.
3. Запускаем setproxy() и передаем нужные данные
4. Подключаемся и используем сокет, как обычный…

import socks
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_SOCKS5, 'localhost', 9050)
s.connect(('www.whatismyip.com', 80))
s.send('GET /automation/n09230945.asp HTTP/1.1\r\n\r\n')

data = ''
buf = s.recv(1024)
while len(buf):
data += buf
buf = s.recv(1024)
s.close()

print("Connected from %s." % (data))

Nginx redirect all HTTP request to HTTPS rewrite rules

776px-Nginx-battleship.svgI have setup nginx as a secure reverse proxy server. How do I redirect all http://example.com/ requests (traffic) to https://example.com/ under nginx web server?

The syntax is as follows. You need to add the following in location or server directives:

 

if ($host ~* ^(example\.com|www\.example\.com)$ ){
rewrite ^/(.*)$ https://example.com/$1 permanent;
}

OR better use the following rewrite:

rewrite ^ https://$server_name$request_uri? permanent;

Edit nginx.conf, enter:

# vi nginx.conf

You need to define both http and https server as follows:

 
## our http server at port 80
server {
      listen      1.2.3.4:80 default;
      server_name example.com www.example.com;
      ## redirect http to https ##
      rewrite        ^ https://$server_name$request_uri? permanent;
}

## Our https server at port 443. You need to provide ssl config here###
server {
      access_log  logs/example.com/ssl_access.log main;
      error_log   logs/example.com/ssl_error.log;
      index       index.html;
      root        /usr/local/nginx/html;
      ## start ssl config ##
      listen      1.2.3.4:443 ssl;
      server_name example.com www.example.com;

     ## redirect www to nowww
      if ($host = 'www.example.com' ) {
         rewrite  ^/(.*)$  https://example.com/$1  permanent;
      }

    ### ssl config - customize as per your setup ###
     ssl_certificate      ssl/example.com/example.com_combined.crt;
     ssl_certificate_key  ssl/example.com/example.com.key_without_password;
     ssl_protocols        SSLv3 TLSv1 TLSv1.1 TLSv1.2;
     ssl_ciphers RC4:HIGH:!aNULL:!MD5;
     ssl_prefer_server_ciphers on;
     keepalive_timeout    70;
     ssl_session_cache    shared:SSL:10m;
     ssl_session_timeout  10m;

    ## PROXY backend
      location / {
        add_header           Front-End-Https    on;
        add_header  Cache-Control "public, must-revalidate";
        add_header Strict-Transport-Security "max-age=2592000; includeSubdomains";
        proxy_pass  http://exampleproxy;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
      }
}

Save and close the file. Reload or restart the nginx:

# nginx -s reload

Test it:

$ curl -I http://example.com
$ curl -I http://example.com/foo/bar/file.html

Sample outputs:

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Sat, 01 Dec 2012 23:49:52 GMT
Content-Type: text/html
Content-Length: 178
Connection: keep-alive
Location: https://example.com/

Парсинг биржевых котировок

Решение задачи по парсингу биржевых котировок с финансовых сайтов. Используется только CURL для получения информации, все остальное — чистый PHP.

function get_web_page($url) {

$uagent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1017.2 Safari/535.19";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // возвращает веб-страницу
curl_setopt($ch, CURLOPT_HEADER, false); // не возвращает заголовки
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // переходит по редиректам
curl_setopt($ch, CURLOPT_ENCODING, ""); // обрабатывает все кодировки
curl_setopt($ch, CURLOPT_USERAGENT, $uagent); // useragent
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); // таймаут соединения
curl_setopt($ch, CURLOPT_TIMEOUT, 120); // таймаут ответа
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // останавливаться после 10-ого редиректа

$content = curl_exec($ch);

curl_close($ch);

return $content;
}

$url = "http://www.finam.ru";

$result = get_web_page($url);

//print $result;
//$text = $result;

print "
";
print "";

$result= mb_convert_encoding($result,'UTF-8','Windows-1251');

//VTB AO
$findme = $result;
$findme0 = "ВТБ ао";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,5); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//BRENT
$findme = $result;
$findme0 = "Brent*";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,6); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//NICKEL
$findme = $result;
$findme0 = "Никель";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,5); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

//GOLD
$findme = $result;
$findme0 = "Золото";
$pos1 = strpos($findme, $findme0); // вычисление позиции
$a1 = strlen($findme0); // длина строки поиска (60)
$b1 = substr($findme,$pos1); // отрезаем findme до позиции начала строки findme0
$c1 = substr($b1, 0, $a1);
$e1 = preg_replace('#(.*?)]* href=[^>]*?>(.*?)#', '\\1\\2\\3', $c1);
$findme2 = '';
$pos2 = strpos($b1, $findme2);
$a2 = strlen($findme2);
$b2 = substr($b1,$pos2);
$c2 = substr($b2,$a2);
$d2 = substr($c2,0,7); // size of value
$findme3 = "";
$pos3 = strpos($b2, $findme3);
$a3 = strlen($findme3);
$b3 = substr($b2,$pos3);
$c3 = substr($b3,$a3);
$d3_temp = substr($c3,0,6); // size of value
if (strval($d3_temp) < 0) {
$d3 = substr($c3,0,7);
$d3 = "".$d3."";
} else {
$d3 = substr($c3,0,6);
$d3 = "+".$d3."";
}
print "".$e1.": ".$d2." ".$d3."";
print "
";

print "";

?>

 

Интересная инфа тут: http://parsing-and-i.blogspot.com

Парсинг котировок валют

Как то надо было доставать котировки валют с внешнего сайта. Использовал CURL для получения контента и простой xml_parser_create для парсинга информации.

$res = '';

function startElement($parser, $name, $attrs) {
global $res;
switch ($name) {
case 'VALCURS':
$d = mb_convert_encoding(urldecode($attrs['DATE']),'UTF-8', 'windows-1251');
//$dd = $d[0].$d[1].$d[2].$d[3].$d[4];
//$res .= 'Дата: '.$dd.'';
break;
}
}

function endElement($parser, $name) {}

function contents($parser, $data) {
global $res;
$data = mb_convert_encoding($data,'windows-1251','UTF-8');
//$res .= trim($data)."";
}

$ch = curl_init();

//$date = date("d/m/Y");
//$url = "http://www.cbr.ru/scripts/XML_daily.asp?///date_req=".$date;
$url = "http://www.cbr.ru/scripts/XML_daily.asp";

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_PROXYPORT, 0);
curl_setopt($ch, CURLOPT_PROXY, '');

$data = curl_exec($ch);

curl_close($ch);

$XMLparser = xml_parser_create();

xml_set_element_handler($XMLparser, 'startElement', 'endElement');
xml_set_character_data_handler($XMLparser, 'contents');

$xml_array = file($url);

$res .= "".$xml_array[67].": ".$xml_array[70]."";
$res .= "".$xml_array[74].": ".$xml_array[77]."";
print $res;

if (!xml_parse($XMLparser, $data)) {
die('Ошибка обработки данных');
}

xml_parser_free($XMLparser);
?>

Интересная инфа тут: http://parsing-and-i.blogspot.com