Поиск по блогу

среда, 24 сентября 2014 г.

Пробуем выполнить код из TOR With Python Tutorial #2 ( видео 2)

Смотрим второе видео, в котором к простому примеру (из первого видео, которое я посмотрел в мае) добавляется метод def newIdentity(). В примерах использовались библиотеки socket, socks, httplib . Исправляем ошибки и запускаем пример из первого видео - connectTor(), но поменять IP newIdentity() здесь не удается - raise SOCKS5Error("{:#04x}: {}".format(status, error))

TOR With Python Tutorial #1 С модулями socks socket ...по мотивам видеоролика и нового репозитория Pysocks на GitHub
SocksiPy - A Python SOCKS client module
TOR With Python Tutorial #1 С модулями socks socket ...по мотивам видеоролика и нового репозитория Pysocks на GitHub
How can I use a SOCKS 4/5 proxy with urllib2? -
Tor with Python?
Crawling anonymously with Tor in Python
socksipyhandler.py
How to make HTTP request through a (tor) socks proxy using python?
Emulating SSH's SOCKS Proxy Tunnel in Python
socks.setdefaultproxy
Where is the Tor API documentation?
SOCKS5 proxy using urllib2 and PySocks
Anorov/PySocks

Здесь примеры и ссылки с urllib2. Поскольку эта библиотека поддерживает только http(s) прокси. То либо подключают Privoxy, либо создают загрузчик

