python脚本获取服务器网卡的MAC地址和本机IP
#!/usr/bin/python
import fcntl,socket,struct
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ':'.join(['%02x' % ord(char) for char in info[18:24]])
def Get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('10.0.0.1', 8888))
ip = s.getsockname()[0]
finally:
s.close()
print(ip)
def get_hw_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(),0x8927,struct.pack('256s', ifname[:15]))
hwaddr = []
#print len(info)
for char in info[18:24]:
hdigit = '%02x' % struct.unpack('B',char)[0]
hwaddr.append(hdigit)
print(':'.join(hwaddr))
print(getHwAddr('eth1'))
Get_host_ip()
get_hw_address('eth1')
运行结果:
在Linux中,hwaddr代表硬件地址(Hardware Address),也被称为MAC地址(Media Access Control Address)。MAC地址是分配给网络设备(如网卡)的唯一标识符。它由六个十六进制数对表示,例如:00:1A:2B:3C:4D:5E
python实现配置网卡bond
思路:
1、将ifcfg-eth0 ifcfg-eth1 ifcfg-bond0文件打包成bond.tgz文件,拷贝到主机并解压,将原始的ifcfg-eth1文件mv到/tmp下
[root@szxhy-sys-dhcp00 bond-net]# cat ifcfg-eth0
DEVICE=eth0
TYPE=Ethernet
ONBOOT=yes
SLAVE=yes
MASTER=bond0
BOOTPROTO=none
[root@szxhy-sys-dhcp00 bond-net]# cat ifcfg-eth1
DEVICE=eth1
TYPE=Ethernet
ONBOOT=yes
SLAVE=yes
MASTER=bond0
BOOTPROTO=none
[root@szxhy-sys-dhcp00 bond-net]# cat ifcfg-bond0
DEVICE=bond0
TYPE=Ethernet
USERCTL=no
ONBOOT=yes
BONDING_OPTS="miimon=100 mode=4"
BOOTPROTO=static
IPADDR=
NETMASK=255.255.255.0
GATEWAY=
2、主要需要配置ifcfg-bond0文件,用函数实现获取本机ip和网关,并写入到ifcfg-bond0文件
3、重启服务
# --*-- coding:utf-8 --*--
import socket,struct,fcntl,sys
from commands import getoutput
import os
import subprocess
import urllib2
import sys
import time
from optparse import OptionParser
def exec_run(cmd):
stdoutls = []
def receive():
(stdout) = \
proc.communicate()
try:
for rcmd in cmd:
proc =subprocess.Popen(rcmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
while proc.returncode is None:
stdout = proc.communicate()
stdoutls.append(stdout)
except Exception,e:
print e
sys.exit(0)
finally:
return stdoutls
def Get_host_ip(): 获取本机的ip
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('10.0.0.1', 8888))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def get_gateway():
file = "/tmp/ifcfg-eth0"
with open(file) as f:
content = f.readlines()
if content:
for line in content:
if ("GATEWAY" in line):
return(line.replace("\n", ""))
def get_url():
os.chdir("/opt")
f = urllib2.urlopen("http://10.2.56.6/xhy_kubeinit/bond-net.tgz")
data = f.read()
with open("bond-net.tgz", "wb") as code:
code.write(data)
exec_run(["tar zxvf bond-net.tgz"])
def set_info():
if os.path.exists("/etc/sysconfig/network-scripts/ifcfg-eth0"):
os.chdir("/opt/bond-net")
exec_run(["mv /etc/sysconfig/network-scripts/ifcfg-eth0 /tmp","mv * /etc/sysconfig/network-scripts/"])
getoutput("sed -i 's@IPADDR=@IPADDR=%s@g' /etc/sysconfig/network-scripts/ifcfg-bond0" % (Get_host_ip()))
getoutput("sed -i 's@GATEWAY=@GATEWAY=%s@g' /etc/sysconfig/network-scripts/ifcfg-bond0" % (get_gateway()))
os.system("service network restart")
else:
print("no such file")
sys.exit(0)
if __name__ == '__main__':
set_info()
socket函数
s.connect(address) 连接到address处的套接字。一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。
s.getsockname() 返回套接字自己的地址。通常是一个元组(ipaddr,port)
urllib模块urlopen()函数
Python urllib 库提供了一个从指定的 URL 地址获取网页数据,然后对其进行分析处理,获取想要的数据。
urlopen(url, data=None, proxies=None)
f = urllib2.urlopen("http://10.2.56.6/xhy_kubeinit/bond-net.tgz")
参数url表示远程数据的路径,一般是网址;
参数data表示以post方式提交到url的数据(玩过web的人应该知道提交数据的两种方式:post与get);
参数proxies用于设置代理。
urlopen返回 一个类文件对象(fd),它提供了如下方法:
read() , readline() , readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样;
info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息(header)
getcode():返回Http状态码。如果是http请求,200表示请求成功完成;404表示网址未找到;
geturl():返回请求的url;
os.system
system函数可以将字符串转化成命令在服务器上运行;
Subprocess.run
import subprocess
import shlex
# process=subprocess.run(["date"])
# print(process)
# process=subprocess.run(["date","-y"])
# print(process)
# process=subprocess.run(shlex.split("date -y"))
# print(process)
#
#
# process=subprocess.run(shlex.split("date -y"),check=True) ##执行失败就跳出错误,而不是继续运行
# print(process)
# process=subprocess.run(shlex.split("echo 'hello world'"))
# print(process)
# process=subprocess.run(shlex.split("date +%D"),capture_output=True)
# print(process)
# print(process.stdout.decode())
# process=subprocess.run(shlex.split("python ask.py"),capture_output=True,input="yes".encode())
# print(process)
# print(process.stdout.decode())
Subprocess.popen
import subprocess
import shlex
process=subprocess.Popen(shlex.split("python ask.py"),stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
print('next line') #直接输出,Popen不会阻塞,run方法会阻塞
print(process)
process.stdin.write('yes\n'.encode())
process.stdin.flush()
print(process.stdout.read())