I'd like to replace one string in file with another, to be more specific, replace username:password entry in dovecot passwd file ( /etc/dovecot/passwd
) but only if record exists.
So, what I need:
sed
command- that does nothing if record does not exist (see dovecot passwd example)
- that replaces in file ( if there isn't very good reason for outputing to new file and moving new file to original )
Here is /etc/dovecot/passd
example:
johndoe@example.com:{CRAM-MD5}479375185777b7ba573747c111483bdd628332a70268ce283dc80bedd0f65988
janedoe@example.com:{CRAM-MD5}10b7176649d8bb3eb38f6b68a0c6c826ffab5656181821e598296ebd31e8f64f
and what I've tried so far (creates new file, output to new and mv
to original even if record does not exist)
#!/usr/bin/env php
<?php
$passwd_file = '/etc/dovecot/passwd';
$time = time();
$newtempfile = '/tmp/' . $time . 'dvctpwd';
/**
* $search generates replace target johndoe@example.com:{CRAM-MD5}479375185777b7ba573747c111483bdd628332a70268ce283dc80bedd0f65988
* if johndoe@example.com gives correct password to dovecot's doveadm pw -u johndoe@example.com -poldpassword
**/
$search = $argv[1] .':' . exec("doveadm pw -u " . $argv[1] . " -p" . $argv[2]);
/**
* $replace generates replace value johndoe@example.com:{CRAM-MD5}...
* i.e. scheme with new password
**/
$replace = $argv[1] .':' . exec("doveadm pw -u " . $argv[1] . " -p" . $argv[3]);
$command = <<<DD
sed -e "s|$search|$replace|" $passwd_file > $newtempfile && mv $newtempfile $passwd_file && echo "Password changed!\n";
DD;
$output = passthru($command);
echo $output . PHP_EOL;