I have a little python script that I wrote to populate my proxychains.conf file with valid public proxies. For each request, 10 proxies are retrieved and added to proxychains.conf, and this is done 3 times so that a total of 30 proxies are added.
When I was writing the script and having results return to stdout everything worked as expected = 30 proxies were retrieved and returned. However when I added the file operations part of the script only 10 proxies are written to the file. I'm still learning Python and I've tried to rearrange some things but it's not working out. I can't figure out if :
- my counter is in the wrong place?
- my file operations are in the wrong place?
Here is the code:
#!/usr/bin/env python3
import requests
import sys,os
proxy_file = '/etc/proxychains.conf'
base_url = 'http://proxy.tekbreak.com/10/json'
headers = {'user-agent':'Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20'}
def fetchprox():
pf = open(proxy_file, 'r')
lines = pf.readlines()
pf.close()
with open (proxy_file, 'w') as f:
del lines[69:]
f.writelines([item for item in lines[:-1]])
r = requests.get(base_url, headers=headers)
n = 0
while n < 10:
ip = r.json()[n]['ip']
port = r.json()[n]['port']
p_type = r.json()[n]['type']
#output to proxychains.conf
f.writelines(str(p_type + " " + ip + " " + port + "\n"))
n += 1
for i in range(0,3):
fetchprox()
Thanks for the help!
EDIT I found a solution based off of Giordano's answer, however I believe it could be implemented better. It seems redundant to have to access this file 3 times to just to write some data. So here is the portion of the script that was changed:
<--snip->
pf = open(proxy_file, 'r')
lines = pf.readlines()
pf.close()
f = open (proxy_file, 'w')
del lines[69:]
f.writelines([item for item in lines[:-2]])
f.close()
def fetchprox():
with open (proxy_file, 'a') as f:
r = requests.get(base_url, headers=headers)
n = 0
while n < 10:
<--snip-->
so is there a more efficient way to accomplish this?
proxy_fileand write the result to the same file. You overwrite it, so after the first iteration only 10 lines are left. No matter how many times you run the loop, it would always be 10 lines.