Linux 使用 shell 脚本将行附加到 /etc/hosts 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19339248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:04:07  来源:igfitidea点击:

Append line to /etc/hosts file with shell script

linuxbashshellubuntused

提问by Stephen Howells

I have a new Ubuntu 12.04 VPS. I am trying to write a setup script that completes an entire LAMP installation. Where I am having trouble is appending a line to the /etc/hostsfile. My current hosts file looks like this:

我有一个新的 Ubuntu 12.04 VPS。我正在尝试编写一个安装脚本来完成整个 LAMP 安装。我遇到问题的地方是在/etc/hosts文件中附加一行。我当前的主机文件如下所示:

127.0.0.1       localhost Venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

I would like it to look like this:

我希望它看起来像这样:

127.0.0.1       localhost Venus
192.241.xx.xx  venus.example.com venus

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

I have tried a variety of sedcommands using the append (\a) command. For some reason Ubuntu either just echoes the contents of the hostsfile in terminal or does nothing at all. How would I properly inject the second line into the file with a bash script?

我已经sed使用 append ( \a) 命令尝试了各种命令。出于某种原因,Ubuntu 要么只是hosts在终端中回显文件的内容,要么什么都不做。如何使用 bash 脚本将第二行正确注入文件?

采纳答案by damienfrancois

Make sure to use the -ioption of sed.

确保使用 的-i选项sed

-i[SUFFIX], --in-place[=SUFFIX]
  edit files in place (makes backup if extension supplied)

sed -i "2i192.241.xx.xx  venus.example.com venus" /etc/hosts

Otherwise,

除此以外,

echo "192.241.xx.xx  venus.example.com venus" >> /etc/hosts

would append the line at the end of the file, which could work as you expect.

将在文件末尾附加该行,这可以按您的预期工作。

回答by Vladimir Dimitrov

echo "127.0.0.1 localhost `hostname`">./temp_hosts
echo "192.241.xx.xx  venus.example.com">>./temp_hosts
cat /etc/hosts |tail -n +2 >>./temp_hosts
cat ./temp_hosts > /etc/hosts
rm ./temp_file

回答by kojiro

I should point out that sed(the streameditor) is not actually intended for editing files, although it can be used to do that. (Standard seddoesn't have a built-in mechanism for writing to other than standard output.) A more appropriate tool would be ed.

我应该指出sed编辑器)实际上并不用于编辑文件,尽管它可以用来做到这一点。(标准 sed没有用于写入标准输出以外的内置机制。)更合适的工具是ed.

The following ed script says "find the line containing the (admittedly sloppy) regular expression /127.0.0.1/ and append at the next line." (The lone period tells ed to stop appending.)

下面的 ed 脚本说“找到包含(公认的草率)正则表达式 /127.0.0.1/ 的行并附加到下一行。” (单独的句点告诉 ed 停止追加。)

ed /etc/hosts <<-'EOF'
    /127.0.0.1/a
    192.241.xx.xx  venus.example.com
    .
    wq
EOF

That said, you can really just append this line to the endof your /etc/hosts file very trivially:

也就是说,您真的可以非常简单地将此行附加到/etc/hosts 文件的末尾

echo '192.241.xx.xx  venus.example.com' >> /etc/hosts

回答by Jsonras

If your in mac or you need sudo permission to this try this:

如果您在 mac 中或者您需要 sudo 权限,请尝试以下操作:

sudo -- sh -c -e "echo '192.34.0.03   subdomain.domain.com' >> /etc/hosts";

It will still ask you for password.

它仍然会要求您输入密码。

alternative way from @kainjow

来自@kainjow的替代方式

echo '192.34.0.03 subdomain.domain.com' | sudo tee -a /etc/hosts

回答by brismuth

Insert/Update Entry

插入/更新条目

If you want to programmatically insert/update a hosts entry using bash, here's a script I wrote to do that:

如果你想使用 bash 以编程方式插入/更新主机条目,这是我写的一个脚本:

#!/bin/bash

# insert/update hosts entry
ip_address="192.168.x.x"
host_name="my.hostname.example.com"
# find existing instances in the host file and save the line numbers
matches_in_hosts="$(grep -n $host_name /etc/hosts | cut -f1 -d:)"
host_entry="${ip_address} ${host_name}"

echo "Please enter your password if requested."

if [ ! -z "$matches_in_hosts" ]
then
    echo "Updating existing hosts entry."
    # iterate over the line numbers on which matches were found
    while read -r line_number; do
        # replace the text of each line with the desired host entry
        sudo sed -i '' "${line_number}s/.*/${host_entry} /" /etc/hosts
    done <<< "$matches_in_hosts"
else
    echo "Adding new hosts entry."
    echo "$host_entry" | sudo tee -a /etc/hosts > /dev/null
fi

The script is intended for use with OS X but would work on linux as well with minor tweaking.

该脚本旨在与 OS X 一起使用,但也可以在 linux 上使用,并稍作调整。

回答by crackerHyman

you can use sed, like:

您可以使用 sed,例如:

sed '/Venus/ a\
192.241.xx.xx venus.example.com venus' /etc/hosts

sed '/Venus/ a\
192.241.xx.xx venus.example.com venus' /etc/hosts

回答by sanjay

try this with root access.

用 root 访问试试这个。

 public void edithost() {
    sudo("echo " + "192.168.43.1     www.openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.43.1  openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.2.144  www.openrap.com openrap" + " >> /etc/hosts");
    sudo("echo " + "192.168.2.144  openrap.com openrap" + " >> /etc/hosts");
}

sudo for super user permission

sudo 获得超级用户权限

public static void sudo(String... strings) {
    try {
        Process su = Runtime.getRuntime().exec("su");
        DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

        for (String s : strings) {
            outputStream.writeBytes(s + "\n");
            outputStream.flush();
        }

        outputStream.writeBytes("exit\n");
        outputStream.flush();
        try {
            su.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

this will append the lines to hosts in the android

这会将行附加到 android 中的主机