python shell根据ip获取主机名代码示例
这篇文章里我们主要分享了python中shell 根据 ip 获取 hostname 或根据 hostname 获取 ip的代码,具体介绍如下。 笔者有时候需要根据hostname获取ip 方法1:利用 socket 模块 里的 gethostbyname 函数 代码如下,使用socket模块 >>> import socket >>> socket.gethostbyname("www.baidu.com") '61.135.169.125' >>> socket.gethostbyname("rs.xidian.edu.cn") '202.117.119.1' 方法2 利用 shell 中 hostname 命令 疑惑: 有时候socket不太稳定,有时候无法获取到 ip 具体原因带查明。 主要思想是在另一台机器上把 hostname 信息写到文件里,然后把文件拷到本机器上,读取文件里的 hostname 信息。 利用 plink 在远程ip机器上执行hostname > %s.hostname命令,将hostname 信息输出到文件 代码如下: def getHostName(ip): command = 'java -jar %s %s "hostname > %s.hostname"' %(remoteCmdLoca,ip,ip) result = subprocess.call(command,shell=True) command = '%s -q -r -pw passwd %s root@%s:/root' % (pscpLoca,pscpLoca,shell=True) command = '%s -q -r -pw passwd root@%s:/root/%s.hostname %s' %(pscpLoca,fileDir) result = subprocess.call(command,shell=True) fileName = fileDir + ip + '.hostname' readFile = open(fileName,'r') hostnameInfo = str(readFile.readline().strip('n')) readFile.close() subprocess.call('rm '+ fileName,shell=True) print "=========%s hostname is %s========" %(ip,hostnameInfo) return hostnameInfo 下面分享一则简单的windows下python 获取主机名的代码示例,我是win10系统,待会可以试试: 环境:windows10 64位 + python2.7 代码如下: import socket hostName = socket.gethostname() 运行结果如下: >> import socket >>> hostName = socket.gethostname() >>> print hostName LAPTOP-H7MGGAAT 总结 以上就是本文关于python shell根据ip获取主机名代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站: python自动裁剪图像代码分享 Python算法之图的遍历 如有不足之处,欢迎留言指出。感谢朋友们对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |