in Development, System Administration

Digital Ocean Blocking IPv6 Mail Traffic && A Python Search and Replace One Liner

I got nearly insane yesterday, so let this be your warning: Digital Ocean is blocking IPv6 mail traffic…. on purpose.

To deactivate IPv6 in RHEL 7, go to /etc/sysconfig/network-scripts/ifcfg-eth0, change IPV6INIT=yes to IPV6INIT=no and reboot. I have to admit, it would have been far better to leave IPv6 enabled and route mail traffic over IPv4. Anyway, I got distracted by list comprehensions and generator expressions, which resulted in this one-liner to deactivate IPv6 “automatically” (valid only for RHEL derivates and Python > 3.3):

python -c "import fileinput; [ print(line, end='') for line in ( lines.replace('IPV6INIT=yes', 'IPV6INIT=no') for lines in fileinput.input('/etc/sysconfig/network-scripts/ifcfg-eth0', inplace=True) ) ]"

For everyone new to python one liners, here is what’s going on:

  • -c : program passed in as string (that’s what we are doing)
  • import fileinput : Iterate over lines from multiple input streams
  • The outer [] is a list comprehension. It generates a new list and describes what items should be therein: [f(x) for x in S if P(x)].
    [ print(line) for every line in ( generator expression ) ]
  • The end argument tells print to not write new lines
  • The generator expression expresses a generator: (f(x) for x in S if P(x)).
    ( replace string with string for all lines in fileinput )
  • Fileinput.input takes an input file as argument
  • inplace = True lets us write the changed right back

This concludes in:

[ Print (every  line) ( after replacing (string x with string  y) of that (file and make all changes in place ) ) ]

Apparently, contrary to the past, search and replace one liners are now possible in Python. If you have any suggestions to my proposed solution, I am happy to hear them.