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).
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 am running a PYSTRAY icon which starts a console program. When I try stopping it with this code
def stop_rtd():
print("Stopping RTD")
sys.exit()
icon.stop()
The system throws back this error
An error occurred when calling message handler
Traceback (most recent call last):
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_win32.py", line 389, in _dispatcher
uMsg, lambda w, l: 0)(wParam, lParam) or 0)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_win32.py", line 209, in _on_notify
descriptors[index - 1](self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 267, in inner
callback(self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 368, in __call__
return self._action(icon, self)
File "C:\Users\ramac\AppData\Local\Programs\Python\Python37\lib\site-packages\pystray\_base.py", line 463, in wrapper0
return action()
File "C:/Tej/GitHub/Python/YahooDLs/try_systray.py", line 16, in stop_rtd
sys.exit()
SystemExit
RTD is the console program which is perpetual. It stops but the icon continues and console does not close. On closing the console the program exits and the icon is closed.
I am running this on Windows10
Please help me solve this problem.
I found an alternative way to exit the program. The os module also has a exit function called _exit. It takes one argument that is the exit code/status code. Usually it should be 0. So your function will look like this:
import os
def stop_rtd():
icon.stop()
os._exit(0)
Also note that you have to stop icon before exit the program.
I have created tf.data.Dataset pipeline variable to which I pass a python function which is trying to run sox command through python's subprocess module. The code is running fine on cpu with windows os but is not able to run on Google Colab's GPU which has linux os. Here is the code -
from scipy.io import wavfile
import tensorflow as tf
def tf_func(inp_sample):
def func(inp_sample,<tf.string object>):
try:
fdesc, infile = tempfile.mkstemp(suffix=".wav")
os.close(fdesc)
fdesc, outfile = tempfile.mkstemp(suffix=".wav")
os.close(fdesc)
wavfile.write(infile,<sample rate>,inp_sample.numpy()) //writes audio file to disk
arguments = ['sox',infile,outfile,'-q','compand',
*DRC_PRESET[<tf.string object>.numpy().decode('utf-8')]]
subprocess.check_call(arguments)
finally:
os.unlink(infile)
os.unlink(outfile)
return tf.convert_to_tensor(inp_sample,dtype=tf.float32)
drc = np.random.choice(<lis of string>)
[inp_sample,] = tf.py_function(dynamic_compression,
[inp_sample,tf.constant(drc)],[tf.float32])
inp_sample.set_shape(target_sample_size) //target_size=<some int>
return inp_sample
...
inp=tf.data.Dataset.from_tensor_slices(inp) // inp shape eg: (4, 500)
inp = inp.map(tf_dynamic_compression)
for i in inp:
print(i.numpy())
And the error it throws -
UnknownError: 2 root error(s) found.
(0) Unknown: CalledProcessError: Command 'None' died with <Signals.SIGINT: 2>.
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/script_ops.py", line 233, in __call__
return func(device, token, args)
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/script_ops.py", line 122, in __call__
ret = self._func(*args)
File "/tmp/tmpn_9q_jxm.py", line 24, in dynamic_compression
ag__.converted_call(subprocess.check_call, dynamic_compression_scope.callopts, (arguments,), None, dynamic_compression_scope)
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/autograph/impl/api.py", line 541, in converted_call
result = converted_f(*effective_args)
File "/tmp/tmpozf4qyav.py", line 50, in tf__check_call
ag__.if_stmt(cond_1, if_true_1, if_false_1, get_state_1, set_state_1, (), ())
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/autograph/operators/control_flow.py", line 895, in if_stmt
return _py_if_stmt(cond, body, orelse)
File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/autograph/operators/control_flow.py", line 1004, in _py_if_stmt
return body() if cond else orelse()
File "/tmp/tmpozf4qyav.py", line 44, in if_true_1
raise ag__.converted_call(CalledProcessError, check_call_scope.callopts, (retcode, cmd), None, check_call_scope)
How to solve this problem?
The problem was coming due to sox not getting executed by subprocess module. It has been answered earlier. There are two solutions -
First change the arguments line
arguments = " ".join(['sox',infile,outfile,'-q','compand',*DRC_PRESET[<tf.string object>.numpy().decode('utf-8')]])
and then
os.system(arguments)
OR
subprocess.check_call(arguments, shell=True)
For me the second worked.
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.
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