Posts Tagged ‘class’

How to check if network ethernet cards are active on Linux server / detect the physical connected state of a network cable / connector?

Tuesday, November 1st, 2022

linux-check-connectivity-interface-software-implementation-of-multi-queue-support-in-Linux-using-commodity-Ethernet-NICs

Lets say you are administrating some Linux server and need to upgrade a switch and temporary move out traffic for ethernet interfaces connected via a Gigabit network to a Gigabit Cisco / Junper EX Series / HPE Aruba or Arista Platform network switch to a newer version of a switch or software.

Usually if you don't have control over the Network switch (if you're employeed in a large corporation), that migration will be handled by a colleague from the Network team in a prescheduled time slot and usually in a coordinated meeting, once the cabling is being physically moved by someone a person in the Computer Room (in DC) in the respective data center.

Then once the correct commands are executed on the network switch to remap the new cable to point to the right location on the Linux server, where the old switch was and the setup has to be double verified by the network team mate.

Once this is done either by a colleague or if you're in a smaller company and you work as one man army sysadmin and you have done it yourself.
Next step is to verify that the Ethernet LAN cards on the Linux server lets say 6 or 8 LAN cards are still connected and active to the preset Active LAN / VLANs.

On Linux this is pretty simple and there is many ways to do it with external tools like ethtool, if you're lucky and your server doesn't have to have a paranoid security rules to follow or have to be a minimilastic machine with a 100% PCI High security standards compliancy.

To check connectivity for all your ethernet interfaces you can simply run a one liner shell script like so:

[root@linux-server ~]# for i in $(ip a s|grep -i :|grep -v link|awk '{ print $2 }'|sed -e 's#:##g'|grep -v lo); do ethtool $i; done
Settings for eth0:
        Link detected: yes
Settings for eth1:
        Link detected: yes
Settings for eth2:
        Link detected: yes

So far so good but what if your RHEL / CentOS / Debian server doesn't have ethtool installed and you're not allowed to install it then how can you check whether network cable connector is indicating a network activity to the connected Ethernet LAN cards?

[root@linux-server ~]# for f in $(ls -1 /sys/class/net/); do echo "Eth inface: $f"; cat /sys/class/net/$f/operstate; done
Eth inface: eth0
up
Eth inface: eth1
up
Eth inface: eth2
up
Eth inface: lo
unknown

If your operstate returns something different like state unknown, e.g.:

root@linux-server ~]# cd /sys/class/net/
[root@linux-server net]# grep "" eth2/operstate
unknown
[root@linux-server net]#

[root@linux-server net]# grep "" eth{0,1,2,3}/operstate  
eth0/operstate:unknown
eth1/operstate:unknown
eth2/operstate:unknown
eth3/operstate:unknown

Then you need to check the carrier file

[root@linux-server net]# grep "" eth{0,1,2,3}/carrier
eth0/carrier:1
eth1/carrier:1
eth2/carrier:1
eth3/carrier:1

It could return either 0 or 1

The number 1 in the above output means that the network cable is physically connected to your network card’s slot meaning your network switch migration is success.

Method 2: Next, we will test a second network interface eth1:

[root@linux-server net]# cat /sys/class/net/eth1/carrier
[root@linux-server net]# cat: /sys/class/net/eth1/carrier: Invalid argument

This command’s output most likely means the the eth1 network interface is in powered down state.

So what have learned?

We have learned how to monitor the state of the network cable connected to a Linux ethernet device via external switch that is migrated without the use of any external tools like ethtool.

How to Avoid the 7 Most Frequent Mistakes in Python Programming

Monday, September 9th, 2019

python-programming-language-logo

Python is very appealing for Rapid Application Development for many reasons, including high-level built in data structures, dynamic typing and binding, or to use as glue to connect different components. It’s simple and easy to learn but new Python developers can fall in the trap of missing certain subtleties.

Here are 7 common mistakes that are harder to catch but that even more experienced Python developers have fallen for.

 

1. The misuse of expressions as function argument defaults

Python allows developers to indicate optional function arguments by giving them default values. In most cases, this is a great feature of Python, but it can create some confusion when the default value is mutable. In fact, the common mistake is thinking that the optional argument is set to whatever default value you’ve set every time the function argument is presented without a value. It can seem a bit complicated, but the answer is that the default value for this function argument is only evaluated at the time you’ve defined the function, one time only.  

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-3

 

2. Incorrect use of class variables

Python handles class variables internally as dictionaries and they will follow the Method Resolution Order (MRO). If an attribute is not found in one class it will be looked up in base classes so references to one part of the code are actually references to another part, and that can be quite difficult to handle well in Python. For class attributes, I recommend reading up on this aspect of Python independently to be able to handle them.

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-2

 

3. Incorrect specifications of parameters for exception blocks

There is a common problem in Python when except statements are provided but they don’t take a list of the exceptions specified. The syntax except Exception is used to bind these exception blocks to optional parameters so that there can be further inspections. What happens, however, is that certain exceptions are then not being caught by the except statement, but the exception becomes bound to parameters. The way to get block exceptions in one except statement has to be done by specifying the first parameter as a tuple to contain all the exceptions that you want to catch.

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-1
 

4. Failure to understand the scope rules

The scope resolution on Python is built on the LEGB rule as it’s commonly known, which means Local, Enclosing, Global, Built-in. Although at first glance this seems simple, there are some subtleties about the way it actually works in Python, which creates a more complex Python problem. If you make an assignment to a variable in a scope, Python will assume that variable is local to the scope and will shadow a variable that’s similarly named in other scopes. This is a particular problem especially when using lists.

 

5. Modifying lists during iterations over it

 

When a developer deletes an item from a list or array while iterating, they stumble upon a well known Python problem that’s easy to fall into. To address this, Python has incorporated many programming paradigms which can really simplify and streamline code when they’re used properly. Simple code is less likely to fall into the trap of deleting a list item while iterating over it. You can also use list comprehensions to avoid this problem.

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-8

       

6. Name clash with Python standard library

 

Python has so many library modules which is a bonus of the language, but the problem is that you can inadvertently have a name clash between your module and a module in the standard library. The problem here is that you can accidentally import another library which will import the wrong version. To avoid this, it’s important to be aware of the names in the standard library modules and stay away from using them.

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-5

 

7. Problems with binding variables in closures


Python has a late binding behavior which looks up the values of variables in closure only when the inner function is called. To address this, you may have to take advantage of default arguments to create anonymous functions that will give you the desired behavior – it’s either elegant or a hack depending on how you look at it, but it’s important to know.

 

 

how-to-avoid-the-7-most-frequent-mistakes-in-python-programming-6

Python is very powerful and flexible and it’s a great language for developers, but it’s important to be familiar with the nuances of it to optimize it and avoid these errors.

Ellie Coverdale, a technical writer at Essay roo and UK Writings, is involved in tech research and projects to find new advances and share her insights. She shares what she has learned with her readers on the Boom Essays blog.

35 years passed since first Bulgarian Аstronaut visited open space (cosmos)

Thursday, April 10th, 2014


soyuz-33_spaceship_pad
On 10th of April 1976 in 20:34 mins Moscow time from Boikonur Cosmodrome was launched s spaceship "Souyz-33 / Union-33" . On spacecraft flies 3 cosmonauts part of the space program Inter-cosmos, one of which is the Bulgarian cosmonaut and explorer Georgi Ivanov. Georgi Ivanov became the first Bulgarian who the leave planet earth, becoming the first space visitor with Bulgarian nationality.

Georgi_Ivanov_first-Bulgarian-cosmonaut

Ivanov spend in space 1 day 23 hours and 1 minute, after that the capsule landed in 320 km south-easy from Jezkazgan (Khazakhstan).
For his short stay in space in Earth's orbit Ivanov made 31 full turns around Planet Earth. With his flight to space Bulgaria joined the elite club of  "austranaut nations", making Bulgaria the sixth nation in world who sent representative in space.

