用python获取windows或linux主机名的方法

来源:互联网 发布:淘宝卖steam游戏 编辑:程序博客网 时间:2024/06/05 18:37

http://tony413.iteye.com/blog/395177



通过python的os模块获取windows或者linux主机名的通用函数。

 

Python代码  收藏代码
  1. #!/usr/bin/env python  
  2. #coding=utf-8  
  3.   
  4. import os  
  5.   
  6. def hostname():  
  7.         sys = os.name  
  8.   
  9.         if sys == 'nt':  
  10.                 hostname = os.getenv('computername')  
  11.                 return hostname  
  12.   
  13.         elif sys == 'posix':  
  14.                 host = os.popen('echo $HOSTNAME')  
  15.                 try:  
  16.                         hostname = host.read()  
  17.                         return hostname  
  18.                 finally:  
  19.                         host.close()  
  20.         else:  
  21.                 return 'Unkwon hostname' 

0 0