获取以太网设备的永久地址

时间:2019-07-12 17:35:30

标签: linux python-3.x

我正在寻找一种在Python(3)中检索以太网设备的永久地址的方法。

我研究了多种方法来实现此目的:

  • 这里是netifaces,这是一个可以检索MAC地址的Python库。可悲的是,它无法获取设备的永久地址。这样就可以覆盖

  • 这里是python-ethtool。这可以实现我想要的功能,但已弃用并且无法在要开发的特定计算机上与Python3一起运行。

  • 然后,我当然可以从命令行(在Python中,使用子进程)调用import * as bcrypt from 'bcrypt'; import * as express from 'express'; import * as jwt from 'jsonwebtoken'; import User from 'users/user.interface'; import UserWithThatEmailAlreadyExistsException from '../exceptions/UserWithThatEmailAlreadyExistsException'; import WrongCredentialsException from '../exceptions/WrongCredentialsException'; import Controller from '../interfaces/controller.interface'; import DataStoredInToken from '../interfaces/dataStoredInToken'; import TokenData from '../interfaces/tokenData.interface'; import validationMiddleware from '../middleware/validation.middleware'; import CreateUserDto from '../users/user.dto'; import userModel from './../users/user.model'; import LogInDto from './logIn.dto'; class AuthenticationController implements Controller { public path = '/auth'; public router = express.Router(); private user = userModel; constructor() { this.initializeRoutes(); } private initializeRoutes() { this.router.post(`${this.path}/register`, validationMiddleware(CreateUserDto), this.registration); this.router.post(`${this.path}/login`, validationMiddleware(LogInDto), this.loggingIn); this.router.post(`${this.path}/logout`, this.loggingOut); } private registration = async (request: express.Request, response: express.Response, next: express.NextFunction) => { const userData: CreateUserDto = request.body; if ( await this.user.findOne({ email: userData.email }) ) { next(new UserWithThatEmailAlreadyExistsException(userData.email)); } else { const hashedPassword = await bcrypt.hash(userData.password, 10); const user = await this.user.create({ ...userData, password: hashedPassword, }); user.password = undefined; const tokenData = this.createToken(user); response.setHeader('Set-Cookie', [this.createCookie(tokenData)]); response.send(user); } } private loggingIn = async (request: express.Request, response: express.Response, next: express.NextFunction) => { const logInData: LogInDto = request.body; const user = await this.user.findOne({ email: logInData.email }); if (user) { const isPasswordMatching = await bcrypt.compare(logInData.password, user.password); if (isPasswordMatching) { user.password = undefined; const tokenData = this.createToken(user); response.setHeader('Set-Cookie', [this.createCookie(tokenData)]); response.send(user); } else { next(new WrongCredentialsException()); } } else { next(new WrongCredentialsException()); } } private loggingOut = (request: express.Request, response: express.Response) => { response.setHeader('Set-Cookie', ['Authorization=;Max-age=0']); response.sendStatus(200); } private createCookie(tokenData: TokenData) { return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn}`; } private createToken(user: User): TokenData { const expiresIn = 60 * 60; // an hour const secret = process.env.JWT_SECRET; const dataStoredInToken: DataStoredInToken = { _id: user._id, }; return { expiresIn, token: jwt.sign(dataStoredInToken, secret, { expiresIn }), }; } } export default AuthenticationController; ~~~ **posts.controller.ts** ~~~ import * as express from 'express'; import PostNotFoundException from '../exceptions/PostNotFoundException'; import Controller from '../interfaces/controller.interface'; import RequestWithUser from '../interfaces/requestWithUser.interface'; import authMiddleware from '../middleware/auth.middleware'; import validationMiddleware from '../middleware/validation.middleware'; import CreatePostDto from './post.dto'; import Post from './post.interface'; import postModel from './posts.model'; class PostsController implements Controller { public path = '/posts'; public router = express.Router(); private post = postModel; constructor() { this.initializeRoutes(); } private initializeRoutes() { this.router.get(this.path, this.getAllPosts); this.router.get(`${this.path}/:id`, this.getPostById); this.router .all(`${this.path}/*`, authMiddleware) .patch(`${this.path}/:id`, validationMiddleware(CreatePostDto, true), this.modifyPost) .delete(`${this.path}/:id`, this.deletePost) .post(this.path, authMiddleware, validationMiddleware(CreatePostDto), this.createPost); } private getAllPosts = async (request: express.Request, response: express.Response) => { const posts = await this.post.find(); response.send(posts); } private getPostById = async (request: express.Request, response: express.Response, next: express.NextFunction) => { const id = request.params.id; const post = await this.post.findById(id); if (post) { response.send(post); } else { next(new PostNotFoundException(id)); } } private modifyPost = async (request: express.Request, response: express.Response, next: express.NextFunction) => { const id = request.params.id; const postData: Post = request.body; const post = await this.post.findByIdAndUpdate(id, postData, { new: true }); if (post) { response.send(post); } else { next(new PostNotFoundException(id)); } } private createPost = async (request: RequestWithUser, response: express.Response) => { const postData: CreatePostDto = request.body; const createdPost = new this.post({ ...postData, authorId: request.user._id, }); const savedPost = await createdPost.save(); response.send(savedPost); } private deletePost = async (request: express.Request, response: express.Response, next: express.NextFunction) => { const id = request.params.id; const successResponse = await this.post.findByIdAndDelete(id); if (successResponse) { response.send(200); } else { next(new PostNotFoundException(id)); } } } export default PostsController; ~~~ 并读取输出。

我看过ethtool的代码,而我所需的信息似乎存在于名为perm_addr的struct dev领域:

ethtool -P

如何在Python中访问此信息?与打开子进程并调用ethtool相比,我更喜欢使用全Python解决方案。

1 个答案:

答案 0 :(得分:1)

可通过文件/sys/class/net/<iface>/address使用。文件/sys/class/net/<iface>/addr_assign_type表示地址的类型。

请参见https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net,然后在该文档中查找“永久”。