In []:
0:00is welcome back to your second video on how do you store
0:03alongside Python 9 the spill your gonna start to take a look at
0:07the different ways in which you can control tower from within your paper
0:11applications
0:12so I'm gonna jump back into the script that we were at last time
0:16where we simply connected to tour
0:19and demonstrated we're definitely running
0:23all over traffic through the SOCKS proxy
0:27into tower and therefore become mean anonymous
0:31or well slightly more anonymous then we would be
0:36through tour now
0:39in this tutorial we're going to take a look at controlling tore and the
0:43different commands
0:44you can issued from within Python to make it to simi
0:48things for this example I'm gonna show you guys how to
0:53request a new identity within two or
0:56mean it should give you a an entirely new IP address
1:00an entirely new right for all this year Internet traffic to go through
1:04so to do this we are going to create a new function
1:09in our place in script right here we're going to define a function
1:13hold analytical news and Danny
1:16and synthetic fairly good name for what it's going to be doing
1:20and the first thing that we want this function to do
1:24is we wanted to sleep sucks not set
1:27different proxy and we're going to leave the parameters
1:33plank know if this is going to is it's pretty much going to make it
1:37this line right here sock starts at default proxy
1:41to art for proxy know the reason we're doing this
1:45is because to issue tower commands on our local machine
1:50we can't be connected to tour at the same time
1:53otherwise is going to try to issue commands to to renew
1:57were connected to and set a firm local machine so
2:01as soon as we have Kinder's
2:05disconnected from torrent here week and start getting to work on
2:09issuing commands to are
2:12local tour proxy and to do so
2:15going to create a new variable simply called s which is for socket
2:19and concerta anything new socket
2:23dart socket and the first
2:26parameter 2x market in I napped
2:30and a certain player concluded sent to socket:
2:34sucks 3 know this is a pretty basic circuit variable
2:38and it's going to be used to connect to Artur control port
2:42which you can use to can issue love her commands and
2:46going to send and receive data for
2:49to and from tore through the soccer here to
2:53you're going to cool stuck and we're going to connect to
2:58127 don't sealed off 2.1 once again
3:02which is our local IP address which tour is running on
3:05but this time we're not going to connect in 1950
3:08as airport words taken clinton ninety 51
3:12which is the port used to control tower which is slightly different from the
3:16port we used up here which is 9050
3:19which we use to proxy through
3:22so once we've connected or sock it to the tour Control Board
3:26the next thing we're gonna do need to do is we're going to need to send a command
3:30of some sort
3:31and to do so we're just gonna cool s tufts and
3:35and we're going to simply send string
3:39which says of then tikki followed by
3:43backslash are and backslash and
3:46which is carried returned newline pretty much this command right here
3:51stats and authenticated is just going to
3:55authenticate a swift or or art or control port router
3:59and it's going to allow us to Kenneth issue commands
4:03and it's just kinda something you need to do
4:07before you can send any proper commands through to renew authenticate yourself
4:11with your own
4:13tower control poor first I'll go into the little
4:17and a little more in depth in the next tutorial
4:20overpass for protecting our tour control port but for now you can just use and
4:25stuff then
4:26authenticate followed by carriage return and a new line
4:29or backlash on percussion so once we've sent
4:33he a request to authentic yourself with our tour Control Board
4:38we need to store art or control ports reply
4:41and variable and corresponds we're gonna call response
4:46equals are see
4:49RTC be sorry and
4:53going to receive 128 bytes to
4:57we should be more than enough for anything we want to
5:00received from our tour Control Board
5:04so once we've received a response right here what we need to do is check
5:08is to responded positively or respond
5:11negatively chances are he
5:15have your tour control port password-protected
5:18and you tend to authenticate with the incorrect or new password
5:23it's going to respond negatively and will too late to issue commands
5:28however if it has responded positively you can check
5:32easy and response to starts
5:35way and we're gonna check response start
5:38starts with 250 which is the code for a positive response from tour
5:44and what we want to do is we want to send another command
5:47you wanna send s dots and
5:51and this time we want to send signal space
5:55new mean which is just going to
5:58asked or to provide us with the new year IP address and I can do
6:02completely new identity from now on and we're also gonna finish this with
6:06carriage return new vine backslash are backslash
6:10and once again and we've sent a request
6:14to get a new identity we can actually close the sport because that's really
6:18all we need to do
6:20we could cuddle s don't clues
6:23and finally in our new identity function because we
6:27over week overrated this
6:30answer to for proxy which is loans to proxy through tour
6:34we can have turned this off and disconnected from two right here
6:38so we're going to have to call connect or
6:41mckeon just to ensure that work and is connected to tour
6:44and we're not assuming that we're connected to tour when we actually
6:48aren't
6:49so we're just gonna call it explicitly right here just to make sure
6:53now with an army in function the contest the site
6:57I'm going to try beneath their code
7:00which will printer IP address to the command line
7:03and going to try calling the new
7:06identity function right here which should in theory
7:09if the schools or correct that is it should give us an entirely new identity
7:14and a new IP address
7:16and to test whether this is working on a and copying keys
7:19of this code which is 29 I peter
7:23IP address I to the consul
7:26I'm gonna ps2 right here would be a good idea to put this in its own separate
7:30function
7:31the for the sake of time I'm just gonna copy and paste
7:35okay so now we can see if this and we contested
7:39if a champion in the command line right here and try running
7:43forward to hi which is the name the script that i've
7:46been making right here I'll try callin
7:49we see we've got connected to tour
7:53knife with a couple seconds we should get her first
7:57IP address which is visible
8:02and we can your
8:05sorry about that we actually meant to do here was s
8:09dark rect no can see if this
8:12and try running the turkey and hopefully this time
8:16the clear the screen for Central Committee with this time
8:19work with owners and we get connected to tour
8:25there's our first IP address which is visible to the web server
8:30if everything's gone correctly we should have gotten a new identity
8:34and her second peter it should be different from for school
8:38and there you have it our second IP address is slightly different era first
8:42when they're actually fairly similar
8:44but there is a slight difference you teen change it it changed from 97 to 96
8:50from forty 6201 showing that are
8:54code for retrieving a new identity definitely did work
8:58so that's basically all im gonna go through today goes I hope you can have
9:02understood about sheet or with commands
9:06through the torque amanpour I'm going to be good for the soul more in future
9:10tutorials
9:11to I mean if you didn't understand anything you can only send me a message
9:14or comment on the video
9:16but I thanks for watching and I'll see you guys next time
In [4]:
%load "C:\\Users\\kiss\\Desktop\\Tor Browser\\Data\\Tor\\torrc-defaults"
In []:
# If non-zero, try to write to disk less frequently than we would otherwise.
AvoidDiskWrites 1
# Where to send logging messages.  Format is minSeverity[-maxSeverity]
# (stderr|stdout|syslog|file FILENAME).
Log notice stdout
# Bind to this address to listen to connections from SOCKS-speaking
# applications.
SocksPort 9150
ControlPort 9151
CookieAuthentication 1
## fteproxy configuration
ClientTransportPlugin fte exec Tor\PluggableTransports\fteproxy --managed

