GithubHelp home page GithubHelp logo

hostile's Introduction

hostile ci npm downloads javascript style guide

Simple, programmatic /etc/hosts manipulation (in node.js)

hostile

install

npm install hostile

usage

If you use OS X or Linux, this module assumes your hosts file is at /etc/hosts. On Windows, it assumes your hosts file is at C:/Windows/System32/drivers/etc/hosts.

Commands that modify the hosts file require root privileges.

list all host file records

hostile list

set a domain in the hosts file

hostile set [ip] [host]

examples:

hostile set localhost domain.com
hostile set 192.168.33.10 domain.com

remove a domain from the hosts file

hostile remove [host]

example:

hostile remove domain.com

load a set of hosts from a file

hostile load [file_path]

hosts.txt

# hosts.txt
127.0.0.1 github.com
127.0.0.1 twitter.com

example:

hostile load hosts.txt

unload [remove] a set of hosts from a file

hostile unload [file_path]
# hosts.txt
127.0.0.1 github.com
127.0.0.1 twitter.com

example:

hostile unload hosts.txt

methods

Commands that modify the hosts file require root privileges.

I wouldn't recommend running your production node server with admin privileges unless you downgrade to a normal user with process.setuid(id) before you start accepting requests.

All methods have sync versions. Just omit the callback parameter.

add a rule to /etc/hosts

var hostile = require('hostile')
hostile.set('127.0.0.1', 'peercdn.com', function (err) {
  if (err) {
    console.error(err)
  } else {
    console.log('set /etc/hosts successfully!')
  }
})

If the rule already exists, then this does nothing.

remove a rule from /etc/hosts

hostile.remove('127.0.0.1', 'peercdn.com', function (err) {
  if (err) {
    console.error(err)
  } else {
    console.log('set /etc/hosts successfully!')
  }
})

If the rule does not exist, then this does nothing.

get all lines in /etc/hosts

// If `preserveFormatting` is true, then include comments, blank lines and other
// non-host entries in the result
var preserveFormatting = false

hostile.get(preserveFormatting, function (err, lines) {
  if (err) {
    console.error(err.message)
  }
  lines.forEach(function (line) {
    console.log(line) // [IP, Host]
  })
})

get all lines in any file

// If `preserveFormatting` is true, then include comments, blank lines and other
// non-host entries in the result
var preserveFormatting = false

hostile.getFile(file_path, preserveFormatting, function (err, lines) {
  if (err) {
    console.error(err.message)
  }
  lines.forEach(function (line) {
    console.log(line) // [IP, Host]
  })
})

contributors

license

MIT. Copyright (c) Feross Aboukhadijeh.

hostile's People

Contributors

carlsorenson avatar d-asensio avatar feross avatar greenkeeper[bot] avatar jhermsmeier avatar leftstick avatar ljharb avatar morriswchris avatar morsdyce avatar unilynx avatar xiaojue avatar yorkie avatar zmillman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hostile's Issues

completion does not work

I'm trying to have the completion into my zsh command line, but the instructions on the readme don't work.

I couldn't find any code related to completions on this repository also.

Is this implementend on the npm package? If so which version?

Please update the readme to reflect the current status.

Removing hostnames doesnt work

From batch nothing happens from nodeJS-App it messes up the file around the entry that should be deleted (missing linebrakes). I'm on rapsbian.

Code I'm using

var preserveFormatting = false
hostile.get(preserveFormatting, function (err, lines) {
    if (err) {
        console.error('getting lines failed: ' + err.message)
    }
    lines.forEach(function (line) {
        console.log("found line with ip=" + line[0] + " and entry=" + line[1]);
        if (line[0] == "127.0.1.1")
        {
            console.log("removing line with ip=" + line[0] + " and entry=" + line[1]);
            hostile.remove(line[0], line[1] , function (err) {
                if (err) {
                    console.error('removing etc/hosts/ failed: ' + err)
                } else {
                    console.log('removed /etc/hosts successfully!')
                }
            })
        }
    })
})

Support file parsing

Support the ability to load and unload hosts to /etc/hosts given a file of hosts

I.E.

127.0.0.1  github.com
127.0.0.1  twitter.com

Example using sudo

Is there an example of a node script that calls hostile using sudo? I've tried child_process.spawn() without success. Do you know of a way to achieve this without manually configuring OS files (chmod, etc.). Thanks

Add TypeScript Typings

Would love to see typings added to this repository or to DefinitelyTyped for TypeScript users.

I'm happy to advise & review if it's at all helpful/required.

❀️

Requesting a Backup Feature Request

The ability to backup a host file to a given name and then revert it back when you are done.

A person would make changes to the host file using this and then revert it back to the original file after its fully completed.

Are your writes atomic?

Hi,

I hosed my /ets/hosts file after using hostile in combination with async.parallel:

    async.parallel [
      (cb) ->
        exe "sudo hostile set 127.0.1.1 api2-vbox.example.com", cb
      (cb) ->
        exe "sudo hostile set 127.0.1.1 tmp-vbox.example.com", cb
      (cb) ->
        exe "sudo hostile set 127.0.1.1 worker-vbox.example.com", cb
      (cb) ->
        exe "sudo hostile set 127.0.1.1 vbox.example.com", cb
    ], callback

Are you using something like https://github.com/npm/fs-write-stream-atomic to make sure writes are atomic?

(I could easily recover, but others might have bigger problems - and node makes it pretty easy to have things going on in parallel ofc)

Bug: batch set

import hostile from 'hostile';
import { promisify } from 'util';

const hostileSet = promisify(hostile.set);

Promise.all([
  hostileSet('1.2.3.4', 'test1'),
  hostileSet('1.2.3.5', 'test2'),
  hostileSet('1.2.3.4', 'test1'),
  hostileSet('1.2.3.4', 'test3')
]).then(console.log);
// [ undefined, undefined, undefined, undefined ]

in host file:

1.2.3.4 test1

only add one line


import hostile from 'hostile';
import sleep from 'sleep-promise';
import { promisify } from 'util';

const hostileSet = promisify(hostile.set);

Promise.all([
  (async () => {
    await sleep(200);
    await hostileSet('1.2.3.4', 'test1');
  })(),
  (async () => {
    await sleep(200);
    await hostileSet('1.2.3.5', 'test2');
  })(),
  (async () => {
    await sleep(200);
    await hostileSet('1.2.3.4', 'test1');
  })(),
  (async () => {
    await sleep(200);
    await hostileSet('1.2.3.4', 'test3');
  })()
]).then(console.log);
// [ undefined, undefined, undefined, undefined ]

in host file:

1.2.3.4 test1

only add one line

An in-range update of standard is breaking the build 🚨

Version 12.0.0 of standard was just published.

Branch Build failing 🚨
Dependency standard
Current Version 11.0.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

standard is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 91 commits.

  • ff1a156 authors
  • 17727fc 12.0.0
  • bdbd248 changelog
  • 3db3a62 https
  • cf1802c eslint-plugin-standard ~4.0.0
  • 7d779b8 eslint-plugin-import ~2.14.0
  • 66f676b eslint ~5.4.0
  • 3933c6b Use npm versions of eslint shared configs
  • c00dc66 Use ~ for eslint dep
  • 588d5ab Add links to French README translation!
  • aee57b4 ESLint 5
  • c89d5c7 Merge pull request #1145 from theo4u/patch-1
  • 6477dbf Merge pull request #1184 from standard/greenkeeper/babel-eslint-9.0.0
  • 8792b9b Merge pull request #1180 from standard/greenkeeper/eslint-plugin-promise-4.0.0
  • ff070b8 Merge branch 'master' into greenkeeper/eslint-plugin-promise-4.0.0

There are 91 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

DOesnt work

Im running in admin shell but still getting eperm for .set methods. Listing works but writing doesnt.(windows)

Add tests

  • Use sample, fake hosts file
  • Use tape

Multiple entries not being added

Hi,

I'm not sure why this does not work but only the last entry actually gets added.

var currentPrototypes = fs.readdirSync(path.join(__dirname, '..', 'prototypes'));
currentPrototypes.forEach(function(prototype){
    console.log(prototype);
    hostile.set('127.0.0.1', prototype + '.ux.localhost', function (err) {
      if (err) {
        console.error(err);
      } else {
        console.log('set /etc/hosts successfully!');
      }
    });
});

Where currentPrototypes is a list of subfolders in the prototypes directory.

Also, if I run it again, it adds another identical entry where it should fail silently.

Any ideas?

Thank you,

Suggestion - dry run or check mode that tells you if changes need to be made

We use hostile as part of our dev workflow, and we have to run it with sudo so that it has the right permissions to do its bit. However, most of the time there's nothing for it to do, and we end up being prompted for our password even when there's nothing to be done.

We've worked around this by doing a host lookup to check all our hosts before invoking hostile with a sudo. I feel like hostile would be in a better position to check if it has something to do.

I'm happy to submit a Pull Request if you like.

Line comments cause entry to be ignored

Hello,

When running $ hostile list, valid entries which contain comments are ignored. For example,

127.0.0.1 github.com
127.0.0.1 ponyfoo.com #ponyfoo

will only notice github.com.