syiuz-33-mission-logo-stamp

Flight mission's goal was linkage of their spaceship with orbital station "Salute-6" but because of technical malfunction "Syiuz 33"s moving with higher than forecasted and speed autoamtic correction system turns on which damages part of fuel camera, making necessary to cancel the flight.

Georgi-Ivanov-cosmonaut-with-russian-colleague-soyuz

Returning home on Earth he was awarded with medals "Hero of the USSR" and "Hero of Republic Bulgaria"
Nevertheless the mission was unsuccesful and dangerous Ivanov's pulse during all flight kept normal.

Georgi Ivanov is born in Lovech on 2-nd of July 1940 in family of Anastasia Kakalova and Ivan Ivanov Kakalov.During his school years he excercised parachutism, graduating in high-school "Todor Kirkov" Lovech in 1958.

Ivanov entered Bulgarian army in 1958 graduated Military school in Dolna Mitropolia (1964) with specialty of flight engineer and a pilot of class 1.
He served in Bulgarian National Army as a pilot, senior pilot, commander  and a squadron commander. In 1984 he defended his thesis and received a science degree "candidate of physics sciences". Georgi Ivanov is currently 73 years old. Nowadays Ivanov's birthouse in qr. "Varosha" is of historical importance and is preserved as a museum.

The fact that we Bulgarians have a cosmonaut is a great pride for me and all of us Bulgarians. Let us not forget our heroes and patriots and know our history.

Beside myself

Sunday, October 12th, 2008

There is not much to say, Recently I’m experiencing mix of spiritual and emotional fluctuations ups and downs.I feel so alone quite often. There are not many valuable people (considering my interests).Day by day I’m asking myself the question “Hey man , why are you studying HRQM this stupid secreatary stuff.”I’m confused quite a lot and in a state of a denial, or better to say I feel a kind of lost because I’m out of my confortzone .. The teachers here in the HRQM stream claim that when a man is frightened and out of his confort zone,then he is learning a lot. They might be true about that, I don’t know. At Friday we had that Business Ethics test.Before the test we watched the movie “The Wizard of Oz” a movie from the distant year 1939. Right after the class wasover I went home and laundered my clothes. Then we had a dinner. Today I woke up around 11:00, had my breakfastat around 13:00 and near 13:30 I went out for a walk. I went to the city center and walked around the river Netherlands Rijn.A little later I walked through the city center around the open market which was located right before The St. Eusibeus Chapel.I went through a waggon which sells bibles in different languages and tried to draw people back close to God andspoke for a while with one nice old man who said used to be a Christian for 40 years already.Then I went for shopping to the grocy stores Aldi and Albertheijn and went back “home” to Honigkamp… That’s mostlyhow my day passed … I should thank to God for still caring for me and providing me with all necessary for my daily living.Thanks Lord! END—–

Farting all the day

Tuesday, February 20th, 2007

Can’t stop farting terribly the whole day :] Yesterday I ate tons of food without thinking I’ll suffer in the morning.I woke up with terrible acids in the stomach. It’s like the sin. When you sin again and again you don’t realize sinleads consequences after him body suffering illness and death in the end both spiritual and physical. My daystarted terrifying. I was feeling cold most of the day. I have a bad blood movement so it’s very usual for me to feel cold.I hate this coldness! I went to the college for an hour it happened I have hour after 1 hour. I was almost ready to sleep walking.Today I’m terribly sleepy. On my home I met “Narf” a collegue in the college who is an IRC maniac and linux fan also :]. He proposedto drink coffee. So we spent an hour on a coffee. He explained me about the structure of the IRC in general it seems the backbone of the UniBG irc is debian.spnet.net. After an hour we went to the college but it seems like our English class was not after an hour but 2 hours, again the dumbs mismatched The Schedule. Nomen was infront of the college and we drunk coffee together on the fountain. I had Introduction to Management after the Business English. My classes ended in 15:45. I take Habib and we went home and discussed his plans about his future. He have plans to fly for UK if they approve him for Visa and make some money to be able to pay his taxes. After that Nomen come home we played MAMEs. A very commical situation was in the midday when I was with Nomen infront of a food kiosks, he was wayting for his snack, suddenly I farted terribly :]]. And we started laughing cause it smelled very brutally :]] I have peace almost the whole day. And I feel God’s love through his holy spirit. Thanks Lord Shabbaoth glory be to your Holy name Father!END—–

Light, Camera, Action!

Wednesday, July 18th, 2007

It was a pretty hot day. In the morning we discussed a lot about the idea to move one of the colocated servers from Netinfo to Evolink. Also I have moved www.bcc.bg from one machine to another did various other Job, plamenko come home and we uploaded some of his other videos, Damqncho called and was my guest for some time ( This guy is going to become a good man in Faith I’m sure). In 6:00 we had to go to the ex-calculation center and to sign for the Cisco Academy with Mitko but it happened that he had urgent work in Balchik so I have to go alone. I used Plamenko’s bike to go to the calculation center which was located at the end of the city (Riding bike is great !). I signed for Cisco and signed also Niki (Mitko’s brother) and Niki. So we are going to share the same Cisco class! :]. After that I went to Mitko’s home to explain to his brother about the cisco way of studying. Also I forgot to mention that Doncho, has given us all the material for the semestar on a cd, we are going to have 4 semesters for the first degree, each of the semestars is going to be something like 2 months or so, the practice is going to be in Saturday. Later I have met Alex and we drink beer together. Later I saw Lily for a while and we had a walk I met Galio ( A homeless boy :[), and bought him some food, later I realised that I have lost my wallet with some money I walked again the walk where I walked after I bought him food but I didn’t found it I get a little distressed but at the same time I was feeling very calm (unusual for such a situations ). I have put my hope God would give it back. First I suspected that Galio has stolen the wallet from me but I was wrong this boy respects me. I found Galio and asked him did he stole the money, he denied to be guilty and I trusted him because he was honest. He was very kind to me he came with me looking again over all the way where I have walked at last I suggested to look in the central park where we have drinked beer together with Alex, under the bench where we have seated Me and Galio found the Wallet. And we got really happy about this. I checked my wallet there was 22 lv in there. When we was still searching the wallet I promised to God that If we found the wallet I will give 10 lv. to for his kindness and concern about my problem. After I have found the wallet I have completed my promise. Galio walked with me up to my home. The End. The only think that I can say after all this is PRAISE THE LORD, BLESS HIS HOLY NAME OH HEAVENS AND EARTH AND ALL LIVING, AND OH MY SOUL BLESS THE LORD GOD! BLESSED BE OH LORD!!!! :] END—–

How to add manually adsense code to your wordpress blog in blog index and single page posts

Thursday, April 7th, 2011

I’ve recently realized that the Easy Adsenser plugin which I used to place google adsense advertisements on my blog, is probably stealing some portion of my clicks.

There were some fraud reports on wordpress.org by people who have found out the author of Easy Adsenser rips clicks, by showing sometimes his own ad code even if the plugin is configured to not grant any clicks as a donation to the plugin author.
I don’t know how true this story is and I don’t have the time to observe the whole plugin code to say for sure if the rumors about clicks stealing are true.

However as I’m paying my internet access (that guarantees) by blog to stay online with some adsense advertisements and the adsense revenues are either equal to my internet tax or a bit higher (depending on the month), it’s quite unpleasent to hear someone is stealing from the ads clicks which still generate very low revenue.

Thus I took the time to read some blog posts online which gave me some hints on how can I directly place the google adsense advertisement code into the theme template files

My goal was to place one google adsense ad to appear right after the title of each article and one to appear as a vertical bar in the end of my sidebar.

In this article in short I’ll explain how I achieved this banner placement via the default wordpress template which obviously I use on my blog.

Let’s start:

1. Add adsense to the index page of the blog

Edit your blog/wp-content/themes/default/index.php file

Therein find the code:

<div id="content" class="narrowcolumn" role="main">

and right after this line put the following php code:

<?php
$postnum = 1;
$showadsense1 = 1;
?>

This code is necessery to assure the adsense code only appears on the first blog post from the blog index page

2. Find the code:

<small><?php the_time('F jS, Y') ?> <!-- by

Immediately after the code place the php code:

<?php if ($postnum == $showadsense1) {
echo '<div class="adsense" style="float:right;margin:12px;">;paste here your adsense code ...</div>';
} ?>

<?php $postnum++; ?>

Now with this changes, 1 adsense advertisements should start appearing right after your first and only on your blog post, next step is to place manually one more vertical adsense banner.

2. Place adsense vertical bannre in wordpress blog sidebar

Login with admin user to wordpress and navigate to:

Appearance -> Widgets

Among the available widgets you will notice the widget called Text click over: Add to add this widget to the list of widgets to appear on your blog sidebar.

Afterwards look up over the Sidebar list of widgets find the newly added Text widget and click over Edit to modify it’s content.

Further on put a Title for the widget or choose to leave the title field as blank if you don’t want a name to appear.
On the next textbox just paste your adsense code and you’re done. A simple refresh of your wordpress blog index page should show you a vertical banner with your adsense code.
! Note that if you have recently issued the adsense code it will take about 10-20 minutes until the banner starts showing up.

Until now wordpress is configured to show adsense adverts on the blog main page, as a next step we need to place the same adsense adverts to appear whether a single blog post is reviewed (opened).

Place an adsense advertisements to single posts opened

For that purpose it’s necessery to edit the file single.php it’s again located in blog/wp-content/themes/default

Once again you will first need to find the code:

if (have_posts())

Put the code after the end of the line on a new line:

<?php
// below code is for adsense
$postnum = 1;
$showadsense1 = 1;
?>

Next lookup in the file for the code:

<h2><?php the_title(); ?></h2>

On a new line after it place:

<?php if ($postnum == $showadsense1) { echo '<div class="adsense" style="float:right;margin:12px;"><script type="text/javascript"> place here your adsense code </div>';
} ?>

<?php $postnum++; ?>

That’s all now the adsense advertisements will be also showing on the single blog posts reviews found via some search engine (google, yahoo etc.).

Hope this article will be helpful to somebody, if so drop me a thanks line in comments 😉

How to make NAT enable hosts in a local network to access the internet, create port forwarding to local IPs behind the router using iptables

Tuesday, August 23rd, 2011

I’m bulding new iptables firewall on one Linux server. The Debian GNU/Linux is required to act as firewall do Network Adress Translation for a small network of office PCs as well as forward some of the inbound ports to hosts from the local network located behind the router.

The local network besides the router had an IP addressing in the class C network e.g. (192.168.1.1-255)

First I procceded and enabled the Network Address Translation via the Linux kernel variable:

linux:~# sysctl -w net.ipv4.ip_forward=1
linux:~# echo 'net.ipv4.ip_forward=1' >> /etc/sysctl.conf

Initially I even forgot to switch on the net.ipv4.ip_forward to 1 (by default this value is set to 0) – GNU/Linux’s default network behaviour is not predetermined to act as network router.
However, since I haven’t configured Network Address Translation for quite some time it completely slipped my mind!

Anyways next the actual iptables rule which makes NAT possible I used is:

linux:~# /sbin/iptables -t nat -A POSTROUTING -s 192.168.1.0/24 ! -d 192.168.1.0/24 -j SNAT --to-source xxx.xxx.xxx.xxx

Whether xxx.xxx.xxx.xxx is the External IP address assigned to the router on eth0

With this very simple rules now Network the local network is capable of accessing the Internet withotu problem.

It’s a good time to say that still many system administrators, still erroneously use MASQUERADE rules instead of SNAT .
IP MASQUERADING is an ancestry from ipchains and these days should be completely abandonded, especially where no often change of primary IP address to access the internet is made.
For dial-ups or other kind of networking, where the IP addresses are often changed still IP MASQUERADING might be a good idea though.

