I want to exception of linux command - linux

I want to control on python
try catch wifi list and connect to catching wife name and password
but I use linux command so I can't care linux error window
I want to check password in python
when i set wrong password, open Network manager.
What should i do?
import commands
def space_filter(x):
if x == ' ':
pass
else:
return x
#fail, output = commands.getstatusoutput("nmcli dev wifi list")
test= commands.getoutput("nmcli dev wifi list")
test1=test.split(' ')
print test
print test1
test2 = []
test1 = list(filter(space_filter, test1))
#print test1
for x in range(len(test1)):
if test1[x] == '\n*' or test1[x] =='\n':
test2.append(test1[x+1])
#print test2
try:
result = commands.getoutput("nmcli d wifi connect " + test2[0] + " password 1234")
print result
except:
print "password is wrong"[enter image description here][1]

Exceptions are a language specific construct to catch abnormal/error situations. The correct way to check error conditions in shell commands is the return value.
Use the getstatusoutput function in commands module to catch the return value along with the output. In your case, you would need to parse the output along with the return code to get the reason for failure since nmcli only distinguishes between certain kinds of failure. - https://developer.gnome.org/NetworkManager/stable/nmcli.html
(status, output) = commands. getstatusoutput("nmcli d wifi connect " + test2[0] + " password 1234")
if not status:
print "error"

Related

Is it possible to interact with the subprocess 3 standards streams on windows?

