-1

I am working on a project which requires accessing some websites with and without tor enabled, and record the content differences. I am working on deepin (which is a linux based debian distro), and using Python 2.7 to accomplish the task. The problem is that I have to manually enable/disable tor, and change the system proxy settings every time I run the script. Now, I am aware that I can issue a shell command from Python itself to enable tor (service tor start), but I cannot figure out how to enable/disable the system proxy settings from Python.

I have already tried this, but no luck.

Khizar Amin
  • 198
  • 1
  • 2
  • 12
  • *debian based linux distro – Khizar Amin May 28 '19 at 10:00
  • Possible duplicate of [How to pass all Python's traffics through a http proxy?](https://stackoverflow.com/q/31639742/608639), [How to unset the 'http_proxy' environment variable in Python](https://unix.stackexchange.com/q/425442), etc. – jww May 28 '19 at 10:22
  • it is not a duplicate to that question. That question deals with HTTP proxy. Tor is a SOCKS proxy, that the question does not address. – Khizar Amin May 28 '19 at 12:14

2 Answers2

1

Use os.system to set the desired proxy like this.

import os
os.system("export http_proxy="http://username:Password@Proxy_IP:Port/")

To unset, simply use

os.system("unset http_proxy")

EDIT

Tor uses SOCKS proxy. For socks proxy, use

os.system("export socks_proxy="socks://username:Password@Proxy_IP:Port/")
Divyanshu Srivastava
  • 1,379
  • 11
  • 24
  • The problem is, Tor is not an HTTP proxy, its rather a SOCKS proxy. I tried modifying your code to "socks_proxy" instead of "http_proxy", and then tried used requests.session() to get my IP from http://httpbin.org/ip, but the returned IP was the same as my original IP address, which means the request did not go through tor. I used: os.system("export socks_proxy=\"http://:@127.0.0.1:9050/\"") – Khizar Amin May 28 '19 at 12:20
  • @KhizarAmin I am updating my answer for socks proxy. What u tried for socks is partially correct. Please see the edit in answer for the correct command. – Divyanshu Srivastava May 29 '19 at 06:13
0

Got the thing working, posting here in case someone else has the same problem:

from selenium import webdriver
import stem.process
from stem import Signal
from stem.control import Controller
from splinter import Browser
proxyIP = "127.0.0.1"
proxyPort = 9050
proxy_settings = {"network.proxy.type":0,
    "network.proxy.socks": proxyIP,
    "network.proxy.socks_port": proxyPort
}
browser = Browser('firefox', profile_preferences=proxy_settings)
driver = browser.driver
driver.get('https://whatismyip.com')

changing network.proxy.type to 1 resets the proxy settings. Solution found here

Khizar Amin
  • 198
  • 1
  • 2
  • 12