I have to update a line on about 200 remote Linux servers.
Can someone please tell me if that't possible using ssh ?
Let's say I have 5 lines in the text file and I want to update a command on line 3 as illustrated below :
line 1
line 2
line 3 # I want to update this line
line 4
line 5
What command would I use remotely, using ssh, to get line 3 updated or add more text in it ?
Thanks.
There are a bunch of ways you can do this. The easiest way to modify a file is by using sed
. So if you want to modify line 3 in a certain way on each server, you could do something like this:
cat list-of-servers | xargs -I{} ssh {} sed -i -e '3s/line/ligne/' FILE
sed
is a standard Unix command, so it should be available. If you need something more complex, you can do it with perl -i
or ruby -i
, which are also good at this. A /usr/bin/perl
binary (with a subset of core Perl modules) will be available on all Debian and Ubuntu systems, since it's part of an essential package, but may not be available on Red Hat or CentOS systems.
If you really want to do it with Vim, you can; all of the colon commands are available in ex
, and you can use ex
to modify a file. Note that the normal mode commands are not usually available here. So you could write something like the following:
cat list-of-servers | \
xargs -I{} ssh {} 'echo '\''3s/line/ligne/ | wq'\'' | ex -s FILE'
In this case, you could just use double quotes instead of escaping single quotes, but in your case that might not be possible, so I've demonstrated how to nest single quotes, since that's tricky.
Note that ed
can also be used for this, but it's actually less common to find on servers than Vim since it's usually only installed as a dependency of patch
, whereas most servers will have some version of ex
and vi
installed for the benefit of the sysadmin.