Exemplo n.º 1
0
Arquivo: sim.py Projeto: ipbus/ipbb
def virtualtap(ictx, dev, ip):
    """Create a virtual tap device
    """

    # -------------------------------------------------------------------------
    if not which('openvpn'):
        raise click.ClickException(
            'OpenVPN (openvpn) not found. Please install it and execute the command again.'
        )
    # -------------------------------------------------------------------------

    lCmds = '''
sudo openvpn --mktun --dev {0}
sudo /sbin/ifconfig {0} up {1}
sudo chmod a+rw /dev/net/tun
'''.format(
        dev, ip
    )

    pwd = getpass.getpass("[sudo] password for %s: " % getpass.getuser())
    with sh.contrib.sudo(password=pwd, _with=True):
        # with sh.contrib.sudo( _with=True):
        sh.openvpn('--mktun', '--dev', dev, _out=sys.stdout)
        sh.ifconfig(dev, 'up', ip, _out=sys.stdout)
        sh.chmod('a+rw', '/dev/net/tun', _out=sys.stdout)
Exemplo n.º 2
0
 def mode(self, mode=None):
     if not mode:
         return self.param("mode")
     try:
         ifconfig(self.dev, "down")
         iwconfig(self.dev, "mode", mode)
         ifconfig(self.dev, "up")
         return self.mode() == mode
     except:
         return False
Exemplo n.º 3
0
 def mode(self, mode=None):
     if not mode:
         return self.param('mode')
     try:
         ifconfig(self.dev, 'down')
         iwconfig(self.dev, 'mode', mode)
         ifconfig(self.dev, 'up')
         return self.mode() == mode
     except:
         return False
Exemplo n.º 4
0
 def create(self, bridge):
     if bridge not in self.bridgeList:
         try:
             brctl.addbr(bridge)
             ifconfig(bridge, 'up')
             self.bridgeList += [bridge]
         except:
             raise BridgeException("Unable to add linux bridge.")
         return True
     else:
         return False
Exemplo n.º 5
0
 def addIP(self, bridge, ipv4, netmask='255.255.255.0'):
     if bridge in self.bridgeList:
         try:
             ifconfig(bridge, 'down')
             ifconfig(bridge, ipv4, 'netmask', netmask, 'up')
         except:
             raise IPException("Bridge IP assignment failed.")
         return True
     else:
         raise BridgeException("Bridge not found.")
         return False            
Exemplo n.º 6
0
 def delIP(self, bridge):
     if bridge in self.bridgeList:
         try:
             ifconfig(bridge, 'down')
             ifconfig(bridge, 'up', '0.0.0.0')
         except:
             raise IPException("Bridge IP removal failed.")
         return True
     else:
         raise BridgeException("Bridge not found.") 
         return False            
Exemplo n.º 7
0
 def destroy(self, bridge):
     if bridge in self.bridgeList:
         try:
             ifconfig(bridge, 'down')
             brctl.delbr(bridge)
             self.bridgeList.remove(bridge)
         except:
             raise BridgeException("Unable to delete linux bridge.")
         return True
     else:
         return False
Exemplo n.º 8
0
    def reconnect(self):
        """
        Reconnects the WIFI connection with new MAC address and hostname
        """
        networksetup("-removepreferredwirelessnetwork", "en0", self.WIFI_SSID)

        self.set_hostname(self.generate_new_hostname())

        ifconfig("en0", "ether", self.generate_new_mac())

        networksetup("-setairportnetwork", "en0", self.WIFI_SSID)
        self.init_usage = self.traffic_usage()
Exemplo n.º 9
0
def tunnelIsReady():
    count = 5
    while count > 0:
        print('tunnelIsReady: count = ' + str(count))
        gateway = ''
        try:
            conf = sh.ifconfig("ppp0")
            print("tunnelIsReady:\n" + str(conf))
            for line in str(conf).splitlines():
                fields = line.split()
                for term in fields:
                    if "P-t-P" in term:
                        gateway = term.split(":")[1]

        except:
            print('tunnel ppp0 not found')

        print('tunnelIsReady: gateway: ' + str(gateway))
        if gateway == '':
            count = count - 1
            time.sleep(5)
        else:
            break

    if count == 0:
        print('Counted down, but no tunnel')
        return False

    return True
