I have just downloaded instabot but when i tried to execute it i saw some errors, this is the main module("example.py"),there is source code :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
sys.path.append(os.path.join(sys.path[0],'src'))
from instabot import InstaBot
from check_status import check_status
from feed_scanner import feed_scanner
from unfollow_protocol import unfollow_protocol
from follow_protocol import follow_protocol
import time
bot = InstaBot(login="username", password="password",
like_per_day=1000,
comments_per_day=0,
tag_list=['follow4follow', 'f4f', 'cute'],
tag_blacklist=['rain', 'thunderstorm'],
user_blacklist={},
max_like_for_one_tag=50,
follow_per_day=300,
follow_time=1*60,
unfollow_per_day=300,
unfollow_break_min=15,
unfollow_break_max=30,
log_mod=0,
proxy='',
# Use unwanted username list to block users which have username contains one of this string
## Doesn't have to match entirely example: mozart will be blocked because it contains *art
### freefollowers will be blocked because it contains free
unwanted_username_list=['second','stuff','art','project','love','life','food','blog','free','keren','photo','graphy','indo',
'travel','art','shop','store','sex','toko','jual','online','murah','jam','kaos','case','baju','fashion',
'corp','tas','butik','grosir','karpet','sosis','salon','skin','care','cloth','tech','rental',
'kamera','beauty','express','kredit','collection','impor','preloved','follow','follower','gain',
'.id','_id','bags'])
while True:
#print("# MODE 0 = ORIGINAL MODE BY LEVPASHA")
#print("## MODE 1 = MODIFIED MODE BY KEMONG")
#print("### MODE 2 = ORIGINAL MODE + UNFOLLOW WHO DON'T FOLLOW BACK")
#print("#### MODE 3 = MODIFIED MODE : UNFOLLOW PEOPLE WHO DON'T FOLLOW BACK BASED ON RECENT FEED ONLY")
#print("##### MODE 4 = MODIFIED MODE : FOLLOW PEOPLE BASED ON RECENT FEED ONLY")
#print("###### MODE 5 = MODIFIED MODE : JUST UNFOLLOW EVERYBODY, EITHER YOUR FOLLOWER OR NOT")
################################
## WARNING ###
################################
# DON'T USE MODE 5 FOR A LONG PERIOD. YOU RISK YOUR ACCOUNT FROM GETTING BANNED
## USE MODE 5 IN BURST MODE, USE IT TO UNFOLLOW PEOPLE AS MANY AS YOU WANT IN SHORT TIME PERIOD
mode = 0
#print("You choose mode : %i" %(mode))
#print("CTRL + C to cancel this operation or wait 30 seconds to start")
#time.sleep(30)
if mode == 0 :
bot.new_auto_mod()
elif mode == 1 :
check_status(bot)
while bot.self_following - bot.self_follower > 200:
unfollow_protocol(bot)
time.sleep(10*60)
check_status(bot)
while bot.self_following - bot.self_follower < 400:
while len(bot.user_info_list) <50 :
feed_scanner(bot)
time.sleep(5*60)
follow_protocol(bot)
time.sleep(10*60)
check_status(bot)
elif mode == 2 :
bot.bot_mode = 1
bot.new_auto_mod()
elif mode == 3 :
unfollow_protocol(bot)
time.sleep(10*60)
elif mode == 4 :
feed_scanner(bot)
time.sleep(60)
follow_protocol(bot)
time.sleep(10*60)
elif mode == 5 :
bot.bot_mode=2
unfollow_protocol(bot)
else :
print ("Wrong mode!")
when i launched it i saw those errors :
Trying to login as username...
Traceback (most recent call last):
File "example.py", line 35, in <module>
'.id','_id','bags'])
File "/home/mohand/Desktop/instabot.py-master/src/instabot.py", line 185, in __init__
self.login()
File "/home/mohand/Desktop/instabot.py-master/src/instabot.py", line 224, in login
r = self.s.get(self.url)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 501, in get
return self.request('GET', url, **kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 488, in request
resp = self.send(prep, **send_kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/sessions.py", line 609, in send
r = adapter.send(request, **kwargs)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/adapters.py", line 423, in send
timeout=timeout
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 594, in urlopen
chunked=chunked)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 350, in _make_request
self._validate_conn(conn)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py", line 835, in _validate_conn
conn.connect()
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/connection.py", line 330, in connect
cert = self.sock.getpeercert()
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 324, in getpeercert
'subjectAltName': get_subj_alt_name(x509)
File "/home/mohand/.local/lib/python2.7/site-packages/requests/packages/urllib3/contrib/pyopenssl.py", line 171, in get_subj_alt_name
ext = cert.extensions.get_extension_for_class(
AttributeError: 'Extensions' object has no attribute 'get_extension_for_class'
I'm using python 3.5 please i need help :)
You might want to upgrade your version of cryptography. Check here for details on this issue
Try This:
sudo pip install cryptography --upgrade
Related
can anyone help? I got an error when I was trying to test a simple code with napalm. I used cisco on GNS3. I also added optional arguments (delay_factor), but it got the same error.
from napalm import get_network_driver
driver = get_network_driver("ios")
others = {
"secret" : "cisco",
"dest_file_system" : "nvram:",
'delay_factor': 5
}
device = driver(hostname="192.168.124.148", username="cisco", password="cisco", optional_args=others)
device.open()
device.load_merge_candidate(filename="candidate")
compare = device.compare_config()
print(compare)
device.commit_config()
device.close()
Traceback (most recent call last):
File "c.py", line 16, in <module>
device.commit_config()
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/napalm/ios/ios.py", line 555, in commit_config
output += self.device.save_config()
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/cisco/cisco_ios.py", line 37, in save_config
return super(CiscoIosBase, self).save_config(
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/cisco_base_connection.py", line 224, in save_config
output = self.send_command(command_string=cmd)
File "/Users/zakky.muhammad/Downloads/tmp/Env/lib/python3.8/site-packages/netmiko/base_connection.py", line 1335, in send_command
raise IOError(
OSError: Search pattern never detected in send_command_expect: R\#
You can use the code that I have shared below.
from napalm import get_network_driver
driver = get_network_driver('eos')
device = driver('ip_address', 'username', 'password')
device.open()
device.load_replace_candidate(filename='device.conf')
print (device.compare_config())
if len(device.compare_config()) > 0:
choice = input("\nWould you like to Replace the Configuration file? [yN]: ")
if choice == 'y':
print('Committing ...')
device.commit_config()
choice = input("\nWould you like to Rollback to previous config? [yN]: ")
if choice == 'y':
print('Rollback config is in progress ...')
device.rollback()
else:
print('Discarding ...')
device.discard_config()
else:
print ('No difference')
device.close()
print('Done.')
I'm not trying to download the whole video, just 5 seconds of a video. I tried following this guide. However, this is for in line command and I'm trying to do this with python code. So far I've managed to extract all the required information using youtube-dl. The problem I'm having now is using ffmpeg to output the video with the given parameters, but it's saying it cannot find the file specified.
This is what I have so far:
import youtube_dl
import datetime
import ffmpeg
def getInfo():
link='https://youtu.be/nda20uSjQUI?t=11981'
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})
#This exctracts all the information of the link
with ydl:
result = ydl.extract_info(
link,
download=False
)
#Grabs the duration of the video
duration_info = result.get('duration')
#Grabs the url to the actual video file
url = str(result).split("'url':",1)[1].split(', ')[0]
#YouTube(link).streams.first().download('D:/Downloads')
#Determines the start time based on how the link is formatted
#They can be in three possible formats
if 't=' in link:
if link.endswith('s'):
time_seconds = link.split('t=', 1)[1].strip('s')
else:
time_seconds = link.split('t=', 1)[1]
else:
time_seconds = '0'
#Converts the time into an HH:MM:ss format
#We only want 5 seconds of video, which is what timestamp_end does
timestamp_start = str(datetime.timedelta(seconds=int(time_seconds)))
timestamp_end = str(datetime.timedelta(seconds=int(time_seconds)+5))
video_length = str(datetime.timedelta(seconds=int(duration_info)))
#If the segment we want is less than 5 seconds, such as towards the end of the video,
#then the end will be the end of the actual video
if timestamp_end > video_length:
timestamp_end = video_length
#Returns a list of [url, start, end]
return url ,timestamp_start,timestamp_end
def download_video(result):
#Checks to see if there's a valid argument
if result is None:
return 'Error: no url found'
else:
file_input = ffmpeg.input(result[0])
out = ffmpeg.concat(file_input.trim(start_frame=result[1],end_frame=result[2])).output('test1.mp4').run()
return out
download_video(result=getInfo())
And this is the error I'm getting:
Traceback (most recent call last):
File "C:/Users/Anonymous/PycharmProjects/untitled/test.py", line 53, in <module>
download_video(result=getInfo())
File "C:/Users/Anonymous/PycharmProjects/untitled/test.py", line 50, in download_video
out = ffmpeg.concat(file_input.trim(start_frame=result[1],end_frame=result[2])).output('test1.mp4').run()
File "C:\Users\Anonymous\PycharmProjects\untitled3\venv\lib\site-packages\ffmpeg\_run.py", line 320, in run
overwrite_output=overwrite_output,
File "C:\Users\Anonymous\PycharmProjects\untitled3\venv\lib\site-packages\ffmpeg\_run.py", line 285, in run_async
args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\Lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\Lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
Process finished with exit code 1
I'm trying to write a small python 3 utility script that checks to see if a file exists on my server.
So I have the code below that has a big array of string values that I pass to a simple function that returns the url and the response code.
However, when I run it I get all these errors I don't even know where to start:
$ python ReturnPath.py
Traceback (most recent call last):
File "ReturnPath.py", line 86, in <module>
checkResponse(u)
File "ReturnPath.py", line 5, in checkResponse
code = urllib.request.urlopen(url).getcode()
File "C:\Program Files\Python37\lib\urllib\request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "C:\Program Files\Python37\lib\urllib\request.py", line 510, in open
req = Request(fullurl, data)
File "C:\Program Files\Python37\lib\urllib\request.py", line 328, in __init__
self.full_url = url
File "C:\Program Files\Python37\lib\urllib\request.py", line 354, in full_url
self._parse()
File "C:\Program Files\Python37\lib\urllib\request.py", line 383, in _parse
raise ValueError("unknown url type: %r" % self.full_url)
ValueError: unknown url type: '"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg"'
Here is my code:
import urllib.request
def checkResponse(url):
code = urllib.request.urlopen(url).getcode()
print(url + " = " + code)
return
arrCases = []
arrCases.extend([
"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg",
"https://myserver.org/Media/CharacterAvatarImages/3ea92fa3-1ef0-4358-b38d-bb04e653aa53.jpg",
"https://myserver.org/Media/CharacterAvatarImages/7958a0e3-171b-46b5-875e-970368389bdf.jpg",
"https://myserver.org/Media/CharacterAvatarImages/e9a6cb00-6811-4b47-9aac-88480578dd44.jpg",
"https://myserver.org/Media/CharacterAvatarImages/73df88c3-b829-4519-9523-2bbe1f2c8549.jpg",
"https://myserver.org/Media/CharacterAvatarImages/61aa614b-5c95-487c-b4e3-783231b43677.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8be7811f-18dc-4a81-a557-8b81605e3452.jpg",
"https://myserver.org/Media/CharacterAvatarImages/56539acb-2b1b-4410-a4bc-ac2eb0dc00fa.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8bcf93fc-b435-4fd4-9c82-4aba78c58529.jpg",
])
for u in arrCases:
checkResponse(u)
What am I doing wrong?
You have to catch errors from broken URLs. I also increased speed through multiprocessing.Pool.
import urllib.request
from urllib.error import HTTPError, URLError
import multiprocessing
def checkResponse(url):
try:
code = urllib.request.urlopen(url, timeout=1).getcode()
except (HTTPError, URLError) as error:
print(url, " = ", error)
else:
print(url, " = ", code)
return
arrCases = []
arrCases.extend([
"https://i.stack.imgur.com/DsNOB.jpg",
"https://myserver.org/Media/CharacterAvatarImages/ae275ecb-183e-4e8d-8465-9d6d36c1323f.jpg",
"https://myserver.org/Media/CharacterAvatarImages/3ea92fa3-1ef0-4358-b38d-bb04e653aa53.jpg",
"https://myserver.org/Media/CharacterAvatarImages/7958a0e3-171b-46b5-875e-970368389bdf.jpg",
"https://myserver.org/Media/CharacterAvatarImages/e9a6cb00-6811-4b47-9aac-88480578dd44.jpg",
"https://myserver.org/Media/CharacterAvatarImages/73df88c3-b829-4519-9523-2bbe1f2c8549.jpg",
"https://myserver.org/Media/CharacterAvatarImages/61aa614b-5c95-487c-b4e3-783231b43677.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8be7811f-18dc-4a81-a557-8b81605e3452.jpg",
"https://myserver.org/Media/CharacterAvatarImages/56539acb-2b1b-4410-a4bc-ac2eb0dc00fa.jpg",
"https://myserver.org/Media/CharacterAvatarImages/8bcf93fc-b435-4fd4-9c82-4aba78c58529.jpg",
])
with multiprocessing.Pool(processes=4) as pool:
pool.map(checkResponse, arrCases)
I`m trying to upload a video on youtube via a script, but when I execute the script I get this error. The json file is working as I tested it with another script that does the same thing in a different way.I tried everything this is my last chance or I will give up on this script.
If you need more details please let me know, I appreciate your effort!
This is the error I get:
Extra data: line 1 column 427 (char 426)
Traceback (most recent call last):
File "publisher/botTest.py", line 54, in <module>
youtubeService.uploadVideoToYouTube(config)
File "/root/publisher/core/services/youtube.py", line 202, in uploadVideoToYouTube
youtube = getAuthenticatedService(CREDENTIALS_FILE)
File "/root/publisher/core/services/youtube.py", line 69, in getAuthenticatedService
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES,redirect_uri='urn:ietf:wg:oauth:2.0:oob')
File "/usr/local/lib/python3.6/dist-packages/google_auth_oauthlib/flow.py",
line 172, in from_client_secrets_file
client_config = json.load(json_file)
File "/usr/lib/python3.6/json/__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 427 (char 426)
line 202 form youtube.py:
def uploadVideoToYouTube(config):
CREDENTIALS_FILE = constants.SECRETS_ROOT_LOCATION + config['channel'][1] + '/' +
constants.YOUTUBE_CHANNEL_CREDENTIALS_FILE_NAME
if os.path.isfile(CREDENTIALS_FILE):
youtube = getAuthenticatedServiceFromStorage(CREDENTIALS_FILE)
print(os.path.isfile(CREDENTIALS_FILE))
print(CREDENTIALS_FILE) else:
os.makedirs(constants.SECRETS_ROOT_LOCATION + config['channel'][1])
youtube = getAuthenticatedService(CREDENTIALS_FILE)
line 69 in youtube.py:
# Authorize the request and store authorization credentials. Used to
# generate first auth token. Only needs to happen once.
def getAuthenticatedService(CREDENTIALS_FILE):
flow =InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES,
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
auth_url, _ = flow.authorization_url(prompt='consent')
print('Please go to this URL: {}'.format(auth_url))
code = input('Enter the authorization code: ')
credentials = flow.fetch_token(code=code)
saveCredentials(CREDENTIALS_FILE, credentials)
return build(API_SERVICE_NAME, API_VERSION, credentials = flow.credentials)
Im trying to automate the registration of serial numbers in an online form using Selenium 2.53.5 in Python 2.7. The script has been working for 2+ months, but yesterday I started receiving an error right when I go to run it: httplib.BadStatusLine: ''. Is there any known fix for this? I've read that leading/trailing new line characters can mess up the retrieving of the url but I can't seem to identify the issue.
Code:
import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class SerialSet:
def __init__(self, fileName, driverPath, user, password):
self.fn = fileName
self.failedSerials = []
self.driver = webdriver.Chrome(driverPath)
self.aloSuccess = False
self.user = user
self.password = password
def parseSerialFile(self):
with open(self.fn, 'r') as f:
self.serials = [line.strip() for line in f]
def setCountrySN(self, serial, driver):
driver.find_element_by_xpath("//select/option[#value='USA']").click()
driver.find_element_by_id("serialno").send_keys(serial)
driver.find_element_by_xpath("//input[#value='Continue'][#type='button']").click()
def submitState(self, driver):
driver.find_element_by_xpath("//select/option[#value='CT']").click()
driver.find_element_by_id("Continue1").click()
def login(self, driver):
driver.find_element_by_xpath("//*[#id='accountname']").send_keys(self.user)
driver.find_element_by_xpath("//*[#id='accountpassword']").send_keys(self.password)
driver.find_element_by_xpath("//*[#id='signInHyperLink']").click()
def initiateSN(self, serial, driver):
# select country and enter serialno
driver.get("http://supportform.apple.com/201110/")
self.setCountrySN(serial, driver)
# enter login
time.sleep(3)
if driver.current_url == "http://supportform.apple.com/201110/":
return False
self.login(driver)
# select state and continue
time.sleep(3)
self.submitState(driver)
# final submit
time.sleep(3)
driver.find_element_by_id("finalContinue").click()
return True
def newSN(self, serial, driver):
# select country and enter serialno
driver.get("http://supportform.apple.com/201110/")
self.setCountrySN(serial, driver)
# select state and continue
time.sleep(3)
if driver.current_url == "http://supportform.apple.com/201110/":
return False
self.submitState(driver)
# final submit
time.sleep(3)
driver.find_element_by_id("finalContinue").click()
return True
def automateSerials(self):
for i in self.serials:
if self.aloSuccess == False:
if not self.initiateSN(i, self.driver):
self.failedSerials.append(i)
del i
else:
self.aloSuccess = True
else:
if not self.newSN(i, self.driver):
self.failedSerials.append(i)
del i
self.driver.quit()
print(str(len(self.serials) - len(self.failedSerials)) + ":" + str(len(self.serials)))
def main():
newSet = SerialSet(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
newSet.parseSerialFile()
newSet.automateSerials()
if __name__ == "__main__":
main()
Error:
Traceback (most recent call last):
File "automate.py", line 90, in <module>
main()
File "automate.py", line 85, in main
newSet = SerialSet(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
File "automate.py", line 11, in __init__
self.driver = webdriver.Chrome(driverPath)
File "/Library/Python/2.7/site- packages/selenium/webdriver/chrome/webdriver.py", line 67, in __init__
desired_capabilities=desired_capabilities)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 90, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 177, in start_session
response = self.execute(Command.NEW_SESSION, capabilities)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 234, in execute
response = self.command_executor.execute(driver_command, params)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 401, in execute
return self._request(command_info[0], url, body=data)
File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 432, in _request
resp = self._conn.getresponse()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1132, in getresponse
response.begin()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 453, in begin
version, status, reason = self._read_status()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 417, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine: ''
Make sure your using the latest version chromedriver:
http://chromedriver.storage.googleapis.com/2.25/chromedriver_linux64.zip
I installed chromedriver 2.0 and got this error,
when I upgraded to 2.25 it got rid of this error.