Append line to /etc/hosts file with shell script

前端 未结 7 1817
春和景丽
春和景丽 2021-01-30 08:41

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/ho

7条回答
  •  我在风中等你
    2021-01-30 09:04

    try this with root access.

     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

    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

提交回复
热议问题