Exemplo n.º 10
0
def get_host_ip():
    ip_exp = re.compile('(?:inet addr:192.168.)(\d+\.\d+)')
    ip_out = ip_exp.findall(sh.ifconfig().stdout)
    if len(ip_out) == 1:
        return '192.168.' + ip_out[0]
    else:
        return '127.0.0.1'
def get_ipv6_tunnel_prefix():
    try:
        out = ifconfig(IPV6TUNNEL_INTERFACE)
        lines = out.split('\n')

        # Look for a line with a global address in it
        for line in lines:
            if 'Scope:Global' in line:
                segments = line.split()

                # Find the portion of the line that has '::1/128'
                for segment in segments:
                    try:
                        # Split the prefix (assuming it has one) from the
                        # rest of the address so that IPy works.
                        addr_pieces = segment.split('/')
                        ipaddr = IPy.IP(addr_pieces[0])

                        # Get the just the upper 64 bits
                        prefix = ipaddr.int(
                        ) & 0xFFFFFFFFFFFFFFFF0000000000000000
                        return str(IPy.IP(prefix)) + '/64'
                    except Exception:
                        pass
        return None
    except sh.ErrorReturnCode_1:
        # This is what happens when the interface doesn't exist
        print('Could not find IPv6 Tunnel interface.')
        return None
    except Exception:
        # Catch all
        return None
Exemplo n.º 12
0
Arquivo: cli.py Projeto: D3f0/inspy
def get_ips():
    output = sh.ifconfig()
    for match in re.findall("inet (addr:)?(([0-9]*\.){3}[0-9]*)", str(output)):
        _, ip, *_ = match
        if ip.startswith("127"):
            continue
        yield ip
Exemplo n.º 13
0
def get_ipv6_tunnel_prefix ():
	try:
		out = ifconfig(IPV6TUNNEL_INTERFACE)
		lines = out.split('\n')

		# Look for a line with a global address in it
		for line in lines:
			if 'Scope:Global' in line:
				segments = line.split()

				# Find the portion of the line that has '::1/128'
				for segment in segments:
					try:
						# Split the prefix (assuming it has one) from the
						# rest of the address so that IPy works.
						addr_pieces = segment.split('/')
						ipaddr = IPy.IP(addr_pieces[0])

						# Get the just the upper 64 bits
						prefix = ipaddr.int() & 0xFFFFFFFFFFFFFFFF0000000000000000
						return str(IPy.IP(prefix)) + '/64'
					except Exception:
						pass
		return None
	except sh.ErrorReturnCode_1:
		# This is what happens when the interface doesn't exist
		print('Could not find IPv6 Tunnel interface.')
		return None
	except Exception:
		# Catch all
		return None
Exemplo n.º 14
0
def local_ip():
    res = sh.ifconfig().stdout
    ip = None
    m = re.search(r'inet (30[0-9\.]+[0-9]+)', res)
    if m:
        print(m.group(1))
        ip = m.group(1)
    return ip
Exemplo n.º 15
0
    def ifdown(self, reset=False):
        logger.info('Bringing down interface %s', self.name)
        ret = True
        try:
            sh.ifdown(self.name)
        except:
            logger.warning('Error Bringing down interface %s', self.name)
            ret = False

        if reset:
            logger.warning('Resetting interface %s', self.name)
            for i in ['0.0.0.0/0', 'down']:
                try:
                    sh.ifconfig(self.name, i)
                except:
                    pass

        return ret
Exemplo n.º 16
0
def get_host_ip():
    """
    parses ifconfig system command and returns host ip
    """
    ip_exp = re.compile(r"(?:eth\d.*?inet addr\:)(\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3})", re.DOTALL)
    ip_out = ip_exp.findall(sh.ifconfig().stdout)
    if len(ip_out) > 0:
        return ip_out[0]
    else:
        return "127.0.0.1"
