Need to get mac address tables from d-link switches with python - pysnmp

Probably I should use SNMP v2c and pysnmp, but can't figure out how can I do that clearly, probably I need a list of port to mac array dictionaries.
Anyways I am going to push that into mongodb and then get the port number having the mac address.
Here is the shell command that gives that information
snmpwalk -O0sUX -v2c -Cc -c public 10.77.10.8 BRIDGE-MIB::dot1dTpFdbPort
update: https://github.com/edikmkoyan/portmatrix/blob/master/portmatrix.py

I'd suggest starting from a script like this. It's not debugged, so if you get it fixed to a fully working condition - please comment and I'd update the code to benefit others.
from pysnmp.hlapi import *
for (errorIndication,
errorStatus,
errorIndex,
varBindTable) in bulkCmd(SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('demo.snmplabs.com', 161)),
ContextData(),
0, 25,
ObjectType(ObjectIdentity('BRIDGE-MIB', 'dot1dTpFdbPort')),
lexicographicMode=False):
if errorIndication:
Exception(errorIndication)
elif errorStatus:
Exception(errorStatus)
else:
for varBinds in varBindTable:
for varBind in varBinds:
# imaginary MongoDB document mapping port-ID -> MAC
db.portsAndMacs.insert_one(
{varBind[1].prettyPrint(): varBind[0].prettyPrint()[-17:]}
)

Related

pySerial running command to list ports

I am using pySerial and I am running this command using CMD to list available COM ports and displays a COM port number when found:
python -m serial.tools.list_ports
I know that the command line will import the serial module when I use the python -m flag and I can access the objects inside it so it should show the output. However, the same command however does not work when run using the IDLE shell:
import serial
print(serial.tools.list_ports_common)
This returns an error AttributeError: module 'serial' has no attribute 'tools'
Why is it not working at IDLE?
You need to import it first:
from serial.tools import list_ports
list_ports.main() # Same result as python -m serial.tools.list_ports
You can check out the source here
You can simply try connecting to each possible port (COM0...COM255). Then add the ports with successful connections to a list. Here is my example:
import serial
def connectedCOMports ():
allPorts = [] #list of all possible COM ports
for i in range(256):
allPorts.append("COM" + str(i))
ports = [] #a list of COM ports with devices connected
for port in allPorts:
try:
s = serial.Serial(port) #attempt to connect to the device
s.close()
ports.append(port) #if it can connect, add it the the list
except:
pass #if it can't connect, don't add it to the list
return(ports)
print(connectedCOMports())
When I ran this program, it printed ['COM7'] to the console. This represents the ESP32 microcontroller that I connected to my USB port.

Program and Run PIC18 with pickit4 on linux

I am on linux ubuntu and target is a PIC18F47J53.
I basically want to program the chip and then let it run, using command lines and using pickit4.
using ipecmd (from mplab x ide v5.45), this is my command:
/opt/microchip/mplabx/v5.45/sys/java/zulu8.40.0.25-ca-fx-jre8.0.222-linux_x64/bin/java -jar /opt/microchip/mplabx/v5.45/mplab_platform/mplab_ipe/ipecmd.jar -TPPK4 /P18F47J53 -M -F"/path_to_myfile.hex" -W
This is my output
DFP Version Used : PIC18F-J_DFP,1.4.41,Microchip
*****************************************************
Connecting to MPLAB PICkit 4...
Currently loaded versions:
Application version............00.06.66
Boot version...................01.00.00
Script version.................00.04.17
Script build number............db473af2f4
Tool pack version .............1.6.961
PICkit 4 is supplying power to the target (3.25 volts).
Target device PIC18F47J53 found.
Device Revision Id = 0x1
*****************************************************
Calculating memory ranges for operation...
Erasing...
The following memory area(s) will be programmed:
program memory: start address = 0x0, end address = 0x3ff
program memory: start address = 0x1fc00, end address = 0x1fff7
configuration memory
Programming/Verify complete
Program Report
30-Jan-2021, 12:54:41
Device Type:PIC18F47J53
Program Succeeded.
Operation Succeeded
All good, and takes about 12 seconds, however, after that the pickit4 turns off the power target, and the pickit LED is BLUE (I guess state "ready")
The main question is how can I let the pickit4 powering the boards? any specific parameter? (I cannot find on the readme.html)
If I use MPLAB X IPE GUI to program, the programming is much quicker (3 or 4 seconds), the pickit LED is YELLOW and the target is left powered on. (I selected "release from reset")
I have tried to get the log out with as many details as possible, but I cannot see the commands sent to the pickit4.
Any idea? thanks
I realize that it's been a while since you asked, but i put the answer here for anyone who needs it. Add -OL to your command line options.

Determining operating system of the host using python-nmap

Until Python 3.4 you were able to determine target's operating system with
Python as follows:
import nmap
nm = nmap.PortScanner()
scanner = nm.scan(IP, port, arguments='-O')
print(scanner['scan'][IP]['osmatch'])
I'm using Python 3.6 and osmatch returns nothing.
Is there a way how to go about this ?
I've tested your script with Python 3.7.6:
import nmap
nm = nmap.PortScanner()
scanner = nm.scan(IP, port, arguments='-O')
print(scanner['scan'][IP]['osmatch'])
and it works well. The problem you have is that, for some reasons, the scan didn't retrieve any result, and the result object is empty, but if you try again on a different host it should work.

Fail2ban: get mac addresses no ip

Is it possible to detect with a fail2ban regex, a MAC address ?
What I can do: Detect the source ip address
From the log file
Jan 18 11:15:14 server kernel: [DROP]IN=eth0 OUT= MAC=00:00:00:00:00:00:00:00:00:00:00:00:00:00 SRC=1.2.3.4 DST=4.5.6.7 LEN=40 TOS=0x00 PREC=0x00 TTL=239
Fail2ban failregex
failregex = \[DROP\]IN=.* OUT= MAC=.* SRC=<HOST>*
Give 1.2.3.4 as a result. Then, any fail2ban action can use the <ip> variable.
What I would like to do: Detect the MAC address
Is it possible to do something like that?
failregex = \[DROP\]IN=.* OUT= MAC=<MAC> *
Shoud give 00:00:00:00:00:00:00:00:00:00:00:00:00:00 as a result. Then, any fail2ban action could use a<mac> variable for exemple.
Is someone have an answer, or any documentation? I didn't find informations about fail2ban regex or detection possibilities.
Not sure how to do it on Fail2Ban config and I don't have one to test right now. I did a little bash script to test this and maybe you can extract from here the regex.
#!/bin/bash
str="Jan 18 11:15:14 server kernel: [DROP]IN=eth0 OUT= MAC=00:00:00:00:00:00:00:00:00:00:00:00:00:00 SRC=1.2.3.4 DST=4.5.6.7 LEN=40 TOS=0x00 PREC=0x00 TTL=239"
[[ ${str} =~ \[DROP\].*MAC=([0-9:]+) ]] && test_output="${BASH_REMATCH[1]}"
echo $test_output
It gives as output: 00:00:00:00:00:00:00:00:00:00:00:00:00:00
I'm capturing the mac inside a group (between parenthesis) and asigning it to a var. Maybe could be like your <MAC>.
I can't assure this because as I said, I don't have fail2ban right now to test, so is a "wild thing"... but I can venture to suggest something like this:
failregex = \[DROP\].*MAC=<MAC>
I hope it helps.
From fail2ban manual website:
As a convenience, you can use the predefined entity in your regexes. is an alias for (?:::f{4,6}:)?(?P\S+), which matches either a hostname or an IPv4 address (possibly embedded in an IPv6 address).
I understand that it is possible use custom regex, but how? There isn't lot of articles about that..

DBD::Informix connection issues

