I want to get the SSID and Password from the user und connect it to WIFI.
I'm using Raspbian and Python3 for that.
My Code:
#!/user/bin/python3.5
#!/user/bin/env python
from wifi import Cell, Scheme
def WirelessConnection():
userSSID = input("Enter the SSID: ")
userPass = input("Enter the Password: ")
cells = Cell.all('wlan0')
schemes = list(Scheme.all())
for cell in cells:
if cell.ssid == userSSID:
print('Connecting to %s' % userSSID)
passKey = userPass
scheme = Scheme.for_cell('wlan0', 'netcom3', cell, passKey)
scheme.activate()
else:
print('WRONG!')
WirelessConnection()
The problem is the "scheme.activiate" line... I'll get an error:
Traceback (most recent call last): File "/home/pi/Desktop/idk.py",
line 30, in WirelessConnection() File
"/home/pi/Desktop/idk.py", line 26, in WirelessConnection
scheme.activate() File
"/usr/local/lib/python3.5/dist-packages/wifi/scheme.py", line 174, in
activate subprocess.check_output(['/sbin/ifdown', self.interface],
stderr=subprocess.STDOUT) File "/usr/lib/python3.5/subprocess.py",
line 316, in check_output
**kwargs).stdout File "/usr/lib/python3.5/subprocess.py", line 398, in run output=stdout, stderr=stderr) subprocess.CalledProcessError:
Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1
I changed this line in scheme.py:
['/sbin/ifdown', 'wlan0']
to:
['/sbin/ifconfig', 'wlan0', 'down']
After this line I added a "sleep(30)".
I changed the interfaces-config to:
auto wlan0
iface wlan0 inet loopback
and lot of another thing... But I'm still getting this error. What is the reason? What can I do?
I had the same problem. It seems that u need to execute as super user.
I changed in the scheme.py this line:
subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
by this line
subprocess.check_output(['sudo','/sbin/ifconfig', self.interface,'up'], stderr=subprocess.STDOUT)
Hope it works for you
Related
I want to capture ping -h output using Python, it results in exit status 2.
I am working on a Linux host.
import subprocess
class Network_Ping ():
def Get_Ping_Help(self):
res = subprocess.check_output(['ping', '-h'], universal_newlines = True)
print (res)
def main():
obj = Network_Ping()
obj.Get_Ping_Help()
if __name__ == "__main__":
main()
This is the output
`Traceback (most recent call last):
File "Network_Ping.py", line 42, in <module>
main()
File "Network_Ping.py", line 35, in main
obj.Get_Ping_Help()
File "Network_Ping.py", line 20, in Get_Ping_Help
res = subprocess.check_output(['ping', '-h'], universal_newlines = True)
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 512, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['ping', '-h']' returned non-zero exit status 2.`
The command seems to execute normally on the shell. What is the cause of this error? How can I fix it?
Following Barmar solution
It is a normal behavior for ping, but the shell does not show it; Shell does not return exit status. We can see it by:
ping -h;echo $?
To avoid checking the exit status, we can replace subprocess.check_output() with subprocess.run()
and to capture the output successfully.
res = subprocess.run(['ping', '-h'],capture_output=True, text = True)
print(res.stderr)
I tried lot of different way but i can't figure out this problem..i am not expert in python can any one explain how can i solve this problem...plzzz
command = "netsh wlan show profile"
ssid = subprocess.check_output(command, shell=True)
ssid = ssid.decode("utf-8")
ssid_list = re.findall('(?:Profile\s*:\s)(.*)', ssid)
for ssid_name in ssid_list:
subprocess.check_output(["netsh","wlan","show","profile",ssid_name,"key=clear"])
and it gives error:
Traceback (most recent call last):
File "C:/Users/Prakash/Desktop/Hacking tool/Execute_sys_cmd_payload.py", line 18, in <module>
subprocess.check_output(["netsh","wlan","show","profile",ssid_name,"key=clear"])
File "C:\Users\Prakash\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "C:\Users\Prakash\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 512, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['netsh', 'wlan', 'show', 'profile', 'Prakash_WiFi\r', 'key=clear']' returned non-zero exit status 1.
Process finished with exit code 1
With check_output this exception will be raised whenever a command extis abnormally, as indicated by a non-zero return code.
A possible solution is to use subprocess.run instead. This will run the process and return a CompletedProcess instance, which has a returncode attribute that you can check;
import subprocess as sp
command = ["netsh","wlan","show",ssid_name,"key=clear"]
netsh = subprocess.run(command, shell=True, stdout=sp.PIPE)
if netsh.returncode != 0:
print(f'netsh error: {netsh.returncode}')
else:
# process netsh.stdout.
From reading this page, it seems that the command you should use is netsh wlan show (without profile).
I'm trying to do topic modeling with Gensim and Mallet (link).
When I locate the mallet_path and then try to assign it to gensim, I get the error
subprocess.CalledProcessError : returned non-zero exit status 1
And I get prompted to update Java (which I have done).
Any hints on how to solve it?
mallet_path = '/Users/username/mallet-2.0.8/bin/mallet'
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=20, id2word=id2word)
Traceback (most recent call last):
File "<pyshell#85>", line 1, in <module>
ldamallet = gensim.models.wrappers.LdaMallet(mallet_path, corpus=corpus, num_topics=20, id2word=id2word)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gensim/models/wrappers/ldamallet.py", line 132, in __init__
self.train(corpus)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gensim/models/wrappers/ldamallet.py", line 273, in train
self.convert_input(corpus, infer=False)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gensim/models/wrappers/ldamallet.py", line 262, in convert_input
check_output(args=cmd, shell=True)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gensim/utils.py", line 1918, in check_output
raise error
subprocess.CalledProcessError: Command '/Users/username/mallet-2.0.8/bin/mallet import-file --preserve-case --keep-sequence --remove-stopwords --token-regex "\S+" --input /var/folders/76/hdlh6w8d3nbb4m424wx3010w0000gn/T/adc98e_corpus.txt --output /var/folders/76/hdlh6w8d3nbb4m424wx3010w0000gn/T/adc98e_corpus.mallet' returned non-zero exit status 1.
In bin directory, open the mallet file with a text editor then increase the MEMORY limit. It worked for me.
Below is my code to try and query my ldap server. However, for some reason, I cannot seem to make the bind command work to progress in my code. I continue to get the following message and am not sure what it means or how to fix it. I apologize about the error message formatting. I tried my best to make it as readable as possible.
Any help would be greatly appreciated!
>>> from ldap3 import Server, Connection, SUBTREE
>>> server = Server('<server_name>')
>>> conn = Connection(server, user='<username>', password='<password>')
>>> conn.open()
>>> conn.bind()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.5/site-packages/ldap3/core/connection.py", line 427, in bind
response = self.post_send_single_response(self.send('bindRequest', request, controls))
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 122, in post_send_single_response
responses, result = self.get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 298, in get_response
responses = self._get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 168, in _get_response
dict_response = self.decode_response(ldap_resp)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 403, in decode_response
result = bind_response_to_dict(component)
File "/usr/lib/python3.5/site-packages/ldap3/operation/bind.py", line 119, in bind_response_to_dict
'saslCreds': bytes(response['serverSaslCreds']) if response['serverSaslCreds'] is not None else None}
File "/usr/lib/python3.5/site-packages/pyasn1/type/univ.py", line 984, in bytes
return bytes(self._value)
File "/usr/lib/python3.5/site-packages/pyasn1/type/base.py", line 164, in plug
raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name)
pyasn1.error.PyAsn1Error: Uninitialized ASN.1 value ("len" attribute looked up)
I am not a python guru I am just writing a code to check my api authentication and URL access status. I just want to assure that my api and domain url is accessible to users.
For the above reason I am writing a python script which can check and a cron can send an alert to me.
Here is my Code:
def check(argv):
# I'm going to use argpase.It makes
# command-line args a breeze.
parser = argparse.ArgumentParser()
parser.add_argument('-H', '--hostname', dest='hostname', required=True)
parser.add_argument('-a', '--auth_id', dest='authenticationid')
parser.add_argument('-t', '--auth_token', dest='authenticationtoken')
parser.add_argument('-r', '--dest_url', dest='dest_url',help="""Path to report relative to root, like /v1/ OR /""", required=True)
parser.add_argument("-q", "--quiet", action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = vars(parser.parse_args())
if args['authenticationid'] and args['authenticationtoken'] and not len(sys.argv) == 7:
authurl = urllib.request.Request('https://{%s}:{%s}#%s%s/%s/' %(args['authenticationid'],args['authenticationtoken'],args['hostname'], args['dest_url'],args['authenticationid']))
return (getAuthResponseCode(authurl))
else:
url = urllib.request.Request("https://%s%s" %(args['hostname'], args['dest_url']))
return(getResponseCode(url))
def getResponseCode(url):
try:
conn = urllib.request.urlopen(url,timeout=10)
code = conn.getcode()
return (status['OK'], code)
except timeout:
return (status['WARNING'], logging.error('socket timed out - URL %s', url))
except urllib.error.URLError as e:
return (status['CRITICAL'], e.reason)
else:
return (status['UNKNOWN'])
def getAuthResponseCode(authurl):
try:
authconn = urllib.request.urlopen(authurl, timeout=10)
authcode = authconn.getcode()
return (status['OK'], authcode)
except timeout:
return (status['WARNING'], logging.error('socket timed out - URL %s'))
except urllib.error.URLError as err:
return (status['CRITICAL'], err.reason)
else:
return (status['UNKNOWN'])
ERROR Message:
G:\Python>python check_http.py -H api.mydomain.com -r /API/Function/ -a 'MAMZMZZGVLMG
FMNTHIYTREETBESSS' -t 'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAwMmZm'
Traceback (most recent call last):
File "C:\Python33\lib\http\client.py", line 770, in _set_hostport
port = int(host[i+1:])
ValueError: invalid literal for int() with base 10: "{'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAw
MmZm'}#api.mydomain.com"
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "check_http.py", line 76, in <module>
print (check(sys.argv[1:]))
File "check_http.py", line 41, in check
return (getAuthResponseCode(authurl))
File "check_http.py", line 61, in getAuthResponseCode
authconn = urllib.request.urlopen(authurl, timeout=10)
File "C:\Python33\lib\urllib\request.py", line 156, in urlopen
return opener.open(url, data, timeout)
File "C:\Python33\lib\urllib\request.py", line 469, in open
response = self._open(req, data)
File "C:\Python33\lib\urllib\request.py", line 487, in _open
'_open', req)
File "C:\Python33\lib\urllib\request.py", line 447, in _call_chain
result = func(*args)
File "C:\Python33\lib\urllib\request.py", line 1283, in https_open
context=self._context, check_hostname=self._check_hostname)
File "C:\Python33\lib\urllib\request.py", line 1219, in do_open
h = http_class(host, timeout=req.timeout, **http_conn_args)
File "C:\Python33\lib\http\client.py", line 1172, in __init__
source_address)
File "C:\Python33\lib\http\client.py", line 749, in __init__
self._set_hostport(host, port)
File "C:\Python33\lib\http\client.py", line 775, in _set_hostport
raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])
http.client.InvalidURL: nonnumeric port: '{'DafniisfnsifnsifsbANBBDSDNBISDExODZlODAw
MmZm'}#api.mydomain.com'
I know this is not write my code forum but I am helpless and looking for some help.If some one can tell where exactly I went wrong so that I can fix it.
I am using python3.
You're passing ʹhttps://user:pass#whateverʹ as the url.
Python doesn't understand you're trying to authenticate, and thinks you're passing ʹhttps://domain:port...ʹ
To do basic auth with urllib, you need to use a urllib.request.HTTPBasicAuthHandler
Sorry I'm not posting links and/or example code, but I'm typing this on my phone, and it makes those a pain.