Setting a new host removes line comments from existing hosts

Given a hosts file like:

127.0.0.1        localhost
10.0.0.100     otherhost # some comment

Adding a new configuration with hostile set 127.0.0.1 newhost adds the new host but removes the line comment from the existing entry, leaving

127.0.0.1        localhost
10.0.0.100     otherhost
127.0.0.1        newhost

I would expect this tool to leave existing line comments intact. I have other tooling which depends on their presence.

Attempting to set new line gives back permission denied error

I am trying to set a line of code to the hosts file but I keep on getting this error:

Error: EACCES: permission denied, open '/etc/hosts

How do I give permission to edit the hosts file using the code:

hostile.set('127.0.0.1', 'example.com', function (err) {
if (err) {
console.error(err);
} else {
console.log('set /etc/hosts successfully!');
}
})

Bug adding hosts to host file

Hello,

I'm trying to add some host like this:

project.hosts.forEach(function (mapping) {
    hostile.set(mapping.ip, mapping.hostname, function (err) {
        if (err) {
            console.error(err)
        } else {
            console.log('Successfully added:', mapping.ip, mapping.hostname);
        }
    });
});

It outputs:

[09:01:27] Starting 'apply-hosts'...
Successfully added: 127.0.0.1 brian.example.com
Successfully added: 127.0.0.1 allan.example.com

but only brian.example.comis added to the host file. I'm running windows 8.1.

http vs https in static html

Hello!

The problem:

  • set no https listener or configuraiton, direct http in a simple local server.
  • set a name with hostile
  • set a public folder for html files
  • put in 2 html files with 2 links

result: When you have a static html in a public folder and click on simple link, link go ever in https and not http.

heeeelp XD

-this is an amazing plugin, i love you, it work also in linux?-

Support for setting Windows hosts within WSL

Provided an elevated shell session is used, it is possible to modify the Windows hosts file within WSL (Windows Subsystem for Linux). It would be useful if hostile supported working with Windows hosts within WSL.

An example of adding hosts;

declare -a LOCAL_DOMAINS=("some-site.test" "api.some-site.test")

# add Domains to hosts
for domain in ${LOCAL_DOMAINS[@]}
do
    if grep -q microsoft /proc/version; then
        declare -a windowsHosts=$(wslpath -u -a C:\\Windows\\System32\\drivers\\etc\\hosts);
        if ! grep --quiet ${domain} $windowsHosts; then
            echo "Adding ${domain} to Windows hosts file..."
            echo "127.0.0.1 ${domain}" | tee -a $windowsHosts || { echo >&2 "Failed to add entry to hosts file - ${domain}, try running WSL terminal instance as admin" ; exit 1; }
        fi
    fi
done

With standard host drive mount configuration, wslpath -u -a C:\\Windows\\System32\\drivers\\etc\\hosts returns /mnt/c/Windows/System32/drivers/etc/hosts. The resolved path should be treated as case sensitive.

Thoughts?

Last hostname entry doesn't work on Alpine Linux

I'm using hostile to add an IP to the hosts file to make it easy to set up our testing flow. We're using a mix of Mac, Windows, & Alpine Linux servers. This works fine on Mac/Windows, but not on Alpine Linux, which is within Docker, so I'm not entirely sure whether the trouble is caused by Docker or Alpine Linux.

Here's the (simplified) code that I'm using:

var hostile = require('hostile');
hostile.set('127.0.0.1', SERVER_URL, function (err) {
    console.log('Set up /etc/hosts');
});

Here's before/after screenshots of my /etc/hosts file:

Before
screen shot 2016-07-14 at 17 24 16

After
screen shot 2016-07-14 at 17 16 52

It looks like the last line break is inserted before the last entry and not after. I've tried manually updating the file, by adding a line break after the last entry, which will make it work in all environments.

Hostile doesn't fail gracefully

Hi there,

A few of our engineers have found that (despite running in admin) they get an access denied error when running hostile.

Error: EPERM: operation not permitted, open 'C:\Windows\System32\drivers\etc\hosts'. Are you running as root?

Interestingly, Notepad++ run as admin can save and modify the file with no issue. This doesn't occur for all the machines so I imagine there's something machine specific causing the problem.

The bug we've noticed is that hostile doesn't gracefully recover from this. After getting the error, the hosts file is completely empty.

Has anyone experienced this?

Thanks
Mason

Which operating systems is this compatible with?

Can the README.md be extended to note which operating systems this works under? _n_x, OSX and windows all have the hosts file in a different place, and OSX and windows require admin privileges to edit the file, so if this module means node apps need to be run with admin privileges, that is a massively important bit of information to list in the readme.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.