简体   繁体   English

使用python更改Linux主机名

[英]Changing the Linux Hostname with python

I am trying to change the linux hostname by having a python program randomly select a name from a file then setting that as the host name. 我试图通过让python程序从文件中随机选择一个名称然后将其设置为主机名来更改linux主机名。 The code works only when the random digit value is 1. What am I doing wrong? 该代码仅在随机数值为1时有效。我做错了什么? The code I am using is below. 我正在使用的代码如下。

import random
import os
import socket

contents=[]

with open("/root/Desktop/names.txt") as rnd:
    for line in rnd:
        line=line.strip()
        contents.append(line)
name = contents[random.randint(0,len(contents)-1)]
rnd.close()
name = "hostname -b "+name
os.system(name)
hostname = socket.gethostname()
print "Hostname:", hostname

The random module provides a function to select a random element from a sequence: random模块提供从序列中选择随机元素的功能:

name = random.choice(contents)

That does exact what you want, I think. 我认为这确实符合您的要求。 Furthermore, it has the advantage that if contents is empty for whatever reason, an exception will be thrown. 此外,它的优点是,如果contents因任何原因而为空,则会抛出异常。


Update: 更新:

In passing, you don't need to call rnd.close() since you are using a context manager when you open the file in the first place ( with open(...) as rnd: ) - it will be called automatically when you leave the scope of the with clause. 顺便说一下,你不需要调用rnd.close()因为你在第一个位置打开文件时使用了一个上下文管理器( with open(...) as rnd: - 当它被自动调用时你离开了with子句的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM