使用python更改Linux主机名

2024-04-24 10:21:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过让python程序从一个文件中随机选择一个名称,然后将其设置为主机名来更改linux主机名。只有当随机数字值为1时,代码才起作用。我做错什么了?我使用的代码如下。在

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

Tags: 文件代码nameimport程序名称oslinux
1条回答
网友
1楼 · 发布于 2024-04-24 10:21:59

random模块提供从序列中选择随机元素的函数:

name = random.choice(contents)

我想这正是你想要的。此外,它还有一个优点,如果contents是空的,那么将抛出一个异常。在


更新:

在传递过程中,您不需要调用rnd.close(),因为您在第一时间打开文件时使用的是上下文管理器(with open(...) as rnd:),当您离开with子句的作用域时,它将被自动调用。在

相关问题 更多 >