Exemplo n.º 17
0
def get_ip(interface=None):
    """
    Get the IP of the specified interface
    :param interface: interface
    :return: ip address or False
    """
    eth0 = sh.ifconfig('eth0')
    ip = re.search(r'inet addr:(\S+)', str(eth0))
    if not ip:
        return False

    return ip.group(1)
Exemplo n.º 18
0
 def wifi(self):
     self.__update_network_interface()
     if (self.__network_interface):
         mSsid = sh.awk(
             sh.networksetup("-getairportnetwork",
                             self.__network_interface),
             '{print $4}').strip()
         mIp = sh.awk(
             sh.ifconfig(self.__network_interface),
             '$1=="inet" {print $2}').strip()
         return mSsid + " " + mIp
     else:
         return "::"
Exemplo n.º 19
0
def _command(cmd=''):
    if cmd == 'df':
        result = df('-h')
    elif cmd == 'ps':
        result = ps('-ef', _tty_out=False)
    elif cmd == 'ifconfig':
        result = ifconfig()
    elif cmd == 'hostinfo':
        result = hostinfo()
    elif cmd == 'sw_vers':
        result = sw_vers()    
    else:
        redirect('/')
    return template(TEXTPAGE, title=cmd.upper(), text=result)
Exemplo n.º 20
0
def rmaliases():
    print("Removing interface aliases..")
    x = sh.ifconfig("lo0")
    for i in x.split("\n"):
        print(i)
        matchobj = re.match(
            r'^\W+inet\W+(' + re.escape(localif_prefix) + '\.\d+)\W+.*$', i)
        if matchobj:
            ip = matchobj.group(1)
            print("Removing %s" % str(ip))
            try:
                output = sh.sudo("ifconfig", "lo0", "-alias", str(ip))
                return (output.exit_code)
            except:
                return ("# ERROR: Failed to remove lo0 alias %s!" % (str(ip)))
Exemplo n.º 21
0
def build_network(_server):
    network = _server['meta']['network']
    sort_order = ['physical', 'symlink', 'bond', 'tagged']
    networks = sorted(network.items(),
                      key=lambda x: sort_order.index(x[1]['type']))

    for name, net in networks:
        if net['type'] == 'symlink':
            continue
        elif net['type'] == 'bond':
            sh.modprobe('bonding', 'mode=4', 'miimon=100',
                        'xmit_hash_policy=1')
            sh.ifconfig(name, 'up')
            for iface in net['interfaces']:
                sh.ifenslave(name, iface)
        elif net['type'] == 'tagged':
            iface = net['interfaces'][0]
            sh.vconfig('add', iface, net['vlan'])
            sh.ifconfig(name, 'up')
        # Assign ip if required
        if net.get('ip'):
            ip = netaddr.IPNetwork('/'.join((net['ip'], net['mask'])))
            sh.ip('addr', 'add', str(ip),
                  'brd', str(ip.broadcast), 'dev', name)
Exemplo n.º 22
0
def build_network(_server):
    network = _server['meta']['network']
    sort_order = ['physical', 'symlink', 'bond', 'tagged']
    networks = sorted(network.items(),
                      key=lambda x: sort_order.index(x[1]['type']))

    for name, net in networks:
        if net['type'] == 'symlink':
            continue
        elif net['type'] == 'bond':
            sh.modprobe('bonding', 'mode=4', 'miimon=100',
                        'xmit_hash_policy=1')
            sh.ifconfig(name, 'up')
            for iface in net['interfaces']:
                sh.ifenslave(name, iface)
        elif net['type'] == 'tagged':
            iface = net['interfaces'][0]
            sh.vconfig('add', iface, net['vlan'])
            sh.ifconfig(name, 'up')
        # Assign ip if required
        if net.get('ip'):
            ip = netaddr.IPNetwork('/'.join((net['ip'], net['mask'])))
            sh.ip('addr', 'add', str(ip), 'brd', str(ip.broadcast), 'dev',
                  name)
Exemplo n.º 23
0
class NetInterfaces:

	sh.ifconfig(_out="/home/edita/scripting/interfaces")

	def __init__(self):
		pass
	def read_write():
		with open("interfaces", 'r', newline='') as f_in:
			net_info = f_in.readlines()
			with open('inet_status.csv','w') as f_out:
				for line in net_info:
					match = re.match(r'[a-z0-9]+', line)
					if match:
						f_out.write(match.group(0))
						f_out.write('\n')
			f_out.close()
		f_in.close()
Exemplo n.º 24
0
def openRoute(tS, ip):
    # At this time, ppp0 is created, named, etc.
    # Check if route already exists
    print("openRoute: " + str(tS) + " " + ip)

    if ip in tS['tunnelRoutes']:
        return True

    # Else open a route
    print("Opening route to " + ip)
    gateway = ""
    try:
        a = sh.ifconfig("ppp0")
        for line in str(a).splitlines():
            fields = line.split()
            for term in fields:
                if "P-t-P" in term:
                    gateway = term.split(":")[1]
                    print("Gateway: " + gateway)
    except Exception as e:
        print("openRoute: cannot ifconfig ppp0 " + str(e))
        return False

    if gateway == "":
        print("openRoute: gateway could not be parsed from ppp0")
        return False

    print("openRoute: Adding route to " + str(ip).split("@")[1])
    try:
        sudo.route("add", "-host",
                   str(ip).split("@")[1], "gw", gateway, "dev", "ppp0")
        print("route added")
    except Exception as e:
        print("Error adding route: " + str(e))
        return False

    print(sh.route("-n"))
    rs = redis.Redis("localhost")
    tS['tunnelRoutes'].append(ip)
    rs.set("tunnelStatus", json.dumps(tS))

    return True
Exemplo n.º 25
0
 def _get_nic_info(self):
     #return [ 'eth0', '192.', '168.', '  1.', ' 148' ]
     nicinfo = {}
     item=None
     for line in sh.ifconfig(_iter = True):
         line = line.strip()
         ifline = line.split('Link encap:')
         if len(ifline) == 2: ## it's a if interface line
             ifname = ifline[0].strip()
             #tmplist = ifline[1].split('HWaddr ')
             tmplist = ifline[1].split()
             item = {}
             item_count = len(tmplist)
             if item_count < 2: ## 这行有错误
                 item = None
                 continue  ## should be loop back if
             if tmplist[0] == 'Local': ## 这是Loopback接口
                 item = None
                 continue
             if tmplist[0] == 'Ethernet': ## 这是以太网接口
                 if item_count == 3: item['MAC'] = tmplist[2] ## 可能有错误。
             elif tmplist[0] == 'Point-to-Point': ## 这是ppp接口
                 item['MAC'] = 'PPP interface'
             else: ## 不知道是什么接口
                 item = None
                 continue
             nicinfo[ifname] = item
             continue
         ipline = line.split('inet addr:')                
         if len(ipline) == 2: ## 这一行包含IP 地址
             if item == None : continue
             tmplist = ipline[1].split(' ', 1)
             ipval = tmplist[0]
             remain = tmplist[1].split('Mask:')
             item['Netmask'] = remain[1] 
             item['IP']      = ipval
             item['Bcast']   = remain[0].split(':')[1].strip()  ## 这一行也可能是 P-t-P 地址
             continue
     return nicinfo
Exemplo n.º 26
0
def get_ip():
    res = sh.ifconfig().stdout
    found = re.findall(r'inet ([0-9\.]+[0-9]+)', res)
    for n, ip in enumerate(found):
        print('{} - {}'.format(n, ip))
        # print(m.groups())
        # print(m.group(1))
        # ip = m.group(1)
    if args.num is None:
        # give a default one
        ret = found[0]
        for ip in found:
            # ignore local
            if ip == '127.0.0.1':
                continue
            else:
                ret = ip
                break
    else:
        ret = found[args.num]

    return ret
Exemplo n.º 27
0
def url_string():
    _r = []
    comp_name = socket.gethostname().split(".")[0]

    for eth in re.compile(r'\n\b', re.I).split(str(sh.ifconfig())):
        if not eth or eth[0] != 'e':
            continue
        ip = re.findall(r'\binet [^\d]*((?:\d{1,3}\.){3}\d{1,3})', eth, re.I)
        iname = re.findall(r'^[a-z0-9]*', eth, re.I)
        if ip and iname:
            _r.append("comp_name={}_{}&comp_ip={}".format(
                comp_name, iname[0], ip[0]))

    #ip_internal = [x.split('inet addr:')[-1].split()[0] for x in sh.ifconfig().split("\n\n") if x.startswith('e')][0]
    try:
        resp = requests.get("https://api.ipify.org?format=json")
        ip_external = json.loads(resp.content.decode('utf-8'))['ip']
        if ip_external:
            _r.append("comp_name={}_external&comp_ip={}".format(
                comp_name, ip_external))
    except:
        pass
    print(_r)
    return _r
Exemplo n.º 28
0
import os

import sh

print sh.ifconfig("en0")
print sh.ls("/")
sh.git.clone("[email protected]:dmj/dmj-tj.git")

os.system('clear')
Exemplo n.º 29
0
#coding=utf8
#基本用法

from sh import ifconfig
print(ifconfig())
print('')

import sh
print(sh.ls("/"))
print('')

# same thing as above
from sh import ls
print(ls("/"))
print('')

#sh.google_chrome("http://google.com")

# 执行shell脚本文件
# run = sh.Command("/home/amoffat/run.sh") # Absolute path
# run()

lscmd = sh.Command("ls")  # Absolute path not needed
print(lscmd())
Exemplo n.º 30
0
 def getMAC(self, device='eth0'):
     return ifconfig(device).split(' ')[43]
Exemplo n.º 31
0
import sh
import time

print "Loading..."
time.sleep(5)

sh.ifconfig("enp0s3", "up")
print "Ethernet up"
time.sleep(1)
print sh.ifconfig("enp0s3")
Exemplo n.º 32
0
 def delIf(self, bridge, devices):
     if bridge in self.bridgeList:
         if type(devices) is list:
             try:
                 ifconfig(bridge, 'down')
                 for device in devices:
                     ifconfig(device, 'down')
                     brctl.delif(bridge, device)
                     ifconfig(device, 'up')
                 ifconfig(bridge, 'up')
             except:
                 raise BridgeException("Interface assignment failed.")
         else:
             try:
                 ifconfig(bridge, 'down')
                 ifconfig(devices, 'down')
                 brctl.delif(bridge, devices)
                 ifconfig(devices, 'up')
                 ifconfig(bridge, 'up')
             except:
                 raise BridgeException("Interface assignment failed.")
         return True
     else:
         raise BridgeException("Bridge not found.")
         return False             
Exemplo n.º 33
0
#coding=utf8
#基本用法

from sh import ifconfig
print(ifconfig())
print('')

import sh
print(sh.ls("/"))
print('')


# same thing as above
from sh import ls
print(ls("/"))
print('')

#sh.google_chrome("http://google.com")

# 执行shell脚本文件
# run = sh.Command("/home/amoffat/run.sh") # Absolute path
# run()


lscmd = sh.Command("ls")  # Absolute path not needed
print(lscmd())
Exemplo n.º 34
0
	print('sudo pip install python-pytun')
	sys.exit(1)
from sh import ifconfig
from sh import ip

import base64
import json
import socket
import struct

GATD_HOST = 'inductor.eecs.umich.edu'
GATD_PORT = 16284

#Create a tun device and setup the configuration to it
tun = pytun.TunTapDevice(name='ipv6gatd')
ifconfig(tun.name, 'up')
ifconfig(tun.name, 'mtu', '1280')
ip('-6', 'route', 'add', '2001:470:1f10:1320::2/128', 'dev', tun.name)

# Parameters for the ipv4 connection to gatd
gatdsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
gatdaddr = (GATD_HOST, GATD_PORT)

# Loop waiting for packets to get routed to this tun interface, strip them,
# and send the import bits back to gatd
while True:
	buf = tun.read(1280)
	pkt = dpkt.ip6.IP6(buf[4:])

	if type(pkt.data) != dpkt.udp.UDP:
		continue
Exemplo n.º 35
0
 def tearDown(self):
     if 'testMacvlan' in ifconfig('-a'):
         self._macvlan.delete()
Exemplo n.º 36
0
    def test_create_delete_macvlan(self):
        self._macvlan.create()
        self.assertTrue(self._veth_name in ifconfig('-a'))

        self._macvlan.delete()
        self.assertFalse(self._veth_name in ifconfig('-a'))
Exemplo n.º 37
0
# coding: utf-8
import sh
sh.ifconfig()
Exemplo n.º 38
0
                return (
                    "# ERROR: cannot find command %s and brew isn't installed, aborting"
                )
    elif command == "ghost":
        if not sh.which('ghost'):
            output = sh.sudo("gem", "install", command)
            return (output.exit_code)


if chkcom("haproxy"):
    print(chkcom("haproxy"))

if chkcom("ghost"):
    print(chkcom("ghost"))

ifaces = sh.ifconfig("lo0")


def findif(iface):
    if not re.search(re.escape(iface), str(ifaces), re.IGNORECASE):
        try:
            output = sh.sudo("ifconfig", "lo0", "alias", iface)
            return (output.exit_code)
        except:
            return ("# ERROR: Failed to add lo0 alias!")


def launch():
    print("Launching haproxy")
    sh.sudo("haproxy", "-f", haproxy_config, _fg=True)
Exemplo n.º 39
0
def setup_networking(ob_num: int):
    """Sets up networking.

    Installs some debs manually that are required for configuring networking,
    since we don't yet have networking and can't apt install them. Then configures
    DNS and network interfaces, then bounces the network interfaces.
    """
    print(" === Setting up networking === ")

    # Install network management packages manually via dpkg, since we can't apt
    # install them without networking already setup.
    print("Installing dependencies for setting up networking...")
    dpkg("-i", *glob("./*.deb"))

    print("Configuring resolved...")
    # Default to the Mikrotik router for DNS, with a fallback of Google's DNS
    sed("-i", "s/^#DNS=$/DNS=172.27.31.254 8.8.8.8/g",
        "/etc/systemd/resolved.conf")
    sed("-i", "s/^#FallbackDNS=$/FallbackDNS=8.8.8.8 8.8.4.4/g",
        "/etc/systemd/resolved.conf")
    systemctl("restart", "systemd-resolved")

    # Not sure if still used, but some things might be expecting orange boxen to
    # have this configuration file.
    with open("/etc/orange-box.conf", "w") as f:
        f.writelines([f"orangebox_number={ob_num}"])

    # Disable the external ethernet port (en*) and use both of the internal
    # ones (enx*). The enx* interfaces map to vlan1 and vlan2, which in turn
    # get mapped to `172.27.{orange box #}.X` and `172.27.{orange box # + 2}.X`,
    # respectively. They are both bridged to the wireless network that the
    # orange box is connected to, hence not needing en* connected.
    print("Writing network configuration...")
    interfaces = list(
        sorted(
            Path(iface).name for iface in glob("/sys/class/net/*")
            if Path(iface).name.startswith("en")))
    internal_ips = [f"172.27.{ob_num}.1", f"172.27.{ob_num + 2}.1"]
    gateway_ips = [f"172.27.{ob_num + 1}.254", f"172.27.{ob_num + 3}.254"]
    sh.ip("addr", "flush", "dev", interfaces[1])
    sh.ifconfig(interfaces[1], f"{internal_ips[1]}/23")
    systemctl("stop", "NetworkManager")
    systemctl("disable", "NetworkManager")

    with open("/etc/network/interfaces", "w") as f:
        f.write(
            textwrap.dedent(f"""
            # These are generated by orange-box build scripts
            auto lo
            iface lo inet loopback

            auto {interfaces[0]}
            iface {interfaces[0]} inet manual

            auto {interfaces[1]}
            iface {interfaces[1]} inet manual

            auto {interfaces[2]}
            iface {interfaces[2]} inet manual

            auto br0
            iface br0 inet static
              address {internal_ips[0]}
              netmask 255.255.254.0
              gateway {gateway_ips[0]}
              dns-nameservers {internal_ips[0]} {gateway_ips[0]}
              bridge_ports {interfaces[1]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0

            auto br1
            iface br1 inet static
              address {internal_ips[1]}
              netmask 255.255.254.0
              bridge_ports {interfaces[2]}
              bridge_stp off
              bridge_fd 0
              bridge_maxwait 0"""))

    print("Restarting network interfaces...")
    bridges = ["br0", "br1"]

    # Take down all of the interfaces
    for iface in interfaces + bridges:
        sh.ifdown("--force", iface)

    # Bring up all interfaces except enp*
    for iface in interfaces[1:] + bridges:
        sh.ifup("--force", iface)

    print("Waiting for network to come up...")
    for _ in range(60):
        try:
            ping("-c1", "8.8.8.8")
            break
        except sh.ErrorReturnCode_1:
            print(" - Still waiting for 8.8.8.8...")
    else:
        print("Waited too long for network to come up.")
        print("Please fix the network.")
        sys.exit(1)

    print("Waiting for DNS to come up...")
    for _ in range(60):
        try:
            ping("-c1", "launchpad.net")
            break
        except (sh.ErrorReturnCode_1, sh.ErrorReturnCode_2):
            print(" - Still waiting for launchpad.net...")
    else:
        print("Waited too long for DNS to come up.")
        print("Please fix the DNS.")
        sys.exit(1)
Exemplo n.º 40
0
#!/usr/bin/env python

import os, sys
import sh

print sh.ifconfig("eth0")

sh.firefox("google.com")
Exemplo n.º 41
0
    def test_create_delete_macvlan(self):
        self._macvlan.create()
        self.assertTrue(self._veth_name in ifconfig("-a"))

        self._macvlan.delete()
        self.assertFalse(self._veth_name in ifconfig("-a"))
Exemplo n.º 42
0
 def inner():
     output_lines = ifconfig(iface).splitlines()
     filtered = filter((lambda x: 'SSID' in x), output_lines)
     return [line.strip() for line in output_lines if address_re.match(line)][0].split()[1]
Exemplo n.º 43
0
table.align["name"] = "1"
table.padding_width = 1
redName = Fore.RED + "mayl" + Fore.RESET
table.add_row([redName, 26, "python", "YBU", date.datetime])
table.add_row(["mayt", 23, "python", "ZJU", date.datetime])
table.sort_key("age")
# table.reversesort = True
print(table)

# python中使用shell命令,用os.popen()执行命令cmd,还有其他方法。。。。。
import os
output = os.popen("ls $HOME/bin")
print(output.read(), type(output))
# -----------
from sh import ifconfig
print(ifconfig("wlan0"))


# progressbar是一个进度条库,该库提供了一个文本模式的progressbar。



# sudo pip3 install colorama
from colorama import Fore
print(Fore.BLUE + "red text ============================================================")

# Python 程序员应该知道的 10 个库 http://blog.jobbole.com/52355/

# http://www.cnblogs.com/scgw/archive/2009/11/09/1599378.html
# http://developer.51cto.com/art/201003/186941.htm
# http://www.pythontab.com/
Exemplo n.º 44
0
import sys
import re
import urllib2
from sh import ifconfig
from subprocess import Popen, PIPE

# this removes the ifconfig file if present, prior to running
Popen('rm /home/pi/JumPi/cruft/ifconfig_*', shell=True, stdin=PIPE).communicate("y")

# this removes the IP file if present, prior to running
Popen('rm /home/pi/JumPi/jump_ip.txt', shell=True, stdin=PIPE).communicate("y")

# this uses sh, which allows you to interface with the subprocess ifconfig
myEth0 = ifconfig("eth0")
myWlan0 = ifconfig("wlan0")

# this will be for the VPN IP
#myIPvpn = ifconfig("")

# this just saves the raw ifconfig output for specified interface to txt
file_ifconfig = open("/home/pi/JumPi/cruft/ifconfig_eth0.txt", "w")
file_ifconfig.writelines(myEth0)
file_ifconfig.close()

file_ifconfig = open("/home/pi/JumPi/cruft/ifconfig_wlan0.txt", "w")
file_ifconfig.writelines(myWlan0)
file_ifconfig.close()

# this will be for the VPN IP
#file_ifconfig = open("/home/pi/JumPi/cruft/ifconfig_vpn.txt", "w")
#file_ifconfig.writelines(myIPvpn)
Exemplo n.º 45
0
def is_ipv6_tunnel ():
	try:
		ifconfig(IPV6TUNNEL_INTERFACE)
		return True
	except Exception:
		return False
Exemplo n.º 46
0

# https://github.com/amoffat/sh
from sh import ifconfig
print(ifconfig("eth0"))

# import sh
# sh.pwd()
# sh.mkdir('new_folder')
# sh.touch('new_file.txt')
# sh.whoami()
# sh.echo('This is great!')
Exemplo n.º 47
0
def get_local_network_ip_addresses():
    ifconfig_result = sh.ifconfig()
    ifconfig_result_str = ifconfig_result.stdout.decode("utf-8")
    ips = re.findall(r'[0-9]+(?:\.[0-9]+){3}', ifconfig_result_str)
    return ips
Exemplo n.º 48
0
# sh is fa full-fledged subprocess interface for Python that allows you to call
# any program as if it were a function.

from __future__ import print_function

import sh

# NOTE here ifconfig() is not Python function, it is running the binary commands
# on your system dynamically by resolving your $PATH, much like Bash does.
# In this way, all the programs on your system are easily available to you from
# within Python.
print(sh.ifconfig('eth0'))

# same thing as above
# from sh import ifconfig
# print(ifconfig('eth0'))


# arguments
print(sh.ls('-l', '/'))

# glob expansion
print(sh.ls(sh.glob('*.py')))

# sub-commands
print(sh.git.status())
print(sh.git('status'))

# exit codes
output = sh.ls()
print(output.exit_code)
Exemplo n.º 49
0
        if check:
            logging.debug("Starting server...")
            with sudo:
                sed('-i', f's/#advertise_addr = "127.0.0.1"/advertise_addr = "{masterIp}"/', '/etc/consul.d/consul.hcl')
                consul('agent', "-config-file", "/etc/consul.d/consul.hcl", "-log-file", "/home/max/", _bg=True)
                #changing consul ip in nomad cfg
                sed('-i', f's/127.0.0.1/{masterIp}/', '/etc/nomad.d/nomad.hcl')
                server(_out=sys.stdout)
                sleep(10)
        else:
            check = checkConn(masterIp)
            if check:
                with sudo:
                    logging.debug("Starting client...")
                    #changing consul ip
                    sed('-i', f's/127.0.0.1/{masterIp}/', '/etc/nomad.d/nomad.hcl')
                    client('-servers', masterIp, _out=sys.stdout)
                    sleep(10)
            else:
                logging.debug("Something wrong...")
                print('Something wrong...')
                print('Try to start manualy...')
                print('Press alt+f2 to start inreractive prompt...')
                print('Here soe envs for you:')
                neofetch(_fg=True)
                ifconfig(_fg=True)
                sleep(120, _fg=True)
    except Exception as e:
        logging.exception('Here some shit happend:', e)
        sleep(10)
Exemplo n.º 50
0
 def getIP(self, device='eth0'):
     return ifconfig(device).split(' ')[28]
Exemplo n.º 51
0
import sh

print sh.ls('/Users/davidnuon')
print(sh.ifconfig("en0"))
Exemplo n.º 52
0
#Will automagically parse your ip and scan the network with nmap
from sh import nmap, ifconfig

ip = ifconfig("en1")
ip = str(ip.split("\n")[3].split("inet ")[1].split(" netmask")[0])

ip_range = ip.split(".")[0] + "." + ip.split(".")[1] + "." + ip.split(".")[2] + "." + "0/24"

print(nmap(ip_range))
Exemplo n.º 53
0
 def tearDown(self):
     if "testMacvlan" in ifconfig("-a"):
         self._macvlan.delete()
Exemplo n.º 54
0
#!/usr/bin/env python

import os,sys
import sh

print sh.ifconfig("eth0")

sh.firefox("google.com")


def is_ipv6_tunnel():
    try:
        ifconfig(IPV6TUNNEL_INTERFACE)
        return True
    except Exception:
        return False