I'm having somewhat weird problem with DBD::Informix. If I run a simple script like that:
use DBI;
my $dbh = DBI->connect_cached('dbi:Informix:database', '', '');
my $sth = $dbh->prepare('select foo from bar');
...
It works all right. But if I try to do exactly the same from a test script it fails with the following message:
SQL: -25588: The appl process cannot connect to the database server cms_ol.
ISAM: 22: Invalid argument
The only difference I see is that test script is quite heavy on module usage; it is based on Test::More and loads a lot of submodules that are to be tested.
Turning on DBI trace does not provide anything useful (for me, at least). Simple script runs along just fine:
DBI 1.616-nothread default trace level set to 0x0/1 (pid 9685 pi 0) at test_ifx.pl line 6
Note: perl is running without the recommended perl -w option
-> DBI->connect(dbi:Informix:cms#cms_ol, , ****, HASH(0x13fad0))
-> DBI->install_driver(Informix) for solaris perl=5.008009 pid=9685 ruid=106 euid=106
install_driver: DBD::Informix version 2011.0612 loaded from /cms/webdash/lib/arch/DBD/Informix.pm
<- install_driver= DBI::dr=HASH(0x1c8070)
!! warn: 0 CLEARED by call to connect method
-->> DBD::Informix::dbd_ix_db_connect()
CONNECT TO 'cms#cms_ol' - no user info
-->> DBD::Informix::dbd_ix_db_check_for_autocommit()
... and the only difference in trace of the problematic script I see is that it just fails:
DBI 1.616-nothread default trace level set to 0x0/1 (pid 9687 pi 0) at 22_report.t line 5 via 22_report.t line 6
Note: perl is running without the recommended perl -w option
-> DBI->connect_cached(dbi:Informix:cms, , ****)
-> DBI->install_driver(Informix) for solaris perl=5.008009 pid=9687 ruid=106 euid=106
install_driver: DBD::Informix version 2011.0612 loaded from /cms/webdash/lib/arch/DBD/Informix.pm
<- install_driver= DBI::dr=HASH(0xb619bc)
!! warn: 0 CLEARED by call to connect_cached method
-->> DBD::Informix::dbd_ix_db_connect()
CONNECT TO 'cms' - no user info
***ERROR***
SQL: -25588: The appl process cannot connect to the database server cms_ol.
ISAM: 22: Invalid argument
<<-- dbd_ix_db_connect (**ERROR-1**)
<<-- DBD::Informix::dbd_ix_db_connect()
I'm running custom Perl 5.8.9 build in Solaris 9, with latest DBI and DBD::Informix versions, against Informix IDS 9.40UC.
Update: If I try to be a smartass and put a block like that at the top of the heavy test script:
use DBI;
BEGIN { my $dbh = DBI->connect_cached( ... ); print "Connected!\n" if $dbh; }
... it prints like this:
Connected!
Out of memory!
Callback called exit.
END failed--call queue aborted at t/22_report.t line 20.
Callback called exit at t/22_report.t line 20.
BEGIN failed--compilation aborted at t/22_report.t line 24.
My guess is that DBD::Informix conflicts with some of the modules loaded after the connection is made. But which one? That's the question...
Another update: It appears that the above trick does something unwieldy. I tried to load all the modules explicitly by replacing 'use Module' with 'require Module; Module->import'. Pure Perl modules are OK but whenever XS module using XSLoader appears, Perl goes boom with friendly 'Out of memory' message. And if I move Informix connection below module initialization, it works all right - except DBD::Informix fails with the same -25588 error. Boomer. I'm at loss. :(
Another another update: I tried to run the same script with standard Perl 5.6.1 shipped with Solaris 9, using DBI 1.601 (the latest that would compile with Perl 5.6) and DBD::Informix 2011.0612. Same thing, so it's not custom Perl giving me trouble.
I can also add that the test module in question was prototyped using DBD::SQLite and fully works. It is the final test with DBD::Informix that is failing... As usual. :/
Workaround: following e-mail discussion with Jonathan, a workaround was found: addition of streams-based 'onipcstr' connection to Informix server allowed DBD::Informix to connect. Apparently, some XS modules interfere with default shmem-based connection method, although the culprit is unknown at the moment.
Further discussion
Custom-built Perl is, in my experience, easier than the system Perl. I never modify the system's Perl installation (I don't want to break it) so I always build my own.
You appear to have:
Solaris 9 (SPARC?)
Perl 5.8.9
DBI 1.616
DBD::Informix 2011.0612
ESQL/C (CSDK) 2.81
Informix Dynamic Server 9.40
We don't have the detailed sub-version of ESQL/C and IDS (2.81.UC2, 9.40.UC5, or whatever). There's a hint that you are using a 32-bit version of IDS, so probably everything is 32-bit. You are probably aware that 9.40 is no longer supported by IBM (and, indeed, its successor version 10.00 is also out of support). However, superficially, none of that should matter very much. The failing t91lvarchar.t is not a big issue.
Can you run the connect in working and non-working modes with DBI_TRACE=9 set in the environment.
If the trace for the connect operation is too voluminous to go into an update to the question, we'd better take this off-line to the DBD::Informix support channels (that's me, but by email).
The 'ISAM' error of 22 (Invalid argument) is puzzling. I'm curious about what is in your sqlhosts file for this server - the entry for cms_ol specifically. I'm not sure it will reveal anything, not least because you say the sample ESQL/C below (in the 'First hypothesis' section) works OK, and sometimes the Perl connects and sometimes it does not.
I wonder if there is a name conflict somewhere between functions in the shared libraries? That sort of thing will be hell to track.
First hypothesis
Further information received shows that this was not the crucial distinction.
The difference appears to be:
Works: CONNECT TO 'cms#cms_ol' - no user info
Fails: CONNECT TO 'cms' - no user info
The tricky part to explain is why the second fails, especially as the error goes on to mention cms_ol.
The workaround is to specify the server name in the connect string:
DBI->connect(dbi:Informix:cms#cms_ol, , ****, HASH(0x13fad0))
DBI->connect_cached(dbi:Informix:cms, , ****)
The underlying problem is more likely at the ESQL/C level than anything to do with other Perl modules. That is, if you compiled and executed this ESQL/C program, it would fail on cms and work on cms#cms_ol:
int main(int argc, char **argv)
{
$ char *dbs = "cms";
if (argc > 1)
dbs = argv[1];
$ whenever error stop;
$ connect to :dbs;
return 0;
}
You could run it without an explicit database name (or with an explicit 'cms'), and I would expect it to fail. You could run it with 'cms#cms_ol' and I would expect it to pass. The program will say nothing if it passes; it will be obvious when it fails (though the messages will not be beautiful).
There is an outside chance it is something to do with connect_cached; that is a service provided by the DBI module and not by the DBD::Informix module. On the whole though, it is more likely something happening at the ESQL/C level.