pirulo pirulo - 2 months ago 14
Python Question

creating teaming from user input

I'm trying to create a centos 7 a networking teaming (bonding) using a user input in a python script. C

import socket

# IP Address
IPADDR = socket.gethostbyname(socket.gethostname())
print IPADDR
# Netmask
NETMASK = raw_input("Enter Netmask address: ")
PREFIX = sum([bin(int(x)).count("1") for x in NETMASK.split(".")])
print NETMASK
# Gateway
GATEWAY = raw_input("Enter Gateway address: ")
print GATEWAY
# Run command and substitution
os.system("nmcli con add type team con-name team0 ifname team0 config '{"runner":{"name": "activebackup"}}'")
os.system("nmcli con mod team0 ipv4.addresses IPDDR/PREFIX")
os.system("nmcli con mod team0 ipv4.gateway GATEWAY")
os.system("nmcli con mod team0 connection.autoconnect yes")
os.system("nmcli con mod team0 ipv4.method manual")
os.system("nmcli con mod team0 ipv6.method ignore")


When I run the script I get this errors:

File "team0.py", line 16
os.system("nmcli con add type team con-name team0 ifname team0 config '{"runner":{"name": "activebackup"}}'")
^
SyntaxError: invalid syntax


Can someone help to find what I'm doing wrong.
Thanks

Answer

The syntax error is occurring because you are not escaping the quote " characters. The interpreter thinks that the string has ended and then trips.

You can use a backslash \ to escape the quote:

os.system("nmcli con add type team con-name team0 ifname team0 config '{\"runner\":{\"name\": \"activebackup\"}}'")

In addition, please note that your declared variables are not being picked up when they are declared in string literals. You will need to modify these commands with format, for example:

os.system("nmcli con mod team0 ipv4.addresses {}/{}".format(IPDDR, PREFIX))
os.system("nmcli con mod team0 ipv4.gateway {}".format(GATEWAY)")

See the above documentation and other SO questions for more info about how to use format.