linux 使用shell脚本将行追加到/etc/hosts文件

pgky5nke  于 5个月前  发布在  Linux
关注(0)|答案(8)|浏览(113)

我有一个新的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

字符串
我希望它看起来像这样:

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


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

mi7gmzs6

mi7gmzs61#

请确保使用sed-i选项。

-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

字符串
否则,

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


会将该行附加到文件末尾,这样就可以按预期工作。

sh7euo9m

sh7euo9m2#

如果你在Mac上或者你需要sudo权限,试试这个:

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

字符串
它仍然会要求您输入密码。
另一种方式从@kainjow

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

pinkon5k

pinkon5k3#

插入/更新条目

如果你想使用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

字符串
该脚本旨在与OS X一起使用,但也可以在Linux上工作,只需稍作调整。

t9eec4r0

t9eec4r04#

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

字符串

62o28rlo

62o28rlo5#

我应该指出,sedstream 编辑器)实际上并不是用来编辑文件的,尽管它可以用来编辑文件。(Standard sed没有内置的机制来写入标准输出以外的内容。)一个更合适的工具是ed
下面的艾德脚本说“找到包含正则表达式/127.0.0.1/的行,并在下一行追加”(单独的句号告诉艾德停止追加)。

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

字符串
也就是说,你真的可以很简单地将这一行附加到/etc/hosts文件的 end

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

pdkcd3nj

pdkcd3nj6#

可以使用sed,例如:

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

字符串

8iwquhpp

8iwquhpp7#

我开发了一个用户友好的脚本,可以轻松地在主机文件中添加、删除和列出IP地址和主机名:

#!/bin/bash
# Created by Mohamad Hamouday
# Date: 2023-12-05
# Purpose: A script to add, remove, and list entries in the hosts file

# Function to add an entry to the hosts file
add_entry() {
    # Get user input for IP address and server name
    read -p "Enter IP address: " ip_address
    read -p "Enter server name: " server_name

    # Check if the input is not empty
    if [ -z "$ip_address" ] || [ -z "$server_name" ]; then
        echo "IP address and server name cannot be empty."
        exit 1
    fi

    # Append the entry to the hosts file
    echo "$ip_address $server_name" >> /etc/hosts

    echo "Entry added to /etc/hosts: $ip_address $server_name"
}

# Function to remove an entry from the hosts file
remove_entry() {
    # Get user input for IP address or server name to remove
    read -p "Enter IP address or server name to remove: " entry_to_remove

    # Check if the input is not empty
    if [ -z "$entry_to_remove" ]; then
        echo "Entry cannot be empty."
        exit 1
    fi

    # Check if the entry exists in the hosts file
    if grep -q "$entry_to_remove" /etc/hosts; then
        # Remove the entry from the hosts file using sed
        sed -i.bak -e "/$entry_to_remove/d" /etc/hosts

        echo "Entry removed from /etc/hosts: $entry_to_remove"
    else
        echo "Entry does not exist in /etc/hosts: $entry_to_remove"
    fi
}

# Function to list all active entries in the hosts file
list_entries() {
    echo "Non-commented entries in /etc/hosts:"
    grep -E -v '^\s*#' /etc/hosts
}

# Check if the script is executed with root privileges
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root."
   exit 1
fi

# Display menu for user choice
echo "1. Add entry"
echo "2. Remove entry"
echo "3. List entries"
read -p "Enter your choice (1, 2, or 3): " choice

case $choice in
    1)
        add_entry
        ;;
    2)
        remove_entry
        ;;
    3)
        list_entries
        ;;
    *)
        echo "Invalid choice. Exiting."
        exit 1
        ;;
esac

字符串
要执行它,只需运行:

sudo sh scriptname.sh

qfe3c7zg

qfe3c7zg8#

尝试使用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超级用户权限

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();
    }
}


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

相关问题