Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 5083  / 2 Years ago, thu, april 7, 2022, 10:48:26

I want to modify /etc/hosts (and later also hostname) via a script and ssh.
So I'm logged in via ssh and this works:



sudo nano /etc/hosts


It shows the remote hosts file in nano. However I was trying this (via commandline, but this should work in order to make it work in a script right?):



echo [mypassword] | sudo -S nano /etc/hosts


but get this output:



Recieved SIGHUP or SIGTERM

Buffer written to /etc/hosts.save


I just saw that this also happens with more simple text-files (e.g. test.txt). Any ideas how to fix this?



And yes, I am aware of the insecurity of the clear password. :)



Thanks in advance


More From » ssh

 Answers
5

What worked for me is writing in a temporary file and replacing /etc/hosts with it



#!/bin/bash

# $1: IP of the new host
# $2: name of the new host

# read current /etc/hosts int temp-file
cat /etc/hosts > tmphost
# add new entry to temp-file
echo "$1 $2" >> tmphost
# replace hosts file
sudo cp tmphost /etc/hosts
# remove temp-file
rm tmphost


like @Pasi suggested, this needs passwordless sudo


[#30259] Friday, April 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alkeake

Total Points: 467
Total Questions: 94
Total Answers: 126

Location: Tajikistan
Member since Tue, Jun 15, 2021
3 Years ago
;