How get ESSID and Access Point when I write iwconfig - linux

I write iwconfig so I can have he name of my lan ESSID and mac of point acess ,I want to recover his two fields for using in a script I can be on the first line, but I can not have the information that I want.
how to ubuntu I vaoir that valeus ESSID and Access Point
wlan0 IEEE 802.11bgn ESSID:"Home"
Mode:Managed Frequency:2.437 GHz Access Point: 00:03:B6:K9:L1:9E
I need help. thanks.
try:
proc = Popen(['iwconfig'], stdout=PIPE, stderr=DN)
print "try de iwconfig %s"%proc
except OSError:
sys.exit("Could not execute iwconfig")
for line in proc.communicate()[0].split('\n'): print "line %s"%line if len(line) == 0:
continue # Isn't an empty string
if line[0] != ' ':
if 'IEEE 802.11' in line:
if "ESSID:\"" in line:
print line[ESSID][0]
if "Access Point:\"" in line:
print line[Access Point][0]

For my output of iwconfig, a regex like this seems to work perfectly fine:
from re import *
from subprocess import *
proc = Popen(['iwconfig'], stdout=PIPE)
intext=str(proc.communicate()[0])
m1=search('Access Point: [ABCDEF0123456789:]*',intext)
AP=m1.group(0).split(' ')[2]
print AP
m2=search('ESSID:".*" ',intext)
ESSID=m2.group(0).split('"')[1]
print ESSID

Related

python3 pexpect spawn object line reference gets skipped

Python version: 3.8.0
pexpect Version: 4.8.0
def runCmd( self, cmd, thisTimeout = None ):
output = ""
if not thisTimeout:
thisTimeout = self.conn.timeout
try:
print("debug: %s" % cmd)
self.conn.sendline(cmd)
print( "before: %s " % self.conn.before.decode() )
index = self.conn.expect( self.expList, timeout = thisTimeout )
output += self.conn.before.decode()
print( "after: %s " % self.conn.after.decode() )
print( "before after: %s" % self.conn.before.decode() )
except Exception as e:
#expect exception thrown
print( "Error running command %s" % cmd )
print( e )
output = "Error: %s" % str(self.conn)
print("yo man %s" % self.conn.before.decode() )
output = output.replace(cmd, "").strip()
print("this has to print %s " % output)
return output
This function executes the cmd through the pexpect interface and returns the output.
Version of Python/pxpect that worked:
Python version: 3.6.9
pexpect version: 4.2.1
After an update of the python script to run on Python 3.8.0/pexpect 4.8.0, the first command sent to pexpect sometimes returns empty output. The reason is when the variable self.conn.before.decode() gets referenced, the python code does not get executed or ineffective.
An example output from described situation:
debug: cat /etc/hostname
before:
after: ubuntu#ip-172-31-1-219:~$
this has to print
An expected behavior:
debug: cat /etc/hostname
after: ubuntu#ip-172-31-1-219:~$
before after: cat /etc/hostname
ip-172-31-1-219
yo man cat /etc/hostname
ip-172-31-1-219
this has to print ip-172-31-1-219
But this time, the line before: gets skipped.
What is going on here?!
Downgrade is not possible as async(pexpect(<=4.2.1) used async as function/variable signature) becomes a keyword.
Update:
The lines are getting executed but it's printing out after I print it as byte string.
before after: b' \r\x1b[K\x1b]0;ubuntu#ip-172-31-1-219: ~\x07'
Where the correct one is printing out
before after: b' cat /etc/hostname\r\nip-172-31-1-219
\r\n\x1b]0;ubuntu#ip-172-31-1-219: ~\x07'
The reason the before and before after lines get skipped is that they contain the carriage return character \r and the escape sequence \x1b[K.
The carriage return is used to move the cursor to the start of the line. If there are characters after it in the string to be written, they get printed from the position of the cursor onward replacing existing printed characters.
The ANSI Control sequence \x1b[K erases the line from the position of the cursor to the end of the line. This clears the already printed strings in your particular case.

From SSH not decoded from bytes to ASCII?

Good afternoon.
I get the example below from SSH:
b"rxmop:moty=rxotg;\x1b[61C\r\nRADIO X-CEIVER ADMINISTRATION\x1b[50C\r\nMANAGED OBJECT DATA\x1b[60C\r\n\x1b[79C\r\nMO\x1b[9;19HRSITE\x1b[9;55HCOMB FHOP MODEL\x1b[8C\r\nRXOTG-58\x1b[10;19H54045_1800\x1b[10;55HHYB"
I process ssh.recv (99999) .decode ('ASCII')
but some characters are not decoded for example:
\x1b[61C
\x1b[50C
\x1b[9;55H
\x1b[9;19H
The article below explains that these are ANSI escape codes that appear since I use invoke_shell. Previously everything worked until it moved to another server.
Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
When I write to the file, I also get:
rxmop:moty=rxotg;[61C
RADIO X-CEIVER ADMINISTRATION[50C
MANAGED OBJECT DATA[60C
[79C
MO[9;19HRSITE[9;55HCOMB FHOP MODEL[8C
RXOTG-58[10;19H54045_1800[10;55HHYB
If you use PuTTY everything is clear and beautiful.
I can't get away from invoke_shell because the connection is being thrown from one server to another.
Sample code below:
# coding:ascii
import paramiko
port = 22
data = ""
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=secret, port=port, timeout=10)
ssh = client.invoke_shell()
ssh.send("rxmop:moty=rxotg;\n")
while data.find("<") == -1:
time.sleep(0.1)
data += ssh.recv(99999).decode('ascii')
ssh.close()
client.close()
f = open('text.txt', 'w')
f.write(data)
f.close()
The normal output is below:
MO RSITE COMB FHOP MODEL
RXOTG-58 54045_1800 HYB BB G12
SWVERREPL SWVERDLD SWVERACT TMODE
B1314R081D TDM
CONFMD CONFACT TRACO ABISALLOC CLUSTERID SCGR
NODEL 4 POOL FLEXIBLE
DAMRCR CLTGINST CCCHCMD SWVERCHG
NORMAL UNLOCKED
PTA JBSDL PAL JBPTA
TGFID SIGDEL BSSWANTED PACKALG
H'0001-19B3 NORMAL
What can you recommend in order to return normal output, so that all characters are processed?
Regular expressions do not help, since the structure of the record is shifted, then characters from certain positions are selected in the code.
PS try to use ssh.invoke_shell (term='xterm') don't work.
There is an answer here:
How can I remove the ANSI escape sequences from a string in python
There are other ways...
https://unix.stackexchange.com/questions/14684/removing-control-chars-including-console-codes-colours-from-script-output
Essentially, you are 'screen-scraping' input, and you need to strip the ANSI codes. So, grab the input, and then strip the codes.
import re
... (your ssh connection here)
data = ""
while data.find("<") == -1:
time.sleep(0.1)
chunk = ssh.recv(99999)
data += chunk
... (your ssh connection cleanup here)
ansi_escape = re.compile(r'\x1B(?:[#-Z\\-_]|\[[0-?]*[ -/]*[#-~])')
data = ansi_escape.sub('', data)

I want to exception of linux command

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"

split() on one character OR another

Python 3.6.0
I have a program that parses output from Cisco switches and routers.
I get to a point in the program where I am returning output from the 'sh ip int brief'
command.
I place it in a list so I can split on the '>' character and extract the hostname.
It works perfectly. Pertinent code snippet:
ssh_channel.send("show ip int brief | exc down" + "\n")
# ssh_channel.send("show ip int brief" + "\n")
time.sleep(0.6)
outp = ssh_channel.recv(5000)
mystring = outp.decode("utf-8")
ipbrieflist = mystring.splitlines()
hostnamelist = ipbrieflist[1].split('>')
hostname = hostnamelist[0]
If the router is in 'enable' mode the command prompt has a '#' character after the hostname.
If I change my program to split on the '#' character:
hostnamelist = ipbrieflist[1].split('#')
it still works perfectly.
I need for the program to handle if the output has the '>' character OR the '#' character in 'ipbrieflist'.
I have found several valid references for how to handle this. Ex:
import re
text = 'The quick brown\nfox jumps*over the lazy dog.'
print(re.split('; |, |\*|\n',text))
The above code works perfectly.
However, when I modify my code as follows:
hostnamelist = ipbrieflist[1].split('> |#')
It does not work. By 'does not work' I mean it does not split on either character. No splitting at all.
The following debug is from PyCharm:
ipbrieflist = mystring.splitlines() ipbrieflist={list}: ['terminal length 0', 'rtr-1841>show ip int brief | exc down', 'Interface'] IP-Address OK? Method Status Protocol', 'FastEthernet0/1 192.168.1.204 YES NVRAM up up ', 'Loopback0 172.17.0.1 YES NVRAM up up ', '', 'rtr-1841>']
hostnamelist = ipbrieflist[1].split('> |#') hostnamelist={list}: ['rtr-1841>show ip int brief | exc down']
hostname = {str}'rtr-1841>show ip int brief | exc down'
As you can see the hostname variable still contains the 'show ip int brief | exc down' appended to it.
I get the same exact behavior if the hostname is followed by the '#' character.
What am I doing wrong?
Thanks.
Instead of this:
ipbrieflist[1].split('> |#')
You want this:
re.split('>|#', ipbrieflist[1])

Indicate no more input without closing pty

When controlling a process using a PTY master/slave pair, I would like to indicate to the process in question that stdin has closed and I have no more content to send, but I would still like to receive output from the process.
The catch is that I only have one file descriptor (the PTY "master") which handles both input from the child process and output to the child process. So closing the descriptor would close both.
Example in python:
import subprocess, pty, os
master,slave = pty.openpty()
proc = subprocess.Popen(["/bin/cat"], stdin=slave, stdout=slave)
os.close(slave) # now belongs to child process
os.write(master,"foo")
magic_close_fn(master) # <--- THIS is what I want
while True:
out = os.read(master,4096)
if out:
print out
else:
break
proc.wait()
You need to get separate read and write file descriptors. The simple way to do that is with a pipe and a PTY. So now your code would look like this:
import subprocess, pty, os
master, slave = pty.openpty()
child_stdin, parent_stdin = os.pipe()
proc = subprocess.Popen(["/bin/cat"], stdin=child_stdin, stdout=slave)
os.close(child_stdin) # now belongs to child process
os.close(slave)
os.write(parent_stdin,"foo") #Write to the write end (our end) of the child's stdin
#Here's the "magic" close function
os.close(parent_stdin)
while True:
out = os.read(master,4096)
if out:
print out
else:
break
proc.wait()
I had to do this today, ended up here and was sad to see no answer. I achieved this using a pair of ptys rather than a single pty.
stdin_master, stdin_slave = os.openpty()
stdout_master, stdout_slave = os.openpty()
def child_setup():
os.close(stdin_master) # only the parent needs this
os.close(stdout_master) # only the parent needs this
with subprocess.Popen(cmd,
start_new_session=True,
stderr=subprocess.PIPE,
stdin=stdin_slave,
stdout=stdout_slave,
preexec_fn=child_setup) as proc:
os.close(stdin_slave) # only the child needs this
os.close(stdout_slave) # only the child needs this
stdin_pty = io.FileIO(stdin_master, "w")
stdout_pty = io.FileIO(stdout_master, "r")
stdin_pty.write(b"here is your input\r")
stdin_pty.close() # no more input (EOF)
output = b""
while True:
try:
output += stdout_pty.read(1)
except OSError:
# EOF
break
stdout_pty.close()
I think that what you want is to send the CTRL-D (EOT - End Of Transmission) caracter, isn't you? This will close the input in some applications, but others will quit.
perl -e 'print qq,\cD,'
or purely shell:
echo -e '\x04' | nc localhost 8080
Both are just examples. BTW the CTRL-D caracter is \x04 in hexa.

Resources