2012-07-30 42 views
1

給出一個配置文件,如sshd_config中:編輯線的配置文件從外殼

[...] 
IgnoreRhosts yes 
RhostsRSAAuthentication no 
HostbasedAuthentication no 
PermitEmptyPasswords no 
ChallengeResponseAuthentication no 
PasswordAuthentication yes 
X11Forwarding yes 
X11DisplayOffset 10 
[...] 

我想編寫一個命令,讓我樹立了配置設置。例如,我想將PasswordAuthentication設置爲no。如果條目已經存在,我想替換它,如果不存在,我想將它添加到文件的末尾。

我該如何從shell中做到這一點?

+0

你可能尋找['awk'](http://linux.die.net/man/1/awk )。 – 2012-07-30 12:09:47

回答

2

您可以使用awk來做到這一點。這裏是一個腳本,我寫道:

$ cat setProp.sh 
#!/bin/sh 

propFile=$1 
key=$2 
value=$3 

awk -v "key=$key" -v "value=$value" '{ 
    if($1==key) { 
     found=1 
     print $1" "value 
    } else { 
     print 
    } 
} 
END { 
    if(!found) print key" "value 
}' $propFile 

用法:

$ setProp.sh myfile RhostsRSAAuthentication no 
IgnoreRhosts yes 
RhostsRSAAuthentication no 
HostbasedAuthentication no 
PermitEmptyPasswords no 
ChallengeResponseAuthentication no 
PasswordAuthentication yes 
X11Forwarding yes 
X11DisplayOffset 10 
0
awk '{if($1~/PasswordAuthentication/){flag=1;if($2~/yes/)$2="no";print $0}else{print}} END{if(flag!=1)print "PasswordAuthentication no"}' temp