I have a script that opens a subprocess, this process awaits multiple inputs.
I tried with subprocess.Popen() but when combining the 3 standards streams it gets stuck in deadlocks...
So I tired to use wexpect (Apparently Windows version of pexecpt) it also didn't worked.
Now I'm using Sarge and my code right now looks like this:
import os
import subprocess
import sarge
import sys
def get_env():
env = os.environ.copy()
return env
def interactive(list_command: list, instruction_dict: dict):
env = get_env()
std_out = ""
for a_number in instruction_dict:
capture_stdout = sarge.Capture(buffer_size=-1)
capture_stderr = sarge.Capture(buffer_size=-1)
child_proc = sarge.Command(list_command, stdout=capture_stdout, stderr=capture_stderr,
shell=True, env=env)
child_proc.run(input=subprocess.PIPE,
async_=True)
print(capture_stdout.readlines(timeout=1.0), capture_stderr.readlines(timeout=1.0))
if instruction_dict[a_number][0] is not None:
#if capture_stdout.expect(instruction_dict[a_number][0]) is not None or capture_stderr.expect(instruction_dict[a_number][0]) is not None:
# self.test_manager.log_event(msg="found line : " + instruction_dict[a_number][0] + "in PIPE", current_event_type=LogLevel.DEBUG, screen_only=False)
print("in exec line : ", child_proc.stdout.readline(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
else:
print("in exec line : ", child_proc.stdout.readlines(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
if instruction_dict[a_number][1] is not None:
print(f"sending \"{instruction_dict[a_number][1]}\" to process in interactive")
temp_bytes = str.encode((instruction_dict[a_number][1]+"\n"))
child_proc.stdin.write(temp_bytes)
try:
child_proc.stdin.flush() # blind flush
except:
pass
print("Last line : ", child_proc.stdout.readlines(timeout=1.0), child_proc.stderr.readlines(timeout=1.0))
child_proc.wait()
std_out += child_proc.stdout.read().decode('utf-8')
child_proc.kill() # kill the subprocess
print("output: ", std_out)
interactive(list_command=["process.exe", "-delete_datamodel", "MODELNAME"],instruction_dict={1 : (None, "y")})
Output looks like this:
[] []
in exec line : [] []
send "y" to process in interactive
Last line : [] [b'User root connected to DB MODELNAME\r\n']
output: Are you sure to delete DB MODELNAME? (y/n)\n\nDelete Data Model Ok\n
In console it looks like this:
C:\>process.exe -delete_data_model -db_name MODELNAME
Are you sure to delete DB MODELNAME ? (y/n)
y
User root connected to DB MODELNAME
Delete Data Model Ok
There are multiple problems:
I can't catch the first stdout "Are you sure to delete DB MODELNAME ? (y/n)" during the loop I only get [].
capture_stdout.expect crash but in fact it might be the same problem as the first one, if it can't read the first stdout.
lines are going in stderr instead of stdout (it might be because of the process, I don't know how to test this)
for another command I ll need to answer more than one interactive by looking of the question before answering them that way my instruction_dict will look like this
instruction_dict = {1 : ("Are you sure to recover the DB", "y"),
2 : ("Do you want to stop the service", "y"),
3 : ("Do you want to stop the DB", "y"),
4 : ("Do you want to drop and create the DB", "y")}
Is this even possible? I have search for a working exemple and didn't found one, I know I might be bad at searching but...
Sorry for the terrible syntax(and bad english), I want to know if there is a pure python solution (I have one solution working in tcl but I'm trying to get rid of it/ I didn't wrote the tcl code).

Last line of STDOUT is not getting printed if there's an STDIN after it

While trying to integrate sqlmap with my automation tool, when tried to run the command and save the output into a file, the line after which user's input is required is not getting printed on the console; It is getting printed after the arguments are passed. It is required that the console output to be printed on both the places (terminal and output file). As sqlmap requires the user's input during execution cannot use subprocess.check_output()
image
Code snippet:
[try:
cmd = cmd.rstrip()
process = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
while True:
out = process.stdout.readline()\[0:\]
if out == '' and process.poll() is not None:
break
if out:
output += out
print(out.strip())
except Exception as e:
exception_message = str(e)
output += exception_message
if 'exit status 1' not in exception_message:
self.utilities.print_color("\[!\] Error executing the command: " + cmd,'red')
output += '\r\n'
print(output)
return output][1]

Python code for telnetting DUT needs further optimization

I need to further optimize my code in Python.
I was earlier executing commands on the Device Under Test step by step which was a lot as I also required sleep timers. However I was able to minimize it through a list and calling elements of the list in a for loop:
I need your inputs to further optimize this code:
ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
tn.write(i.encode('ascii') + b"\n")
print (i, "command entered successfully")
time.sleep(2)
Please note: I am telnetting the DUT as ssh is not supported.
i am using this optimized common code for telnet. we can create a common file where you can add this method
import telnetlib
import time
def telnet(host):
user = <username>
password = <password>
try :
tn = telnetlib.Telnet(host)
except :
print("Unable to connect")
sys.exit()
tn.read_until(b"Username:") # read until username prompt
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:") #read until password prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#")
return tn #return telnetlib handle
than import this method to another file, where we write our script

How to access socket for multiple reception using thread

Hello I am new in networking field and using socket in Python
I am trying to access the function frame_reception_function() but I am getting error "OSError: [Errno 98] Address already in use"
In forward_send_received(), I am calling four different functions using thread, because in my work, this node can be received request frame form previous node and also need to forward this frame to next node and it is also receiving data frame form next node and send to the previous node. so it received two from two sides. How it is possible to access the same socket. I am also closing the connection but it does not work.
Can anybody help me to remove the above error (Address already in Used)
def frame_reception_function ():
print ("starting of frame reception")
PORT = 12345
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(('',PORT))
s.listen(1)
conn,address=s.accept()
message=conn.recv(1024).decode()
conn.close()
recv_message=message.split(';')
message_type=recv_message[0]
if (received_message=='req_status'):
print ('Received Message is req_status')
previous_ip=recv_message[1]
return message_type,previous_ip,recv_message
else:
print ("received message is :",received_message)
print ("Received from:",recv_message[4])
ip=recv_message[4]
#cmd = "arp -n " + str(ip) + " | awk '/" + str(ip) + "/{print $3}'" # Can we extract MAC address from IP instead of Broadcast address???
#x = os.popen(cmd).read().strip()
return recv_message[0],ip,recv_message
def forward_send_received():
Frame_type,ip_address,received_message=frame_reception_function ()
print ("after while")
print (Frame_type)
print (Frame_SrcAddr)
print (ip_address)
print (received_message)
if (Frame_type=="req_status"):
if (not Req_Frame_Relayed): # Check Req_Frame_status
forward_req_status_frame()
Req_Frame_Relayed=True
Probabilistic_Reliable_Broadcast(Frame_type)
Send_Data_status_frame()
Probabilistic_Reliable_Broadcast("current_node_data")
else:
if (Frame_SrcAddr not in Resp_forwarded_set):
Resp_forwarded_set()
forward_Data_status_frame(received_message)
Resp_number=Resp_number+1
Probabilistic_Reliable_Broadcast(Frame_type)
while (time.time()-start_time<Status_collecting_time_interval) and (Resp_number<Nmax):
print ("starting of while ")
Thread(target=forward_send_received).start()

Get the output of fabric.local or run or sudo when the command fails with error

I'm using fabric to run linux commands for the purpose of networking api
I would like to get the output of the commands when they FAIL with an error!
When I do
from fabric.api import local, env
result = local("command", capture = True)
If the command succeed I get the output
but If there was an error I get an exception.
when I add a fallback like this:
result = local("command || echo 'Failed'", capture = True)
I get 'Failed'
I would like to get the exact Error as given by shell command.
If I do:
env.warning_only = True
result = local("command")
I can let the program continue to work and I see the "Error" descriptions as warnings on the terminal when I send a request that will fail
but I want to get these "Error" descriptions on my program to return them to client.
with this code:
env.warning_only = True
result = local("command")
I can only get result.return_code which can be 0 (success) or 1 or 2
when I add capture=True to the last code I don't get return_code and I get the
output only if command succeed
Example: I have bridge "br-vxlan55" and a vxlan vxlan55, I added the vxlan to the bridge, after that if the user wants to add the same vxlan to the same bridge, the Error should be returned in the request response as it was shown on the terminal:
local("sudo brctl addif br-vxlan55 vxlan55")
local("sudo brctl addif br-vxlan55 vxlan55")#AGAIN
Terminal output:
device vxlan55 is already a member of a bridge; can't enslave it to bridge br-vxlan55.
Warning: local() encountered an error (return code 1) while executing 'sudo brctl addif br-vxlan55 vxlan55'
And I get 1 as retun_code
I want to get "device vxlan55 is already a member of a bridge; can't enslave it to bridge br-vxlan55." on my program as an output of local. Is that possible ?
This is only an example, I have so many other commands which may fail, and I want to get the errors descriptions to return them as request response.
I found the solution, it is with "stderr" I didn't know about it
from fabric.api import local, env
env.warn_only = True # if you want to ignore exceptions and handle them yurself
command = "your command"
x = local(command, capture=True)
if(x.stderr != ""):
error = "On %s: %s" %(command, x.stderr)
print x.return_code # which may be 1 or 2
print error
raise Exception(error) #optional
else:
print "the output of %s is: %s" %(command, x)
print x.return_code # which is 0

Resources