## obfsproxy configuration
ClientTransportPlugin obfs2,obfs3 exec Tor\PluggableTransports\obfsproxy managed

## flash proxy configuration
#
# Change the second number here (9000) to the number of a port that can
# receive connections from the Internet (the port for which you
# configured port forwarding).
ClientTransportPlugin flashproxy exec Tor\PluggableTransports\flashproxy-client --register :0 :9000
In []:
In [48]:
# Beginning of code from video TOR With Python Tutorial #2 
import socket
import socks
import httplib
In [49]:
def connectTor():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9150, True)
    socket.socket = socks.socksocket # we can just reset socket.socket !!!  
In [20]:
def main():
    connectTor()
    print("Connected to Tor")
    conn=httplib.HTTPConnection("my-ip.heroku.com")
    conn.request("GET","/")
    response=conn.getresponse()
    print(response.read())
In [21]:
#if __name__=="__main__":
main()
# end of code from video TOR With Python Tutorial #1    
Connected to Tor
81.89.96.88


In []:
socks.
In [18]:
conn=httplib.HTTPConnection("my-ip.heroku.com")
In [19]:
conn.request("GET","/")
response=conn.getresponse()
print(response.read())
81.89.96.88


In [2]:
s=socket.socket
In [54]:
def newIdentity():
    #socks.setdefaultproxy()
    
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    s.connect(("127.0.0.1",9151)) #connect with Tor control port 
    s.send("AUNTHENTICATE\r\n")
    
    response=recv(128)
    if response.startswith("250"):  #250 - The code of Tor positive response
        s.send("SIGNAL NEWNYM\r\n") # Ask to provide a new year IP address 
    s.close()
    
    connectTor()
In [51]:
def main():
    connectTor()
    print("Connected to Tor")
    conn=httplib.HTTPConnection("my-ip.heroku.com")
    conn.request("GET","/")
    response=conn.getresponse()
    print(response.read())
    
    newIdentity()
    conn2=httplib.HTTPConnection("my-ip.heroku.com")
    conn2.request("GET","/")
    response2=conn2.getresponse()
    print(response2.read())
    
In [55]:
main()
Connected to Tor
94.242.251.112

---------------------------------------------------------------------------
SOCKS5Error                               Traceback (most recent call last)
<ipython-input-55-58ca95c5b364> in <module>()
----> 1 main()

<ipython-input-51-2e3807799eb2> in main()
      7     print(response.read())
      8 
----> 9     newIdentity()
     10     conn2=httplib.HTTPConnection("my-ip.heroku.com")
     11     conn2.request("GET","/")

<ipython-input-54-4d72254c69b7> in newIdentity()
      4     s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      5 
----> 6     s.connect(("127.0.0.1",9151)) #connect with Tor control port
      7     s.send("AUNTHENTICATE\r\n")
      8 

C:\Users\kiss\Anaconda\lib\site-packages\socks.pyc in connect(self, dest_pair)
    494             try:
    495                 # Calls negotiate_{SOCKS4, SOCKS5, HTTP}
--> 496                 self.proxy_negotiators[proxy_type](dest_addr, dest_port)
    497             except socket.error as error:
    498                 # Wrap socket errors

C:\Users\kiss\Anaconda\lib\site-packages\socks.pyc in _negotiate_SOCKS5(self, dest_addr, dest_port)
    332             # Connection failed: server returned an error
    333             error = SOCKS5_ERRORS.get(status, "Unknown error")
--> 334             raise SOCKS5Error("{:#04x}: {}".format(status, error))
    335 
    336         # Get the bound address/port

SOCKS5Error: 0x01: General SOCKS server failure

In [56]:
get_default_proxy()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-56-06114178edf7> in <module>()
----> 1 get_default_proxy()

NameError: name 'get_default_proxy' is not defined

Adding an alternative to pan's answer when you need to use many different proxies at the same time.

In that case you need to create an opener like you do with a http proxy. There is a code available in GitHub https://gist.github.com/869791

In []:
opener = urllib2.build_opener(SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, 'localhost', 9999))
print opener.open('http://www.whatismyip.com/automation/n09230945.asp').read()


Посты чуть ниже также могут вас заинтересовать

Комментариев нет:

Отправить комментарий