My next goal was to make the Linux router to do port forwarding of Traffic which arrives on port 80 to a IIS server assigned with a local IP address of 192.168.1.5
I did the webserver (port 80), port forwarding from IP xxx.xxx.xxx.xxx to 192.168.1.5 with the iptables rule:

linux:~# /sbin/iptables -t nat -A PREROUTING -d xxx.xxx.xxx.xxx/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 192.168.1.5:80

There was a requirement to do port forwarding for a Windows remote Desktop running on standard port 3389 from the router to the internal Windows IP address running the IIS webserver, however the company required me to only allow access to the rdesktop 3389 port to certain real IP addresses.
Initially I thought about using the above PREROUTING rule which makes the port redirection to the IIS server and only change port 80 to port 3389 , and then use filter table INPUT chain rules like:

/sbin/iptables -A INPUT -s xx1.xx2.xx3.xx4,1xx,2xx,3xx,4xx,xxx.xxx.xxx.xxx -p tcp -m tcp --dport 3389 -j ACCEPT/sbin/iptables -A INPUT -p tcp -m tcp --dport 3389 -j REJECT --reject-with icmp-port-unreachable
32

However this did not work out, so I decided to give a try to do the same within the filter table using the FORWARD chain, like so:

FORWARD/sbin/iptables -A FORWARD -p tcp -m tcp -s xx1.xx2.xx3.xx4,1xx,2xx,3xx,4xx,xxx.xxx.xxx.xxx -p tcp -m tcp --dport 3389 -j ACCEPT
/sbin/iptables -A FORWARD -p tcp -m tcp --dport 3389 -j REJECT --reject-with icmp-port-unreachable

Adding this rules did not added any filtering to the forwarded remote desktop port. I suspected that somehow probably my above PREROUTING nat rules are read before any other rules and therefore automatically allows any IP address to port fortward traffic.
I’ve checked the iptables documentation and it seems my guess was partially right.

When some kind of network traffic enters the iptables firewall it first goes through the PREROUTING channel and then the traffic flows in a certain order.
iptables packet flow diagram

The iptables network packets flow is clearly seen in above’s diagram a thorough looks gives a very good idea on how packet is being processed by iptables

Finally as I couldn’t think about a good solution on how to only filter the port redirected traffic, which always firstly entered in the POSTROUTING chain, I’ve consulted with the guys in irc.freenode.net in #Netfilter.

I’m quite thanksful as a guy nicknamed Olipro has given me a pretty good picture on the port forwarding POSTROUTING problem and has provided me with a very logical easy and great fix.
He suggested that I only do port forwarding for certain IP addresses instead of allowing all IP addresses and then lookup for a way to allow only some of them and filter the rest.

The iptables rule to restrict the incoming traffic to the remote desktop forwarded port 3389 to few only allowed IP addresses looks like so:

linux:~# /sbin/iptables -t nat -A PREROUTING -d xxx.xxx.xxx.xxx/32 -s xx1.xx2.xx3.xx4,1xx,2xx,3xx,4xx,xxx.xxx.xxx.xxx -p tcp -m tcp –dport 3389 -j DNAT –to-destination 192.168.1.5:3389

Now the three sample IPs passed xx1.xx2.xx3.xx4,1xx,2xx,3xx,4xx,xxx.xxx.xxx.xxx has added to port forward traffic on 3389 to 192.168.1.5

By the way I did not know that newer versions of iptables support passing by multiple IP addresses to the –source or –destination IP. This is really great feature I’ve learned from the good guys from #Netfilter. However one should be careful when using the multiple IPs with -s or -d, it’s really important that the passed consequent IPs has no space between the , delimiter.

Now that’s all my task is completed. All computerse inside the Network 192.168.1.1-255 on the Linux router freely can access the Internet, all IPs are also capable to access the IIS server located behind the NAT as well as only certain IPs are capable of accessing to the IIS remote desktop.
Hope the article helps somebody 😉