简体   繁体   中英

Python: execute shell command using variable

In my Lab I need to change the interface on a server to a random IPv6 address. I have two scripts. The first script makes up a random IPv6 address and works perfectly. I'm trying to take the output of that script and use it as a variable in the second script. Then run an ifconfig command to set that IPv6 address on that interface. That's the general run down of what I'm trying to do. Below is the script that generates the random IPv6 address, ipv6_gen.py

from random2 import seed, getrandbits
from ipaddress import IPv6Network, IPv6Address

subnet = u'1234:5678:ab:cde::/64'

seed()
network = IPv6Network(subnet)
address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen))

print(address)

This one should take the output of the first and execute the ifconfig command.

import ipv6_gen
import os, commands
import subprocess
import shlex

ipv6=ipv6_gen
shell_cmd = ("sudo ifconfig en0 inet6 add %s" %ipv6)

subprocess_cmd = shlex.split(shell_cmd)
subprocess.call(subprocess_cmd)

I'm getting the following errors:

ubuntu:~$ python change_ipv6.py 
1234:5678:ab:cde:8087:1bb6:b264:acdd
<module: Host name lookup failure
getaddrinfo: ipv6_gen: -3
ipv6_gen: Host name lookup failure
ifconfig: `--help' gives usage information.

when I run ifconfig the IPv6 address isn't set. Not sure what I'm doing wrong, tried researching this for awhile now and got nothing. Any help would be appreciated.

Second script looks a bit odd.

You assign module ipv6_gen to a variable ipv6 and then use it for shell command.

Try this version:

import ipv6_gen
import os, commands
import subprocess
import shlex

ipv6 = ipv6_gen.address
shell_cmd = ("sudo ifconfig en0 inet6 add %s" % ipv6)

subprocess_cmd = shlex.split(shell_cmd)
subprocess.call(subprocess_cmd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM