Skip to content

Instantly share code, notes, and snippets.

@un-def
Created June 24, 2015 08:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save un-def/42e6518c9b81b2d119cc to your computer and use it in GitHub Desktop.
Save un-def/42e6518c9b81b2d119cc to your computer and use it in GitHub Desktop.
Toggle network connection up/down using nmcli
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import subprocess
if len(sys.argv) < 2:
print("Usage: nmcli-toggle.py connection_id")
sys.exit()
conn_id = sys.argv[1]
active = subprocess.check_output(['nmcli', 'connection', 'show', '--active'])
up_down = ('up', 'down')[conn_id in active]
subprocess.call(['nmcli', 'connection', up_down, 'id', conn_id])
@derlucas
Copy link

derlucas commented Dec 8, 2019

with python 3 this works:

#!/usr/bin/env python
import sys
import subprocess
if len(sys.argv) < 2:
    print("Usage: nmcli-toggle.py connection_id")
    sys.exit()
conn_id = sys.argv[1]
active = subprocess.check_output(['nmcli', 'connection', 'show', '--active'])
up_down = ('up', 'down')[conn_id in str(active)]
subprocess.call(['nmcli', 'connection', up_down, 'id', conn_id])

@easbarba
Copy link

easbarba commented Dec 10, 2019

@derlucas

Simpler. > py3.6

def net_toogle():
    """Toogle Network Connection. nmcli"""
    import subprocess

    status = str(
        subprocess.check_output(["nmcli", "general", "status"]).decode("utf8")
    ).split()

    up_down = "off" if "connected" in status else "on"

    subprocess.run(["nmcli", "networking", up_down], check=False)

PS: try/except wont hurt .... :D

@ja0nz
Copy link

ja0nz commented Apr 18, 2021

This gist is the first hit for "nmcli toggle" - so I leave my shell solution here for my future self:)

nmcli networking connectivity | grep -q none \
  && nmcli networking on \
  || nmcli networking off

@Javiolonchelo
Copy link

That is a great shell solution!!! I used this for a specific network connection toggle, it looked like this:

nmcli c show --active | grep networkName && nmcli c down networkName || nmcli c up networkName

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment